当无法访问服务器时,PHP的PDO会忽略MySQL的ATTR_TIMEOUT选项 [英] PHP's PDO is ignoring the ATTR_TIMEOUT option for MySQL when server cannot be reached

查看:597
本文介绍了当无法访问服务器时,PHP的PDO会忽略MySQL的ATTR_TIMEOUT选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试无法通过连接随机IP来访问mysql服务器的方案.我使用PDO::ATTR_TIMEOUT => 1将PDO的选项设置为一秒后超时.但是,仍然需要30秒才能引发异常.我猜这个超时仅适用于实际的mysql连接时间,不适用于运行mysql的服务器.

I'm testing scenarios where the mysql server cannot be reached by putting in a random IP to try to connect to. I set PDO's options to time out after one second using PDO::ATTR_TIMEOUT => 1. However, it still takes 30 seconds to throw an exception. I'm guessing this timeout only applies to the actual mysql connection time, not to the server on which mysql is running.

我需要更改哪些PHP选项以使与mysql服务器的连接超时?

What PHP options do I need to change to time out the connection to the mysql server?

推荐答案

只需放置

ini_set("default_socket_timeout", 2);

在您的PDO()连接字符串之前.

before your PDO() connect string.

(在Windows上测试过,在Linux上也可以.)

(Tested on Windows, should also be fine on Linux.)

为什么?

按照手册进行操作:

mysqlnd驱动程序将套接字用于基础连接,而要设置超时,则需要使用套接字(流)超时功能. (请参阅: http://php.net/manual/en/mysqlnd.notes.php )

The mysqlnd driver uses sockets for the underlying connection, and that to set timeouts you need to use the socket (stream) timeout functions. (Ref: http://php.net/manual/en/mysqlnd.notes.php)

使用mysqlnd意味着使用PHP流进行基础连接.对于mysqlnd,应参考有关超时设置等详细信息,而不是MySQL客户端库的文档,查阅PHP流文档(Streams).

Using mysqlnd means using PHP streams for underlying connectivity. For mysqlnd, the PHP streams documentation (Streams) should be consulted on such details as timeout settings, not the documentation for the MySQL Client Library.


如果您想要更多的控制,那么您也许可以更具体地控制实际的套接字:我尚未对其进行测试,因为它仅是Unix.要设置mysqlnd使用的套接字,可以使用ini设置指定套接字(参考: http://php.net/manual/en/ref.pdo-mysql.connection.php )

如果PDO_MYSQL是针对mysqlnd编译的,则可以通过pdo_mysql.default_socket设置来设置默认套接字.

If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.

请参见 http://php.net/manual/zh_cn/ref.pdo-mysql.php#ini.pdo-mysql.default-socket 关于该设置

您也许可以使用 http://php.net/manual设置超时/en/function.stream-set-timeout.php

但是设置默认值可能更容易,一旦完成,就可以重置...

But probably easier to set default and then reset once you're done...

这篇关于当无法访问服务器时,PHP的PDO会忽略MySQL的ATTR_TIMEOUT选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆