I am trying to validate if the input of a url, actually exists or not. I have been trying the following code, however I got no success. This is the following code:
Using cURL:
<?php
$url = 'https://github.com';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
echo "Url not working";
}
echo "true";
?>
Using get_headers
<?php
// Initialize an URL to the variable
$url = "https://www.geeksforgeeks.org";
// Use get_headers() function
$headers = @get_headers($url);
// Use condition to check the existence of URL
if($headers && strpos( $headers[0], '200')) {
$status = "URL Exist";
}
else {
$status = "URL Doesn't Exist";
}
// Display result
echo($status);
?>
I have searche both these answers on stackoverflow and other websites, and used these to check if the url I give actually exists. When I write down a non existing url, I would like it to output that the website does not exists, however, I always end up having the same output as an existing url, meaning that somethig might be wrong, although I cannot fully see it. By the first code, the output is always true, even if the url does not exist. By the second code, the output is always 'URL doesn't exist', even if the url actually exists. Am I doing something wrong? I am using PHP Version 7.4, is this tool still working? I apologize if the question is not clear.