How to test if a url exists using PHP


//the function
function urlExists($url) { 
$ch = curl_init($url); 
//cURL set options
$options = array(
    CURLOPT_URL => $url,              #set URL address
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20080311 Firefox/',  #set UserAgent to get right content like a browser
    CURLOPT_RETURNTRANSFER => true,         #redirection result from output to string as curl_exec() result
    CURLOPT_COOKIEFILE => 'cookies.txt',    #set cookie to skip site ads
    CURLOPT_COOKIEJAR => 'cookiesjar.txt',  #set cookie to skip site ads
    CURLOPT_FOLLOWLOCATION => true,         #follow by header location
    CURLOPT_HEADER => true,                 #get header (not head) of site
    CURLOPT_FORBID_REUSE => true,           #close connection, connection is not pooled to reuse
    CURLOPT_FRESH_CONNECT => true,          #force the use of a new connection instead of a cached one
    CURLOPT_SSL_VERIFYPEER => false         #can get protected content SSL
//set array options to object
curl_setopt_array($ch, $options);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
curl_close($ch);  if(empty($retcode) || $retcode > 400) { return false; } 
else { return true; } 
//to use it
 //URL does not exist!

Shane Stebner

Author: Shane Stebner

Shane is a successful web-developer specializing in responsive design, and the open-source LAMP stack. Over the years, he's gained in-depth experience with Stripe, Twilio, PhantomJs,, PayPal, Facebook, Twitter, and many other plugins/APIs.

comments powered by Disqus