Curl check URL
By: Daniel

I posted a while ago some code on how to check if port 80 (http) is up on a specified domain name. Well, here is some code that does very similar but uses Curl and will show you the status of this domain name. I have commented it so you should be able to figure the main parts out:

<?php
$toCheckURL = "www.wlscripting.com"; // The domain name of the site you want to check
// This all sets up the CURL actions to check the page
$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); //follow up to 10 redirections - avoids loops
$data = curl_exec($ch);
curl_close($ch);
// Get the headers from the $data to the $matches variable
preg_match_all("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches);
$code = end($matches[1]);
//echo $code.' = ';
if(!$data) {
  // If CURL could not open the URL
  echo "Domain could not be found";
} else {
  // Show the correct information based on the status code
  switch($code) {
    case '200':
      echo "Page Found";
      break;
    case '401':
      echo "Unauthorized";
      break;
    case '403':
      echo "Forbidden";
      break;
    case '404':
      echo "Page Not Found";
      break;
    case '500':
      echo "Internal Server Error";
      break;
  }
}
?>

Enjoy!

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)
Loading ... Loading ...

3 Responses to “Curl check URL”

  1. sagoral Says:

    Hi,
    This function always returns “Page Found”…

  2. Daniel Says:

    Are you using OpenDNS on the computer/server you are trying to run this code on?

    You can add the following after the curl_close() and see what is actually being produced:

    var_dump($data);

  3. Gros Says:

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

Leave a Reply

geovisitors