PHP ssh2_connect() Implement A Timeout

Justin picture Justin · May 24, 2012 · Viewed 11k times · Source

I am using the PHP ssh2 library, and simply doing:

$ssh = ssh2_connect($hostname, $port);

The problem is I want to set a timeout, i.e. after 5 seconds stop trying to connect. As far as I can tell the ssh2 library does not support a timeout on connect natively. How can I implement a timeout wrapper?

Answer

Patkos Csaba picture Patkos Csaba · Sep 14, 2017

I know this is an old thread, but the problem is still there. So, here is the solution for it.

ssh2_connect() uses socket_connect(). socket_connect relies on the php ini configuration parameter default_socket_timeout which is set by default to 60 seconds (http://php.net/manual/en/filesystem.configuration.php#ini.default-socket-timeout)

So, the easiest way to solve our problem is to change the ini setting at runtime to a value we want, and than back to the value set in the ini file so we avoid effecting other parts of our software. In the example below, the new values is set to 2 seconds.

    $originalConnectionTimeout = ini_get('default_socket_timeout');
    ini_set('default_socket_timeout', 2);

    $connection = ssh2_connect('1.1.1.1');

    ini_set('default_socket_timeout', $originalConnectionTimeout);

You can find further details about how ssh2 for php works by reading the source code of libssh2 (https://github.com/libssh2/libssh2).