Page 1 of 1

check if a url exists.

Posted: Thu Mar 01, 2007 10:18 am
by murlopaz
Is there a faster way of doing this? This method is really slow.

Code: Select all

function url_exists($url) {
    $a_url = parse_url($url);
    if (!isset($a_url['port'])) $a_url['port'] = 80;
    $errno = 0;
    $errstr = '';
    $timeout = 30;
    if(isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
        $fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
        if (!$fid) return false;
        $page = isset($a_url['path'])  ?$a_url['path']:'';
        $page .= isset($a_url['query'])?'?'.$a_url['query']:'';
        fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
        $head = fread($fid, 4096);
        fclose($fid);
        return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head);
    } else {
        return false;
    }
   }

Posted: Thu Mar 01, 2007 11:18 am
by PrObLeM
What about using fopen:

Code: Select all

function url_exists( $url ) {
$ip = gethostbyname( $url );  
$a = fsockopen($ip,22,$errno,$errstr,10); 
return $a;
}
//true if exists false if error

Posted: Thu Mar 01, 2007 1:55 pm
by murlopaz
I don't think using the ip is a good idea...
does anybody have other ideas?

Posted: Thu Mar 01, 2007 2:32 pm
by mikeq
look at file_exists on the http://www.php.net, someone posted a function (2 from top of user contributed notes)

Code: Select all

<?php
function url_exists($url){
   if(strstr($url, "http://")) $url = str_replace("http://", "", $url);
   $fp = @fsockopen($url, 80);
   if($fp === false) return false;
   return true;
}
?>

Posted: Thu Mar 01, 2007 3:40 pm
by murlopaz
mikeq, i tried the function before.
It does not work within my scripts... did it work for you?

Posted: Thu Mar 01, 2007 4:17 pm
by mikeq
never tried it.

Thankfully I have no need for such a function :P