How do I check if a URL exists (not 404) in PHP?
get_headers() returns an array with the headers sent by the server in response to a HTTP request.
$image_path = 'https://your-domain.com/assets/img/image.jpg';
$file_headers = @get_headers($image_path);
//Prints the response out in an array
//print_r($file_headers);
if($file_headers[0] == 'HTTP/1.1 404 Not Found'){
echo 'Failed because path does not exist.</br>';
}else{
echo 'It works. Your good to go!</br>';
}
function URLIsValid($URL)
{
$exists = true;
$file_headers = @get_headers($URL);
$InvalidHeaders = array('404', '403', '500');
foreach($InvalidHeaders as $HeaderVal)
{
if(strstr($file_headers[0], $HeaderVal))
{
$exists = false;
break;
}
}
return $exists;
}
cURL can return HTTP code I don’t think all that extra code is necessary?
function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}
pretty fast:
function http_response($url){
$resURL = curl_init();
curl_setopt($resURL, CURLOPT_URL, $url);
curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback');
curl_setopt($resURL, CURLOPT_FAILONERROR, 1);
curl_exec ($resURL);
$intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE);
curl_close ($resURL);
if ($intReturnCode != 200 && $intReturnCode != 302 && $intReturnCode != 304) { return 0; } else return 1;
}
echo 'google:';
echo http_response('http://www.google.com');
echo '/ ogogle:';
echo http_response('http://www.ogogle.com');
function urlIsOk($url)
{
$headers = @get_headers($url);
$httpStatus = intval(substr($headers[0], 9, 3));
if ($httpStatus<400)
{
return true;
}
return false;
}
you cannot use curl in certain servers u can use this code
<?php
$url = 'http://www.example.com';
$array = get_headers($url);
$string = $array[0];
if(strpos($string,"200"))
{
echo 'url exists';
}
else
{
echo 'url does not exist';
}
?>