Rick Skeels
Rick Skeels

Reputation: 513

Checking if website is down using curl

I am using a the following code to see if a website is down or not.

<?php
    if (isset($_POST['submit'])) {
        $url = $_POST['url'];
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($code == 200) {
            echo "<h3>Up!</h3>";
        } else {
            echo "<h3>Down!</h3>";
        }
    }
?>

<form action="" method="post">
    Url: <input type="text" name="url" /><br />
    <input type="submit" name="submit" />
</form>

The issue I am having is when I check facebook.com it says its down but it isn't...

Why is this doing this? I orginally thought it could be the https but google works fine.

Upvotes: 0

Views: 1300

Answers (2)

Rick Skeels
Rick Skeels

Reputation: 513

I decided to post my updated code incase others are having same issue

<?php
    if (isset($_POST['submit'])) {
        $url = $_POST['url'];
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        echo "<h3>$code</h3>";



        if ($code == 200) {
            echo "<h3>Up! with a 200 code</h3>";
        } 
        if ($code == 301) {
            echo "<h3>Up! with a 301 code</h3>";
        } 
        else {
            echo "<h3>Down!</h3>";
        }
    }
?>

<form action="" method="post">
    Url: <input type="text" name="url" /><br />
    <input type="submit" name="submit" />
</form>

Above you can see i added the following

if ($code == 301) {
            echo "<h3>Up! with a 301 code</h3>";
        } 

There are alot of offline codes so i decided i would just use the online codes

as Kei posted in a comment you can see the list of return codes here

i also added the line echo "<h3>$code</h3>"; so you can see the responce from the form ie 200, 301

Upvotes: 1

Tristan Godfrey
Tristan Godfrey

Reputation: 369

I believe your curl isn't following HTTP redirects, this means you'll always receive a 301 response from Facebook.

Here's a thread on how to make your curl follow redirects:

Make curl follow redirects?

Upvotes: 1

Related Questions