Hi all, I am having a very strange PHP issue, and hoping someone will have some ideas
Within PHP, functions that support urls (fopen, file_get_contents, etc) will contact the correct server and work fine, and othertimes mistakenly contacts localhost. It would seem like a DNS issue, but both PHP’s dns and outside programs like ping and wget work fine.
Does anyone have any ideas on why PHP would sometimes return files from an incorrect server?
Illustrative code & output follows:
<?php
// Enable extra error logging
error_reporting(-1);
ini_set('display_errors', 1);
// Works fine -- www.google.com
echo "www.google.com = ";
$a = fopen("http://www.google.com", "r");
echo fread($a, 100); // OK, outputs 100 characters of google's homepage
fclose($a);
echo "\
";
// Works fine -- localhost
echo "localhost = ";
$b = fopen("http://localhost", "r");
echo fread($b, 100); // OK, outputs 100 characters of localhost's homepage
fclose($b);
echo "\
";
// Doesn't work -- google.com returns localhost's content
echo "google.com = ";
$c = fopen("http://google.com", "r");
echo fread($c, 100); // Not OK, outputs 100 characters of localhost's homepage instead of google's
fclose($c);
echo "\
";
// Now, let's check DNS...
echo "www.google.com => " . gethostbyname("www.google.com") . "\
"; // OK
echo "localhost => " . gethostbyname("localhost") . "\
"; // OK
echo "google.com => " . gethostbyname("google.com") . "\
"; // OK... so why does fopen return differing content?
// And we can confirm with wget that google.com works fine
$wget = shell_exec("wget google.com -O -");
echo "wget = " . $wget; // returns google's homepage code
?>
Outputs (done on the command line in this case, but same output via apache):
$ php5 test.php
www.google.com = <!doctype html><html><head><meta http-equiv=“content-type” content=“text/html; charset=ISO-8859-1”><
localhost = <a href=“simworld”>SimWorld</a> / <a href=“eatv”>EATV</a> / <a href=“archivegames”>Archive Games</a> [FYI, this is the first 100 characters of the page on localhost]
google.com = <a href=“simworld”>SimWorld</a> / <a href=“eatv”>EATV</a> / <a href=“archivegames”>Archive Games</a>
www.google.com => 74.125.67.106
localhost => 127.0.0.1
google.com => 74.125.67.147
[wget output of contacting google and getting the correct page back is here]