Gordon Tyler
Gordon Tyler

Reputation: 21

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?

Upvotes: 1

Views: 1101

Answers (2)

Gordon Tyler
Gordon Tyler

Reputation: 21

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

Upvotes: 1

ino
ino

Reputation: 2581

There might be different settings of your PHP environment used in Command Line Interpreter/Interface CLI vs Common Gateway Interface CGI .

First compare what .ini files are loaded in both environment, ie.

  1. for CLI run php -i
  2. for CGI create a file phpinfo.php with only content <?php echo phpinfo(); and open it in the web browser.

Compare the results and see what modules are loaded and/or what .ini files are loaded.

Upvotes: 1

Related Questions