PHP file_get_contents() not working

ε祈祈猫儿з 提交于 2019-11-29 07:45:57

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

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

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.

Conrad Lotz

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.

Try a trailing slash after the hostname.

<?php
    echo file_get_contents("http://google.com/");
?>
Tony07

you can try using single quotes like this:

file_get_contents('http://google.com');
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!