David_Hogan
David_Hogan

Reputation: 125

php ping test and redirect

I am trying to get a basic php ping script working that will ping my sites ip and if it responds will redirect the user to my site however if it doesn't it will redirect the user elsewhere. I've attached what I have so far below however currently it does not appear to be pinging the site as it just goes straight to http://othersite.com as show in the example below. Thank you for any help you can provide.

<?php

function ping($host)
{
    exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($host)), $res, $rval);
    return $rval === 0;
}
// random host ip example
$host = '8.8.8.8';
$online = ping($host);

// if site is online, send them to the site.
if( $online ) {
       header('Location: mysite.com');
} 
// otherwise, lets go elsewhere to an online site
else {
        header('Location: http://othersite.com/');
}

?>

Upvotes: 1

Views: 2890

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

Note: Your code seems to work fine on Linux but not on windows. Checking a little further I noticed that windows does not provide -c option for ping, which causes it to return a different value than expected and your ping fails

exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($host)), $res, $rval);
    return $rval === 0;

That seems to assume that the return value will be 0 from exec on success? But according to PHP Manual it will be

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function. To get the output of the executed command, be sure to set and use the output parameter.

It appears like your comparison with returned value is the problem. What value does $rval contain?

Upvotes: 1

Related Questions