Home >Backend Development >PHP Tutorial >How to Verify URL Availability in PHP Without Triggering 404 Errors?

How to Verify URL Availability in PHP Without Triggering 404 Errors?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-01 12:50:11203browse

How to Verify URL Availability in PHP Without Triggering 404 Errors?

Verifying URL Availability Using PHP

If you need to ascertain the existence of a URL without triggering a 404 error in PHP, the following strategies are at your disposal:

Method 1: Using get_headers()

$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;
}

Method 2: Utilizing cURL

function url_exists($url) {
    return curl_init($url) !== false;
}

These methods allow you to determine whether a URL is accessible or not, safeguarding your application from returning undesirable 404 errors.

The above is the detailed content of How to Verify URL Availability in PHP Without Triggering 404 Errors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn