Last active
May 16, 2024 08:18
-
-
Save aalfiann/d2d0c4bc0a0846edd7b02bb0f8a056e0 to your computer and use it in GitHub Desktop.
PHP Curl to check is url exist or not (support redirected url)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Determine that url is exists or not | |
* | |
* @param $url = The url to check | |
**/ | |
function url_exists($url) { | |
$result = false; | |
$url = filter_var($url, FILTER_VALIDATE_URL); | |
/* Open curl connection */ | |
$handle = curl_init($url); | |
/* Set curl parameter */ | |
curl_setopt_array($handle, array( | |
CURLOPT_FOLLOWLOCATION => TRUE, // we need the last redirected url | |
CURLOPT_NOBODY => TRUE, // we don't need body | |
CURLOPT_HEADER => FALSE, // we don't need headers | |
CURLOPT_RETURNTRANSFER => FALSE, // we don't need return transfer | |
CURLOPT_SSL_VERIFYHOST => FALSE, // we don't need verify host | |
CURLOPT_SSL_VERIFYPEER => FALSE // we don't need verify peer | |
)); | |
/* Get the HTML or whatever is linked in $url. */ | |
$response = curl_exec($handle); | |
$httpCode = curl_getinfo($handle, CURLINFO_EFFECTIVE_URL); // Try to get the last url | |
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); // Get http status from last url | |
/* Check for 200 (file is found). */ | |
if($httpCode == 200) { | |
$result = true; | |
} | |
return $result; | |
/* Close curl connection */ | |
curl_close($handle); | |
} | |
// Example | |
echo url_exists('https://google.com'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/aalfiann/d2d0c4bc0a0846edd7b02bb0f8a056e0#file-url_check-php-L38 is unreachable. The
return
must come aftercurl_close
.