sparkmix
sparkmix

Reputation: 2489

Can PHP mysqli set timeout on connect attempt?

I've this line to connect to MySQL db and just wonder if there's a way to set a timeout for connect attempt?

$db = new mysqli($server, $usr, $passwd, $dbname);

Upvotes: 6

Views: 19424

Answers (1)

O. Jones
O. Jones

Reputation: 108641

Yes, you can specify a timeout explicitly for an attempt to connect from your php program to a MySQL database using mysqli.

It's a little hairy, though. If you want to set a timeout, or any other option, you need to use real_connect instead of new mysqli, like the following:

$timeout = 30;  /* thirty seconds for timeout */
$link = mysqli_init( );
$link->options( MYSQLI_OPT_CONNECT_TIMEOUT, $timeout );
$link->real_connect($server,  $usr, $passwd, $dbname);

There's a decent explanation here: https://php.net/manual/en/mysqli.real-connect.php

Upvotes: 19

Related Questions