What is the best way to know if a URL is working?

Asked

Viewed 880 times

-1

Some time ago I had to check if an external image existed to be able to show it, at that moment I used it:

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

I wonder if there is some other way to get the same result with php.

I don’t care if the is in fact a I just want to know if she really exists.

1 answer

3


get_headers() is really the most appropriate for this case, however, in addition to your check being wrong (you reversed the argument from strpos()), i would do the different check:

$headers = @get_headers( $url );

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

    // OK
}

This is because before checking something of some return index, you should check the return itself by avoiding unwanted Notices.

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

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

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

  • This point I think should have been clearer, the important thing for me is to check the URL independent of her Content-Type, what I really want is to know if it exists or not

  • 2

    Yes, yes, I just took the opportunity to complement, given the example and even the future reference of finding this duplicate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.