Search code examples
phpcommand-linefile-get-contentsphp-8.1

PHP file_get_contents() and curl_exec() fail from website but work from command line


Created .test.php file with one line of code:

<?php
var_dump(file_get_contents('https://checkip.amazonaws.com'));
?>

When I open .test.php from browser, it shows bool(false) but when I run it from command line, it shows my WAN IP as expected.

php -f .test.php

I am using CentOS 9, nginx 1.20.1, and PHP 8.1.3 (Although I've also tried RHEL8 and Apache)

I tried setting /etc/php-fpm.d/www.conf to use my userid and group to make sure it was not a permission problem.

phpinfo() shows allow_url_fopen is set to On and that curl 7.76.1 is enabled and that OpenSSL is enabled with version 3.0.1

I also tried with an http: URL

I also tried using curl() libraries in the .php file and those fail in the same manner.

Calling exec() from .php file works if it calls php -v or another .php file but not if it calls curl

Not sure what else to try, so I will probably nuke the whole server again.

UPDATE: Found this in /var/log/nginx/error.log FastCGI sent in stderr: "PHP message: PHP Warning: file_get_contents(https://checkip.amazonaws.com): Failed to open stream: Permission denied

Now what?


Solution

  • Once I found the error log, I was able to find my answer. It was a Linux permission setting and running the following command fixed it: setsebool -P httpd_can_network_connect on