Ads

Using CURL to chech a websites status

This is a custom script of mine, you can see it in use on our affiliation page for the status of each affiliate.

Now i've made mine into a function, but you can do whatever you want with it.


CODE
function websiteStatus($www) {
$toCheckURL = $www; 
$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $toCheckURL);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
$data = curl_exec($ch);
    curl_close($ch);
        preg_match_all("/HTTP/1.[1|0]s(d{3})/",$data,$matches);
    $code = end($matches[1]);
    //echo $code.' = ';
if(!$data) {
  echo "Cannot Find";
} else {
  switch($code) {
    case '200':
      echo "Online";
      break;
    case '401':
      echo "Timeout";
      break;
    case '403':
      echo "Forbidden";
      break;
    case '404':
      echo "Offline";
      break;
    case '500':
      echo "Internal Server Error";
      break;
  }
}
}



Now lets break this down:

CODE
$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $toCheckURL);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
$data = curl_exec($ch);
    curl_close($ch);
        preg_match_all("/HTTP/1.[1|0]s(d{3})/",$data,$matches);
    $code = end($matches[1]);
    //echo $code.' = ';


The above code starts CURL, gets the url, checks the headers, body, and then return-transfer. Next follow location and max-redirs. Now you can find out what each thing does http://ca3.php.net/curl there.

Next is the more 'easier' part to explain.

CODE
if(!$data) {
  echo "Cannot Find";
} else {
  switch($code) {
    case '200':
      echo "Online";
      break;
    case '401':
      echo "Timeout";
      break;
    case '403':
      echo "Forbidden";
      break;
    case '404':
      echo "Offline";
      break;
    case '500':
      echo "Internal Server Error";
      break;
  }
}



The above checks to see if there is data send back, if none it displays 'Cannot Find'. else whatever code that is send back it displays the text for whatever each is. Feel free to modify the text to whatever you want it to say for each code.

You might have seen a variation of this code elsewhere but it is not the same.
More tutorials to come Image Not Found

Friday July 27, 2007 - 1039 reads