PHP code to check server status
Tuesday, October 3rd, 2006Borntwisted came up with a wonderful idea to check that his free host was running without having to visit the a page or check the ftp.
He wrote a short piece of HTML that would pull an image off his website, if the server failed to respond the ALT tage would display OFFLINE.
I like to code things in php so I decided to take this a step further and not actually use any images, thus saving on bandwidth on my server everytime the page loads.
The full code is at the bottom of this post but I am going to break it down and try to explain how each section works.
First of all we need to connect to the server and check to see if a file exists. This file can be anything you like, I chose to use an image called online.gif.
I declared a variable call $url which holds the data needed to connect to the server. @fopen is the php command to connect to the server and open the chosen file. The reason the @ symbol is used is to supress the error that will be returned when the file cannot be found.
Using "r" tells the command we want to open the file in read only mode.
-
<?
Now we use a simple ifelse statment to output the correct part of the formula.
The first part of the formula as below asks if the condition is true (if file exists) and will output the command below it.
-
if ($url) {
Before the command is outputted we have to close the connection to the file for security purposes. fclose closes the connection to the server which is defined again by our variable $url.
Now we can output the following command if the file is found on the server. Basically this is the TRUE part of the conditional statement. We now ECHO a line of code to the browser which will be converted into HTML and displayed as what you will see. Do not worry about the div's and classes, that is just CSS styling for the page I have this code on.
-
}
The following code is the FALSE part of the staement, which is outputted if the above connection cannot find the file. It has similar styling to the above command but this time you will notice that the div class is set to "offline". This is so a different colour is displayed.
-
else {
-
}
-
?>
That's all there is to it. The code is simple and works well. If you use this code you may notice that when the file is removed by yourself the script doe snot update, this is simply because of the server it is on. Sometimes servers take a few minutes to update.
The code as a whole is listed below and I have also added the CSS that I have used. Modify to your needs.
-
.holder{
-
width:80px;
-
margin-left:5px;
-
}
-
-
.name{
-
float:left;
-
}
-
-
.online{
-
text-align:center;
-
width:8px;
-
height:8px;
-
padding:2px;
-
background:#75f475;
-
float:right;
-
border:1px solid #000;
-
margin-bottom:2px;
-
}
-
-
.offline{
-
text-align:center;
-
width:8px;
-
height:8px;
-
padding:2px;
-
background:#ef2424;
-
float:right;
-
border:1px solid #000;
-
margin-bottom:2px;
-
}



by @ 12:36