1

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";
    }
}
?>
1
  • See the docs at php.net/fsockopen pay close attention to $timeout Commented Dec 5, 2014 at 14:55

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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";

5 Comments

Thx dude :D, what is the $errno? should i add that variable too or?
The $errno and $errstr are actually passed to the function as references to be filled in by fsockopen if there's any error or trouble. You can echo those out later to provide more descriptive messages as to why the connection failed!
@NubGuy No problem! Please make sure you mark off the answer that helped you the most as accepted. It can be done by clicking the "checkmark" right below the down/up vote arrows for the answer. Also welcome to SO.
Im new to this forum need 15rep for that if i got that i would
@NubGuy You're confusing accepting an answer with upvoting. There's just a 15-minute time limit for accepting an answer, you should be able to now. See this meta answer for more information!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.