PHP file_get_contents does not work on localhost

前端 未结 7 1184
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 21:48

I am working on my website from localhost (http://172.16.65.1/) a MAMP server on OSX.
I want to load some JSON from Google and some simple tests show me I have a probl

相关标签:
7条回答
  • 2020-12-01 22:14

    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-01 22:14

    I was using file_get_contents this way: file_get_contents("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=".$screenname."&count=5");

    And that was not working, so I changed https to http and after that it is working well.

    file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=".$screenname."&count=5");
    
    0 讨论(0)
  • 2020-12-01 22:16

    In the second one you're trying to open a file named localhost in the current folder, which doesn't exist and hence throws an error. Use http://localhost instead. And to make that work, you're have to set allow_furl_open.

    0 讨论(0)
  • 2020-12-01 22:22

    You need to also check in PHP.ini file

    extension = php_openssl.dll
    

    is enable or not, if not then just enable that by removing ; sign

    allow_url_fopen = on
    
    0 讨论(0)
  • 2020-12-01 22:22

    For me the problem was that file_get_contents didn't work on https://domain.test.loc (domain that resolves to localhost), but worked on http://domain.test.loc. Maybe it doesn't like the self-signed certificate. I do have allow_url_fopen set to ON and extension = php_openssl.dll.

    0 讨论(0)
  • 2020-12-01 22:32

    This may be a setting in your php.ini file. There is a setting for allow_url_fopen which enables/disables the ability to open remote files from php. For security reasons this is usually defaulted to disabled. You can enable it in your php.ini by adding the following line:

    allow_url_fopen = 1
    

    Again, be aware of the security concerns when using this feature.

    http://php.net/manual/en/filesystem.configuration.php

    0 讨论(0)
提交回复
热议问题