Home >Backend Development >PHP Tutorial >Why Does PHP's `file_get_contents` Fail to Fetch External URLs, and How Can I Fix It?
PHP file_get_contents Fails to Fetch External URL Contents
When attempting to utilize the PHP file_get_contents function to retrieve the contents of a remote URL (e.g., file_get_contents('http://example.com')), you encounter an issue where the result is consistently empty on a specific server. However, accessing local files using the same function returns expected results.
Probable Cause in php.ini
The empty result is likely attributed to a configuration setting in the PHP php.ini file.
Solution
To resolve this issue, check for the following specific configurations within the php.ini file:
If these settings are not set as described, adjust them accordingly and restart the PHP server to apply the changes.
Alternative Approach
If you cannot modify the php.ini settings or prefer a different approach, you can mimic the behavior of file_get_contents using cURL, as shown in the following example:
function get_content($URL){ $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $URL); $data = curl_exec($ch); curl_close($ch); return $data; } echo get_content('http://example.com');
The above is the detailed content of Why Does PHP's `file_get_contents` Fail to Fetch External URLs, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!