Problem:
When using the PHP function file_get_contents() to retrieve the contents of an external URL on a specific server, an empty result is returned. However, the function works correctly when used locally or when accessing internal URLs on the same server.
Possible Cause:
The issue is likely related to a PHP.ini configuration setting.
Solution:
To determine which PHP.ini configuration is causing the problem, follow these steps:
Check the allow_url_fopen setting: This setting controls whether PHP can access external URLs through the fopen family of functions. If it is set to Off, file_get_contents() will not be able to retrieve content from external URLs.
Check the PHP.ini file for the following line:
allow_url_fopen = Off
If it is set to Off, change it to On.
Check the allow_url_include setting: This setting controls whether PHP can include external URLs in scripts. If it is set to Off, file_get_contents() may not be able to retrieve content from external URLs.
Check the PHP.ini file for the following line:
allow_url_include = Off
If it is set to Off, change it to On.
Use an alternative function: If the above settings do not solve the issue, you can use alternative functions to mimic the behavior of file_get_contents(). One such function is curl_init():
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 is `file_get_contents()` Failing to Retrieve External URLs on This Server?. For more information, please follow other related articles on the PHP Chinese website!