Posted by: prajapatinilesh | August 8, 2007

Check if a URL exists/is online.

<?php

function is_valid_url($url)
{
$url = @parse_url($url);

if (!$url)
{
return false;
}

$url = array_map(‘trim’, $url);
$url[‘port’] = (!isset($url[‘port’])) ? 80 : (int)$url[‘port’];
$path = (isset($url[‘path’])) ? $url[‘path’] : ;

if ($path == )
{
$path = ‘/’;
}

$path .= (isset($url[‘query’])) ? “?$url[query]” : ;

if (isset($url[‘host’]) AND $url[‘host’] != gethostbyname($url[‘host’]))
{
if (PHP_VERSION >= 5)
{
$headers = get_headers(“$url[scheme]://$url[host]:$url[port]$path”);
}
else
{
$fp = fsockopen($url[‘host’], $url[‘port’], $errno, $errstr, 30);

if (!$fp)
{
return false;
}
fputs($fp, “HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n);
$headers = fread($fp, 4096);
fclose($fp);
}
$headers = (is_array($headers)) ? implode(\n, $headers) : $headers;
return (bool)preg_match(‘#^HTTP/.*\s+[(200|301|302)]+\s#i’, $headers);
}
return false;
}

?>

 

 

 

 

 

<?php
//how to call
if (is_valid_url(http://www.secondversion.com&#8217;))
{
do_something();
}

?>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: