How to check any website status using PHP

May 15th, 2011 by Tony de Jesus

Sometimes we need a tool able to monitor the activity and status of a specific website. For example, in this blog, I have the Sites of the Week series that displays the best websites that I’ve found in the week. I don’t want my readers to click on one of those links and get an error page. What would they think about me? So, I need a service or tool to check all my sites of the week status and then notify me when any of them are down.

There are lots of services over the web where you can pay to have a website monitored and be notified when it’s down. However, they are making good money for a service that you can easily offer to yourself with minimum effort. I’m going to show you an easy to use function that will allow you to check if a website is down. This function is written in PHP and uses cURL library to get the website’s status.

/**
  * Function to check a website status
  * @param string url the url of the website to test
  * @return boolean true if the site is up, false otherwise
*/

function checkStatus($url){
     $agent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; pt-pt) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27";

     // initializes curl session
     $ch=curl_init();

     // sets the URL to fetch
     curl_setopt ($ch, CURLOPT_URL,$url );

     // sets the content of the User-Agent header
     curl_setopt($ch, CURLOPT_USERAGENT, $agent);

     // return the transfer as a string
     curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

     // disable output verbose information
     curl_setopt ($ch,CURLOPT_VERBOSE,false);

     // max number of seconds to allow cURL function to execute
     curl_setopt($ch, CURLOPT_TIMEOUT, 5);

     curl_exec($ch);

     // get HTTP response code
     $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

     curl_close($ch);

     if($httpcode>=200 && $httpcode<300)
          return true;
     else
          return false;
}

Example of use


if(checkStatus("http://www.tonyjesus.com"))
     echo "Website is up";
else
     echo "Website is down";

, ,

 
 
 

4 Comments

  1. Francisco

    great code, Thanks

  2. Antonio

    Great!

    Thank you man!

  3. nato

    Thanks actually works

  4. Great code! Just what I was looking for!!

Trackbacks

Leave a Reply