Home > Backend Development > PHP Tutorial > Why is `file_get_contents()` Failing to Retrieve External URLs on This Server?

Why is `file_get_contents()` Failing to Retrieve External URLs on This Server?

Patricia Arquette
Release: 2024-12-13 14:57:11
Original
830 people have browsed it

Why is `file_get_contents()` Failing to Retrieve External URLs on This Server?

File_get_contents Issue with External URLs on Specific Server

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:

  1. 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
    Copy after login

    If it is set to Off, change it to On.

  2. 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
    Copy after login

    If it is set to Off, change it to On.

  3. 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');
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template