php – mysql_connect(localhost / 127.0.0.1)在Windows平台上运行缓慢

我使用的是Windows 7,Apache 2,PHP 5,MysqL 5,它们都在同一台机器上.
我发现了一个有趣的问题,我有以下代码

    $sql = "select * from user1";
    $conn = MysqL_connect("localhost", "root", "xxxxxxxx");
    MysqL_select_db("test1");
    MysqL_query("set names utf8");
    $result = MysqL_query($sql, $conn);
    while ($row = MysqL_fetch_assoc($result)){
        foreach ($row as $key => $value){
            echo $key." => ".$value." || ";
        }
        echo "<br/>";
    }
    MysqL_free_result($result);
    MysqL_close($conn);

上述代码的运行时间超过1秒.

当我使用127.0.0.1而不是localhost时,运行时间大约为10毫秒.

我试图在互联网上找到根本原因,结果如下:

I recently moved my development from XP to Windows 7 and found that webpages I had developed were taking 5 seconds long to load. This was unacceptable of course so I had to track down the problem.
I eventually tracked down the offending function/method pdo::construct. I also found that MysqL_connect was taking about 1 second to make a connection. After a little googling I found an explaination that PHP had issues with IPv6 and that you Could fix the problem by either disabling IPv6 or switching to the ipaddress 127.0.0.1 when making your connection.

我想知道PHP上的IPv6问题是什么,只是想深入了解.谢谢.

解决方法:

PHP正在尝试打开与localhost的连接.由于您的计算机通过IPv6连接到您的网络,它首先尝试IPv6版本的“localhost”,这是一个IP地址:: 1

http://en.wikipedia.org/wiki/IPv6_address#Special_addresses

::1/128 — The loopback address is a unicast localhost address. If an
application in a host sends packets to this address, the IPv6 stack
will loop these packets back on the same virtual interface
(corresponding to 127.0.0.0/8 in IPv4).

看起来你的MysqL服务器没有监听那个地址,而是只绑定到IPv4地址,所以一旦PHP无法打开连接,它就会退回并尝试通过IPv4又名127.0.0.1打开localhost

我个人更喜欢使用IP地址或使用以太网Windows主机文件或Mac等效来定义’假’域名,然后在连接到MysqL时使用它们,这将解析为IP地址.无论哪种方式,我都可以确切地知道是使用IPv4还是IPv6地址.

MysqL和Apache都支持IPv6,但您必须告诉他们明确使用IPv6地址.对于MysqL,请参阅:
http://dev.mysql.com/doc/refman/5.5/en/ipv6-server-config.html

对于Apache配置,请参阅:
http://httpd.apache.org/docs/2.2/bind.html

Apache支持多个IP地址,因此您可以同时使用两个IP地址 – 如果计算机中的网卡同时具有IPv4和IPv6地址. MysqL支持一个地址.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...