Nov 22, 2010

Posted by in PHP, Technology | 1 comment

Check URL status using CURL in PHP

How to check site status using CURL?

Some times we need this for doing certain things during development. The best practice of using it would be to check Certain Important URLs of a site every time to make sure that they are working fine and the URLs are not down or no errors are associated with them.

Doing it in PHP is pretty simple I have written a function for it to which you need to pass a string containing the URL and it will check that URL for its status and errors in it and will return you the respective message, we can then use that message either to mail the admin or view in browser.

/*
@params - $url - pass the string containing the page URL to be checked.
*/


function chcekSiteStatus($url)
{

  $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.70 Safari/533.4";
 
  $ch=curl_init();
 
  curl_setopt ($ch, CURLOPT_URL,$url );
 
  curl_setopt($ch, CURLOPT_USERAGENT, $agent);
 
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
 
  curl_setopt ($ch,CURLOPT_VERBOSE,false);
 
  curl_setopt($ch, CURLOPT_TIMEOUT, 5);
 
  $page=curl_exec($ch);
 
  //echo curl_error($ch);
 
  $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 
  curl_close($ch);
 
  $return_code = '0';
 
  if($httpcode>=200 && $httpcode<300)
  {
    $return_code = 1;
  }    
 
  //now the site has returned 200 OK, but there might be Fatal Error, lets catch it. If there return 2
  if($return_code==1)
  {
    if(preg_match('/Fatal/',$page))
    {
       $return_code = 2;
    }
   
    if(preg_match('/Parse error/',$page))
    {
       $return_code = 2;
    }
  }
 
  /*
  code - 1 :: Page loaded successfully
  code - 0 :: Failed loading the page (problem with server)
  code - 2 :: This page has Fatal Error
  */

 
  return $return_code;
}

Example of USAGE

/*
List the site URLs you would like to test weather they are loading properly or not.
*/


$url_path = 'http://mysitename.com/';

$site_urls = array(
                   $url_path,
                   $url_path.'imppage1.php',
                   $url_path.'imppage2.php'
                  );


$message = '';

/*
check each URL and create message if req.. this chunk of code can be written in a function if required.
*/
   

foreach($site_urls as $surl)
{
  if(chcekSiteStatus($surl) == 0)
  {
    $message .=  '<p><a href="'.$surl.'?phpMyAdmin=d3qwETWliOOORKkNNT57sCcXIHa">'.$surl.'</a> Couldn\'t load properly </p>';
  }
  else if(chcekSiteStatus($surl) == 2)
  {
    $message .=  '<p><a href="'.$surl.'?phpMyAdmin=d3qwETWliOOORKkNNT57sCcXIHa">'.$surl.'</a> Contains PHP Error </p>';
  }
}

echo $message;

You can also send emails of the message to your admin, or set this in a curl which will keep checking the URLs in the desired intervals and will ping admin when required. I have kept all the code in a file which you can download here.

  1. Thanks! Thats working fine.

Leave a Reply