What is the best way to tell if a URL is working? [duplicate]

-1

At some point I needed to check if an external image existed to be able to display it, at that time I used this:

<?php 
$file = 'http://pt.stackoverflow.com';
$file_headers = @get_headers($file);
$position = strpos($file_headers[0], "404");
if ($position == -1) {
    echo "o site está online.";
}    
?>

I would like to know if there is any other way to get the same result with php.

I do not want to know if the is actually a I just want to know if it really exists.

    
asked by anonymous 11.02.2014 / 18:38

1 answer

3

get_headers () is really the most appropriate for this case, however, plus your check is wrong (you've reversed the argument from strpos () , I would do the different check:

$headers = @get_headers( $url );

if( $headers !== FALSE && strpos( $headers[ 0 ], '200' ) !== FALSE ) {

    // OK
}

That's because before checking something of any return index, you should check the return itself, avoiding unwanted notices.

And although using arroba to suppress the error is not a good practice without a custom error handler, it needs to be used.

However, it is worth noting that this is not sufficient to determine if a URL points to an image.

For this, taking advantage of the form headers, it is enough if the Content-Type entry exists and if there is the term image .

    
11.02.2014 / 19:12