Reputation:
I am trying to implement a PHP script that will ping an IP on a specific port and echo out whether the server is online / offline. This way, users will be able to see if non-access to the server is a server fault or a own network problem.
The site is currently on http://Dev.stevehamber.com. You can see the "Online" is wrapped in a class of 'PHP' and I need this to reflect if the server is online or offline. The application runs on port TCP=25565 so I need the output to show if this port is reachable or not.
Here is a snippet I found that is (I suppose) what I'm looking for:
<?php
$host = 'www.example.com';
$up = ping($host);
// if site is up, send them to the site.
if( $up ) {
header('Location: http://'.$host);
}
// otherwise, take them to another one of our sites and show them a descriptive message
else {
header('Location: http://www.anothersite.com/some_message');
}
?>
How can I replicate something like this on my page?
Upvotes: 0
Views: 1577
Reputation: 88697
Based on the comments on the question, fsockopen()
is the simplest and most widely available way to accomplish this task.
<?php
// Host name or IP to check
$host = 'www.example.com';
// Number of seconds to wait for a response from remote host
$timeout = 2;
// TCP port to connect to
$port = 25565;
// Try and connect
if ($sock = fsockopen($host, $port, $errNo, $errStr, $timeout)) {
// Connected successfully
$up = TRUE;
fclose($sock); // Drop connection immediately for tidiness
} else {
// Connection failed
$up = FALSE;
}
// Display something
if ($up) {
echo "The server at $host:$port is up and running :-D";
} else {
echo "I couldn't connect to the server at $host:$port within $timeout seconds :-(<br>\nThe error I got was $errNo: $errStr";
}
Note that all this does is test whether the server is accepting connections on TCP:25565. It does not do anything to verify that the application listening on this port is actually the application you are looking for, or that it is functioning correctly.
Upvotes: 4