Personal Loans - Babb Fest - Credit Card Consolidation - Loan - Mortgage

PDA

View Full Version : Check to see if site is online using PHP?


Hades
Feb 18th 2008, 1:52 am
Hey guys,

I am a newbie to php, so I was wondering if there was a way for me to have a bit of a code run on my site. I would add a link to it, and when ever a visitor goes on my site, the script will run, and tell them if the url that I entered into the php code previously is either "Online" if it shows up a site, or "Offline" if it shows a 404 page or takes you to the Index Of page.

Is there a way to do that?

Thanks,
Nick

jayshah
Feb 18th 2008, 2:35 am
Yes, you can pass the url via the query string (i.e. script.php?url=xyz.com) and have the script use file_get_contents (easiest), sockets or the likes to fetch the page. If it's online file_get_contents will return data, if not, it's offline. A point to note: file_get_contents will throw an error for offline pages, so suppress it with an @.

Jay

nico_swd
Feb 18th 2008, 4:13 am
I'd use get_headers() if you want to check for 404 errors.


if (!$headers = @get_headers($url))
{
// URL completely unaccessible.
}
else
{
preg_match('~HTTP/1\.\d\s+(\d+)~', $headers[0], $status);

if ($status[1] == 200)
{
// Everything perfect
}
else
{
// HTTP error: $status[1];
}
}

jayshah
Feb 18th 2008, 5:03 am
You always have to be one better than me, don't you :)

A quick note, the PHP Get_Headers (http://uk2.php.net/get_headers) function is only available in PHP 5, so if you have PHP 4, try something else.

Jay

nico_swd
Feb 18th 2008, 5:18 am
You always have to be one better than me, don't you :)


Lol, no, I was just answering the other part of the question that you missed. (404 errors) :)


As for the PHP version, yes, it only works for PHP 5. But PHP 4 is officially dead (http://www.php.net/index.php#2007-07-13-1), so you should upgrade if you need to.