Resolving PHP file_get_contents() “HTTP Request Failed” Error
When attempting to utilize file_get_contents() to retrieve content from a specified URL, users may encounter the error: "Warning: file-get-contents() failed to open stream: HTTP request failed! HTTP/1.1 202 Accepted." This error arises when the HTTP request cannot be successfully executed.
To address this issue, an alternative approach is to employ the cURL extension. cURL offers greater control over HTTP requests and allows for additional configuration options. Here's a modified code snippet using cURL:
<?php $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, 'http://###.##.##.##/mp/get?mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv'); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name'); $query = curl_exec($curl_handle); curl_close($curl_handle); ?>
In this modified version, we leverage cURL functions to initiate the HTTP request. We define a curl handle and set various options:
By utilizing cURL, we gain finer control over the HTTP request and can effectively resolve the "HTTP request failed" error encountered with file_get_contents().
The above is the detailed content of Why Does file_get_contents() Fail and How Can cURL Fix 'HTTP Request Failed' Errors?. For more information, please follow other related articles on the PHP Chinese website!