2

If I run

php -r 'print_r(file_get_contents("http://mirror.facebook.net/centos/timestamp.txt"));'

I get "Tue Oct 28 13:24:01 UTC 2014" (as expected).

But if I have a php file:

<?php
print_r(file_get_contents("http://mirror.facebook.net/centos/timestamp.txt"));

It gives me:

**Warning:** file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known ...

**Warning:** file_get_contents(http://mirror.facebook.net/centos/timestamp.txt): failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known ...

What is the difference between "php -r" and php running the code out of a file


UPDATE

This is not the answer to the question but it did solve my problem so for the sake of future googlers: I don't know which of these two solutions was the key but it was working when I restarted apache.

  1. In resolv.conf set nameserver 8.8.8.8 (which had my router's address)

  2. There's an SELinux boolean httpd_can_network_connect which must be turned on:

setsebool -P httpd_can_network_connect 1

See this solution and this one.

Community
  • 1
  • 1
jcuenod
  • 55,835
  • 14
  • 65
  • 102
  • does `nslookup mirror.facebook.net` work from the command line? – Marc B Oct 28 '14 at 16:24
  • http://stackoverflow.com/questions/6874857/php-file-get-contents-work-with-cli-but-does-not-work-when-called-on-server – Steve Oct 28 '14 at 16:32
  • @MarcB it seems to: I'm not sure what output to expect. `Server` and `Address` are my router but it then gives "Non-authoritative answer:" with mirror.facebook.net and its IP address. – jcuenod Oct 29 '14 at 10:16

1 Answers1

0

Your PHP CLI is using a different php.ini (or maybe no php.ini at all). It's also possible you are running a completely different PHP binary than what your server is using.

You can run php -i on the command line, and phpinfo() in a script to determine which php.ini is in use.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • My server is on my machine so surely it would be the same binary and ini file? – jcuenod Oct 29 '14 at 10:17
  • @j3frea Confirm it with the commands I gave you. I have seen many cases where there are 3 or 4 copies of PHP all on the same box. And, it's very likely you have a different config for your web server than the command line binary. Also, don't forget that PHP can also run in many SAPIs, including Apache module which works differently than the command line binary. – Brad Oct 29 '14 at 13:18
  • I ran `php -i | grep php.ini` and got: "Loaded Configuration File => /etc/php.ini" which is the same as `phpinfo()` gives me. I'm not sure where the binary is listed in phpinfo but I see under PHP Variables "_SERVER["PATH"] /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin" – jcuenod Oct 29 '14 at 19:19