How to configure mysqli TIMEOUT in PHP?

Asked

Viewed 149 times

1

I have some servers I have to test if I have a connection.

Some of these servers have blocked access to my machine for testing, so they’ll give the message Can't connect to MySQL server on.

However, when they try to log into these servers that are blocked, they spend a lot of time trying to connect, so I tried to set up a Timeout following this link.

But it’s not working, I made the code as follows:

<?php

$link = mysqli_init();
if (!$link) {
    die('mysqli_init failed');
}

if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 10)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

include("ConectCTOM.php");

$SELECT_SERVERS = "SELECT * FROM status_db";

$EXECUTE_SERVERS = mysqli_query($conexao, $SELECT_SERVERS);


?>


<br><br>

<?php
$i = 1;
while ($LINE_SERVERS = mysqli_fetch_array($EXECUTE_SERVERS)) {

    $id = $LINE_SERVERS['id'];
    $ips = $LINE_SERVERS['ip'];
    $usuario = $LINE_SERVERS['user'];
    $senha = $LINE_SERVERS['key'];

if (!$conecta = mysqli_real_connect($link, $ips, $usuario, $senha, 'bdcma')){
    echo ('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

if($conecta){
    $resultado = "Conectado ".$i;
} else {
    $resultado = "Falhou ".$i;
}

echo '<a>'.$resultado.'</a><br>';

$i++;


}

mysqli_close($link);
?>
</body>
</html>

1 answer

1


MYSQLI_OPT_CONNNECT_TIMEOUT is a very dynamic configuration, it depends on the OS you are using, the PHP version, whether or not theadsafe, and several other things. For example it does not work well on Windows due to TCP/IP implementation. For Linux you have to activate other modules and make settings, and even then it only starts to count after Handshake (most of the time it doesn’t even get there), anyway it is a very complicated parameter that never worked well. A possible solution would be to do everything via API, create a file. php that works as an API and returns an OK status if it is working, puts the script timeout to type 15 seconds and ready. If I could make the call and return an OK, all right, if it takes more than 15 seconds, it will return timeout error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.