Wednesday, April 11, 2012

check if url exists or not using cURL

currently i am using following function


function urlExist($url)
 {
                 $handle   = curl_init($url);
                 if (false === $handle)
                 {
                         return false;
                 }
                 curl_setopt($handle, CURLOPT_HEADER, false);
                 curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
                 curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox
                 curl_setopt($handle, CURLOPT_NOBODY, true);
                 curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
                 $connectable = curl_exec($handle);
                 ##print $connectable;
                 curl_close($handle);
                 return $connectable;
 }
 


It works fine for simple url but does not work for url that redirects to another domain



Answer:

You need to set the FOLLOWLOCATION option:
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
But why are you issuing a GET request? A simple HEAD is lighter since only headers are sent. To do that, set NOBODY to true:
curl_setopt($handle, CURLOPT_NOBODY, true);

No comments:

Post a Comment