file_get_contents() vs drupal_http_request()

Earlier today I encountered the following error when using the geonames module in Drupal 5:

warning: file_get_contents() [function.file-get-contents]: URL file-access is disabled in the server configuration in /var/www/sites/all/modules/geonames/geonames.module on line 175.

This problem occurs when file_get_contents() gets called with an HTTP URL on a server where allow_url_fopen is disabled in php.ini.

Without write access to php.ini there is no easy workaround for the error. Fortunately it is quite easy to avoid the issue by replacing the following line of code

$data = file_get_contents('http://www.example.com/')

by

$request = drupal_http_request('http://www.example.com/');
$data = $request->data;

Other modules have already made this change and geonames will probably follow soon. So if you maintain a module that uses file_get_contents() with an HTTP URL you might want to consider switching to drupal_http_request().

Topic: 

4 Comments

You should be able to

You should be able to circumvent that in 2 ways. Either add

php_value allow_url_fopen 1

to your .htaccess file

or add

@ini_set("allow_url_fopen", 1);

to your settings.php. Not that ini_set() must be enabled for this 2nd option to work...

If drupal_http_request()

If drupal_http_request() doesn't work on your server, you could also use a cURL request (http://us3.php.net/manual/en/function.curl-exec.php):

<?php

// fictional URL to an existing file with no data in it (ie. 0 byte file)
$url = 'http://www.example.com/empty_file.txt';

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);

// execute and return string (this should be an empty string '')
$str = curl_exec($curl);

curl_close($curl);

// the value of $str is actually bool(true), not empty string ''
var_dump($str);

?>

Great article. Thanks for

Great article. Thanks for posting.... helped to find out the issue why "file_get_contents" function stopped working, plus, suggested a very nice solutions.
Thanks for sharing.