You are currently viewing PHP: How to Check if a URL Exists

PHP: How to Check if a URL Exists

When working with URLs in PHP, it’s important to ensure that the URLs provided by users or retrieved from external sources actually exist before processing them further. Validating the existence of a URL helps prevent errors, improve data integrity, and enhance the user experience.

The provided PHP code checks if a given URL exists and returns a success or error message based on the HTTP response code received. The @ symbol in front of the get_headers() function, suppresses any warning or error messages that may be generated if the function call fails. Suppressing the error with the @ symbol prevents the script from stopping and outputs the error message we define in the else block.

<?php

$url = "https://www.coderscratchpad.com";

$headers = @get_headers($url);

if($headers !== false) {

    $response_code = http_response_code();

    if ($response_code >= 200 && $response_code < 300) {

        echo "The provided URL exists.";

    } else {

        echo "The provided URL returned an error (HTTP {$response_code}).";

    }

} else {

    echo "The provided URL does not exist or could not be reached.";

}

The code is useful for checking the availability of a website and can be a helpful tool in building applications that rely on external URLs. I hope that’s been informative to you. If you wish to learn more about PHP, please subscribe to our newsletter today and continue your PHP learning journey with us!

Leave a Reply