Up or Down App

This app adds to the Ping App we previously created with if/else conditionals based on the results from the ping command. For this example we simply print out text, but you could format text with CSS, or display different images based on whether a server can be pinged.

Code Explanation:

Lines 3-6 – HTML form for submitting domain name / IP address that sends value to the script

Line 10 – Turns value sent from HTML form int value for $command variable

Line 11 – Concatonates $command value with the ping command and sets value to $ping_command variable. We created a new variable for the command in this script so that we can test to see if a value was sent in the if/else statement.

Line 14 – Set value of $result to the results of the shell_exec() function.

Line 16 – Use Strpos() function to test is “1 received” is in $result. If so this means the ping was a success and so print out “site is UP”

Line 18 – Use Else if with strpos() to test if “0 received” is in $result which means the server did not respond to the ping and print “site is DOWN”.

Line 20 – Use Else if to see if $command is empty. So when the form initially loads, or a user presses submit without giving a value it will print “Please Enter Domain Name or IP Address”

Line 23 – Final Else is for if a user submits text that is not an IP address or domain name, such as “bob”. This will then print out “There was a problem”

Line 27 – Prints out the value for $result within <pre> tags. In this example this is used for troubleshooting and so the student understands what the shell_exec() output looks like. For a “real” app this could be removed and only the results of the if/else statement would be displayed.


<h1>Up or Down App</h1>

<form action="updown.php" method="post">
    <input type="text" name="command">
    <input type="submit">


$command = $_POST['command'];

$ping_command = "ping -c 1 $command";

$result = shell_exec($ping_command);

if (strpos($result, "1 received")){
    echo "site is UP";
} else if(strpos($result, "0 received")) {
    echo "site is DOWN";
} else if ($command == ""){
    echo "Please Enter Domain Name or IP Address";
    echo "There was a problem";

echo "<pre>$result</pre>";

Code language: HTML, XML (xml)