[英]Why mysqli_connect doesn't respect MYSQLI_OPT_CONNECT_TIMEOUT?
The code below will stuck on real_connect()
100%.下面的代码将卡在real_connect()
100% 上。 set_time_limit
and default_socket_timeout
and MYSQLI_OPT_CONNECT_TIMEOUT
have been set, but not working. set_time_limit
和default_socket_timeout
和MYSQLI_OPT_CONNECT_TIMEOUT
已设置,但不起作用。
I tested on PHP 5.6 and PHP 7.1.我在 PHP 5.6 和 PHP 7.1 上进行了测试。 mysql driver is mysqlnd. mysql 驱动程序是 mysqlnd。
set_time_limit(30);
ini_set('default_socket_timeout', 10);
$mysql = new mysqli();
$mysql->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$mysql->real_connect('www.baidu.com', 'root', 'xxx', 'xxx', 80);
Questions:问题:
real_connect
when using host address www.baidu.com
and port number 80
?为什么PHP进程在使用主机地址www.baidu.com
和端口号80
时卡在real_connect
?MYSQLI_OPT_CONNECT_TIMEOUT
and the other timeout settings are not working?为什么MYSQLI_OPT_CONNECT_TIMEOUT
和其他超时设置不起作用?I found the reason.我找到了原因。 The timeout in my case is a read timeout, not a connection timeout.在我的情况下超时是读取超时,而不是连接超时。 Therefore MYSQLI_OPT_CONNECT_TIMEOUT
is not working.因此MYSQLI_OPT_CONNECT_TIMEOUT
不起作用。 The solution is to set mysqlnd.net_read_timeout
in the php.ini
file.解决办法是在php.ini
文件中设置mysqlnd.net_read_timeout
。 The parameter value is in seconds.Such as: mysqlnd.net_read_timeout = 3
参数值以秒为单位。如: mysqlnd.net_read_timeout = 3
There are two timeout settings.有两种超时设置。 One is MYSQLI_OPT_CONNECT_TIMEOUT
and the other one is MYSQLI_OPT_READ_TIMEOUT
.一个是MYSQLI_OPT_CONNECT_TIMEOUT
,另一个是MYSQLI_OPT_READ_TIMEOUT
。 The second one is poorly documented, but this option can be set in two ways.第二个没有很好的记录,但可以通过两种方式设置此选项。
Using mysqli::set_opt
:使用mysqli::set_opt
:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli();
$mysqli->set_opt(MYSQLI_OPT_READ_TIMEOUT, 3); // 3 seconds
$mysqli->connect('example.com', 'user', 'pass', 'db');
$mysqli->set_charset('utf8mb4'); // always set the charset
or using the INI confiuguration setting.或使用 INI 配置设置。 Set this in php.ini file:在 php.ini 文件中设置:
mysqlnd.net_read_timeout = 3
The ini setting is just a default value for MYSQLI_OPT_READ_TIMEOUT
if one is not provided through mysqli::set_opt
, so whichever way you chose will work.如果没有通过mysqli::set_opt
提供,ini 设置只是MYSQLI_OPT_READ_TIMEOUT
的默认值,因此无论您选择哪种方式都可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.