Skip to content

Instantly share code, notes, and snippets.

@aalfiann
Last active May 16, 2024 08:18
Show Gist options
  • Save aalfiann/d2d0c4bc0a0846edd7b02bb0f8a056e0 to your computer and use it in GitHub Desktop.
Save aalfiann/d2d0c4bc0a0846edd7b02bb0f8a056e0 to your computer and use it in GitHub Desktop.
PHP Curl to check is url exist or not (support redirected url)
<?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');
?>
@fvwanja
Copy link

fvwanja commented May 16, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment