Check to see if site is online using PHP?

Discussion in 'PHP' started by Hades, Feb 18, 2008.

  1. #1
    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
     
    Hades, Feb 18, 2008 IP
  2. jayshah

    jayshah Peon

    Messages:
    1,126
    Likes Received:
    68
    Best Answers:
    1
    Trophy Points:
    0
    #2
    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
     
    jayshah, Feb 18, 2008 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    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];
        }
    }
    
    PHP:
     
    nico_swd, Feb 18, 2008 IP
  4. jayshah

    jayshah Peon

    Messages:
    1,126
    Likes Received:
    68
    Best Answers:
    1
    Trophy Points:
    0
    #4
    You always have to be one better than me, don't you :)

    A quick note, the PHP Get_Headers function is only available in PHP 5, so if you have PHP 4, try something else.

    Jay
     
    jayshah, Feb 18, 2008 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    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, so you should upgrade if you need to.
     
    nico_swd, Feb 18, 2008 IP