Home >Backend Development >PHP Tutorial >Why Does PHP's `file_get_contents` Fail to Fetch External URLs, and How Can I Fix It?

Why Does PHP's `file_get_contents` Fail to Fetch External URLs, and How Can I Fix It?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 20:07:12771browse

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:

  • allow_url_fopen: Ensure this setting is enabled (set to 1 or On). It controls whether PHP can access URLs using the file system functions.
  • allow_url_include: Disable this setting (set to 0 or Off) if you want to prevent PHP from including remote URLs directly.
  • file_get_contents.allow_url_fopen: If present, this setting overrides allow_url_fopen specifically for file_get_contents. Make sure it's enabled (set to 1).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn