How to check if a URL exists via PHP?

Spread the love

Sometimes, we want to check if a URL exists via PHP.

In this article, we’ll look at how to check if a URL exists via PHP.

How to check if a URL exists via PHP?

To check if a URL exists via PHP, we can use the get_headers function.

For instance, we write

$file = "http://www.example.com/somefile.jpg";
$file_headers = @get_headers($file);
if (!$file_headers || $file_headers[0] == "HTTP/1.1 404 Not Found") {
    $exists = false;
} else {
    $exists = true;
}

to call get_headers with the $file URL to get the file headers if they exist.

We use @ to suppress warnings.

Then we check !$file_headers || $file_headers[0] == "HTTP/1.1 404 Not Found" to get if the file doesn’t exist.

Conclusion

To check if a URL exists via PHP, we can use the get_headers function.

Leave a Reply

Your email address will not be published. Required fields are marked *