NubGuy
NubGuy

Reputation: 9

PHP Socket timeout connection check

I am a newbie at PHP so I am wondering if anyone could help me.

I made a script using lots of work, even tough it's really easy but I just suck.

But yeah, if my website is on, this scripts shows it.

But if it doesn't load it takes a million hours for it to say that.

How can I set the maximum time for the script?

Thank you verry much

(I've searched a lot around Stack Overflow for a solution to this and all answers I found were unclear or not working for me.)

    <?php
$host = '127.0.0.1';
$ports = array(3000, 80);

foreach ($ports as $port)
{
    $connection = @fsockopen($host, $port);

    if (is_resource($connection))
    {
        if($port == 80)
        {
        echo "web: ONLINE";
        }

       if($port == 3000)
        {
        echo 'client: ONLINE';
        }

        fclose($connection);
    }

    else
    {
        echo '<h2>' . $host . ':' . $port . ' is not responding.</h2>' . "\n";
    }
}
?>

Upvotes: 1

Views: 1094

Answers (2)

sjagr
sjagr

Reputation: 16512

You can define the maximum timeout in the 5th argument of the fsockopen function:

$connection = @fsockopen($host, $port, $errno, $errstr, 10); // timeout at 10 seconds

Side note, by passing $errno and $errstr you can now retrieve and subsequently output a little bit more detail in your error:

echo '<h2>' . $host . ':' . $port . ' is not responding.</h2>' . "\r\n";
echo '<p>Error Number ' . $errno . ': ' . $errstr . '</p>'."\r\n";

Upvotes: 1

ravenixx
ravenixx

Reputation: 311

Have a quick look at the documentation and you'll see: parameter 5, float $timeout, is able to do that.

You should also check for $connection being false. That occurs if your timeout has been reached, or if any other error occured.

Upvotes: 1

Related Questions