简体   繁体   中英

Why mysqli_connect doesn't respect MYSQLI_OPT_CONNECT_TIMEOUT?

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:

  1. Why PHP process stuck on real_connect when using host address www.baidu.com and port number 80 ?
  2. Why MYSQLI_OPT_CONNECT_TIMEOUT and the other timeout settings are not working?
  3. For this particular situation, is there any way to set a timeout that can work?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM