微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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支持一个地址.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐