Reputation: 73
The code below will stuck on real_connect()
100%. set_time_limit
and default_socket_timeout
and MYSQLI_OPT_CONNECT_TIMEOUT
have been set, but not working.
I tested on PHP 5.6 and PHP 7.1. mysql driver is 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
?MYSQLI_OPT_CONNECT_TIMEOUT
and the other timeout settings are not working?Upvotes: 4
Views: 2111
Reputation: 33237
There are two timeout settings. One is MYSQLI_OPT_CONNECT_TIMEOUT
and the other one is MYSQLI_OPT_READ_TIMEOUT
. The second one is poorly documented, but this option can be set in two ways.
Using 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. Set this in php.ini file:
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.
Upvotes: 3
Reputation: 73
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. The solution is to set mysqlnd.net_read_timeout
in the php.ini
file. The parameter value is in seconds.Such as:
mysqlnd.net_read_timeout = 3
Upvotes: 3