PHP, Apache, Localhost and IPv6

The number of moving parts in our systems exceeds the limits of single human’s comprehension by a large margin. It is therefore a miracle anything works at all, and we should be thankful for that.

I just spent at least 6 hours over three evenings fighting this problem: when I upgrade my web site from PHP 5.3.0 to PHP 5.4.4, MySQL access stops working. The error message simply says the server is “gone” and connection cannot be established (error code 2006).

I was looking at various config files, countless module versions, setting tracing, logging, and debugging: nothing. Under PHP 5.3.0 everything is fine, under 5.4.4 the code cannot connect to the server and basta.

Then I wrote a simple test script and ran it under command line version PHP. To my astonishment, it worked perfectly under PHP 5.4.4! But only from the command line, not from under Apache.

After pulling my hair for some time, I noticed that the server being accessed is referred to as “localhost”. I replaced it with “127.0.0.1” and voila – the script now works under Apache as well!

What gives? Was my localhost hijacked by evil hackers? Not really. However, if I do “ping localhost” I see that it is not resolved to 127.0.0.1, but to ::1, which is IPv6 address. It always used to be the case, nothing new here.

But once I went to my hosts file (c:\windows\system32\drivers\etc\hosts) and removed the line mapping localhost to ::1, “localhost” suddenly started to work under Apache again.

I don’t think MySQL knows anything about IPv6 and it listens only on 127.0.0.1, never on ::1. But somehow it was not an issue before. The combination of Apache 2.2.22 and PHP 5.3.0 does not care about localhost being mapped to ::1, nor does PHP 5.4.4 by itself. But the combination of Apache 2.2.22 and PHP 5.4.4 suddenly becomes confused and attempts to use the IPv6 address, which does not work. Go figure.

So, current state is: line mapping localhost to ::1 in “hosts” file commented out, “ping localhost” resolves to 127.0.0.1, MySQL connection to “localhost” works both in command line and under Apache. J’ai vainçu 🙂 Good night everyone.

1 Comment


  1. $hehe=file_get_contents(‘http://localhost’); //not working
    $hehe=file_get_contents(‘http://127.0.0.1’);//ok
    Apache/2.2.19 (Win32) mod_ssl/2.2.19 OpenSSL/0.9.8r PHP/5.2.17
    kind regards

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *