check if a url exists.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
murlopaz
Forum Commoner
Posts: 60
Joined: Wed Oct 11, 2006 5:02 pm
Location: Baltimore, MD, USA

check if a url exists.

Post 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;
    }
   }
User avatar
PrObLeM
Forum Contributor
Posts: 418
Joined: Sun Mar 07, 2004 2:30 pm
Location: Mesa, AZ
Contact:

Post 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
murlopaz
Forum Commoner
Posts: 60
Joined: Wed Oct 11, 2006 5:02 pm
Location: Baltimore, MD, USA

Post by murlopaz »

I don't think using the ip is a good idea...
does anybody have other ideas?
User avatar
mikeq
Forum Regular
Posts: 512
Joined: Fri May 03, 2002 3:33 am
Location: Edinburgh, Scotland

Post 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;
}
?>
murlopaz
Forum Commoner
Posts: 60
Joined: Wed Oct 11, 2006 5:02 pm
Location: Baltimore, MD, USA

Post by murlopaz »

mikeq, i tried the function before.
It does not work within my scripts... did it work for you?
User avatar
mikeq
Forum Regular
Posts: 512
Joined: Fri May 03, 2002 3:33 am
Location: Edinburgh, Scotland

Post by mikeq »

never tried it.

Thankfully I have no need for such a function :P
Post Reply