PHP file_get_contents () not working

Can someone explain why the following code returns a warning:

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

I get a warning:

 Warning: file_get_contents(http://google.com): failed to open stream: No such file or directory on line 2 

See codepad

+4
source share
6 answers

Alternatively, you can use cURL, for example:

 $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

+8
source

Try this function instead 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 in the same way as file_get_contents (), but uses cURL.

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

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

See also cURL

+4
source

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

If you can modify PHP.ini, try enabling allow_url_fopen . See also the man page for fopen for more (the same restrictions affect all file processing functions)

If you cannot enable the flag, you will need to use another method, such as Curl, to read your URL.

+2
source

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 on Codepad.Viper - http://codepad.viper-7.com/lYKihI you will see that the HTTP stream is enabled so file_get_contents does not work on 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 will open the google page. The difference, therefore, is an http stream that is disabled on your CodePad.org and included in CodePad.Viper.

To enable it, read the following message How to enable HTTPS wrapping streams . Use cURL as an alternative.

+1
source

Try the trailing slash after the host name.

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

you can use single quotes as follows:

 file_get_contents('http://google.com'); 
-5
source

Source: https://habr.com/ru/post/1432637/


All Articles