Linux – file_get_contents url wrappers work on cli but not cgi

curlfopenlighttpdlinuxPHP

I have a big problem. I have just upgraded to a new dedicated server running Plesk 10, and Ubuntu 11.04 and my scripts can't run file_get_contents or curl to external urls in cgi mode. allow_url_fopen is set to On in the correct php.ini file but still I get the following error.

file_get_contents(http://www.google.com): failed to open stream: Permission denied

Curl request returns false with this:

function get_data($url)
{
  // create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);

// grab URL and pass it to the browser
$data = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
 var_dump($data);
}    
get_data("http://www.google.com");//bool(false)

Both (file_get_contents and curl) run fine in scripts run from command line and from cron and both run fine when php is run as apache module. It is just when running in browser and as a cgi or fastcgi application that the problem arises. I have had the hosting company on all day with no luck. Any help gratefully received.

Best Answer

It turned out to be SELinux that was causing the problem, I fixed it with this command:

setsebool -P httpd_can_network_connect 1

Thanks to @jsmith in this thread: PHP file_get_contents error on CentOS as he was the second person who had suggested SELinux as causing such problems on centOS. I am a novice so I will only try something when it is confirmed by more than one source.