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);
Related Questions
- How can the issue of uncontrolled execution of PHP scripts be resolved server-side?
- What is the recommended method to determine if an item in an array from FTP contains a file or a directory in PHP?
- How can PHP beginners ensure they are posting in the correct forum for their level of expertise on PHP.de?