To validate if an URL exists, use PHP CURL

PHP Curl allows you to validate if a given URL exists. What you need to do is just a simple function as follows, which takes an input URL and returns the code. If the returned code is 200, then the URL exists, else it doesn’t!

<?php

$statusCode = validate($_REQUEST['url']);
if ($statusCode==’200′)
  echo ‘Voila! URL ‘.$_REQUEST['url'].
  ’ exists, returned code is :’.$statusCode;
else
  echo ‘Opps! URL ‘.$_REQUEST['url'].
  ’ does NOT exist, returned code is :’.$statusCode;

function validateurl($url)
{
  // Initialize the handle
  $ch = curl_init();
  // Set the URL to be executed
  curl_setopt($ch, CURLOPT_URL, $url);
  // Set the curl option to include the header in the output
  curl_setopt($ch, CURLOPT_HEADER, true);
  // Set the curl option NOT to output the body content
  curl_setopt($ch, CURLOPT_NOBODY, true);
  /* Set to TRUE to return the transfer
  as a string of the return value of curl_exec(),
  instead of outputting it out directly */

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Execute it
  $data = curl_exec($ch);
  // Finally close the handle
  curl_close($ch);
  /* In this case, we’re interested in
  only the HTTP status code returned, therefore we
  use preg_match to extract it, so in the second element
  of the returned array is the status code */

  preg_match(“/HTTP\/1\.[1|0]\s(\d{3})/”,$data,$matches);
  return $matches[1];
}
?>

For more information about CURL, find out more at PHP.net

Enter your email address to subscribe our newsletter or feed for FREE:

Delivered by FeedBurner


Bookmark with:

[Delicious]    [Digg]    [Reddit]    [Facebook]    [StumbleUpon]

0 Responses to “To validate if an URL exists, use PHP CURL”


  1. No Comments

Leave a Reply

You must login to post a comment.