Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file_get_contents() not working

Tags:

php

codepad

Can anyone 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

like image 611
Kristy Saulsbury Avatar asked Dec 20 '22 16:12

Kristy Saulsbury


2 Answers

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

like image 68
Sudhir Bastakoti Avatar answered Jan 02 '23 03:01

Sudhir Bastakoti


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

like image 28
Adelmar Avatar answered Jan 02 '23 02:01

Adelmar