PHP file_get_contents() not working

后端 未结 6 969
情书的邮戳
情书的邮戳 2020-12-18 09:03

Can anyone explain why the following code returns a warning:


I get a Warnin

相关标签:
6条回答
  • 2020-12-18 09:12

    you can try using single quotes like this:

    file_get_contents('http://google.com');
    
    0 讨论(0)
  • 2020-12-18 09:26

    As an alternative, you can use cURL, like:

    $url = "http://www.google.com";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    echo $data;
    

    See: cURL

    0 讨论(0)
  • 2020-12-18 09:28

    Try this function in place of file_get_contents():

    <?php
    
    function curl_get_contents($url)
    {
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
    
        $data = curl_exec($ch);
        curl_close($ch);
    
        return $data;
    }
    

    It can be used just like file_get_contents(), but uses cURL.

    Install cURL on Ubuntu (or other unix-like operating system with aptitude):

    sudo apt-get install php5-curl
    sudo /etc/init.d/apache2 restart
    

    See also cURL

    0 讨论(0)
  • 2020-12-18 09:28

    If you run this code:

    <?php
        print_r(stream_get_wrappers());
    ?>
    

    in http://codepad.org/NHMjzO5p you see the following array:

    Array
    (
        [0] => php
        [1] => file
        [2] => data
    )
    

    Run the same code in on Codepad.Viper - http://codepad.viper-7.com/lYKihI you will see that the http stream has been enabled thus file_get_contents not working in codepad.org.

    Array 
    ( 
        [0] => https 
        [1] => ftps 
        [2] => compress.zlib 
        [3] => php 
        [4] => file 
        [5] => glob 
        [6] => data 
        [7] => http 
        [8] => ftp 
        [9] => phar 
    )
    

    If you run your question code above in Codepad.Viper then it open the google page. The difference thus is the http stream that is disable in your CodePad.org and enabled in CodePad.Viper.

    To enable it read the following post How to enable HTTPS stream wrappers. Alternatively use cURL.

    0 讨论(0)
  • 2020-12-18 09:32

    This is almost certainly caused by the config setting that allows PHP to disable the ability to open URLs using the file handling functions.

    If you can change you PHP.ini, try switching on the allow_url_fopen setting. See also the man page for fopen for more in (the same restictions affect all file handling functions)

    If you can't switch on the flag, you'll need to use a different method, such as Curl, to read your URL.

    0 讨论(0)
  • 2020-12-18 09:34

    Try a trailing slash after the hostname.

    <?php
        echo file_get_contents("http://google.com/");
    ?>
    
    0 讨论(0)
提交回复
热议问题