How can server responses, such as HTTP status codes, be utilized in PHP to determine the validity of a URL?

When validating a URL in PHP, you can utilize server responses, such as HTTP status codes, to determine the validity of the URL. By making a request to the URL and checking the response code, you can determine if the URL is valid (e.g., 200 OK) or invalid (e.g., 404 Not Found).

function validateURL($url) {
    $headers = get_headers($url);
    $responseCode = substr($headers[0], 9, 3);
    
    if($responseCode == "200") {
        echo "URL is valid";
    } else {
        echo "URL is invalid";
    }
}

$url = "https://www.example.com";
validateURL($url);