Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ini file_get_contents external url

I use following PHP function:

file_get_contents('http://example.com');

Whenever I do this on a certain server, the result is empty. When I do it anywhere else, the result is whatever the page's content may be. When I however, on the server where the result is empty, use the function locally - without accessing an external URL (file_get_contents('../simple/internal/path.html');), it does work.

Now, I am pretty sure it has something to do with a certain php.ini configuration. What I am however not sure about is, which one. Please help.

like image 844
arik Avatar asked Aug 15 '10 17:08

arik


People also ask

What is the use of file_get_contents () function?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

Which is faster cURL or file_get_contents?

Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

What will the file_get_contents () return?

Return Values ¶ The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.


3 Answers

The setting you are looking for is allow_url_fopen.

You have two ways of getting around it without changing php.ini, one of them is to use fsockopen(), and the other is to use cURL.

I recommend using cURL over file_get_contents() anyways, since it was built for this.

like image 154
Aillyn Avatar answered Sep 30 '22 03:09

Aillyn


Complementing Aillyn's answer, you could use a function like the one below to mimic the behavior of file_get_contents:

function get_content($URL){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $URL);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
}

echo get_content('http://example.com');
like image 45
Pablo Avatar answered Sep 30 '22 01:09

Pablo


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

is best for http url, But how to open https url help me

like image 34
Vikash Avatar answered Sep 30 '22 03:09

Vikash