PHP로 URL이 존재하는지 확인하려면 어떻게 해야 하나요?

PHP에 (404가 아닌) URL이 존재하는지 확인하려면 어떻게 해야 하나요?



질문에 대한 답변



여기:

$file = 'http://www.example.com/somefile.jpg'; $file_headers = @get_headers($file); if(!$file_headers
$file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false; } else {
$exists = true; } 

여기서부터 위 포스트 바로 아래에 컬 솔루션이 있습니다.

function url_exists($url) {
return curl_init($url) !== false; } 



php에서 url이 존재하는지 확인할 때 주의해야 할 점이 몇 가지 있습니다.

  • URL 자체가 유효한가(문자열, 빈 구문이 아닌 올바른 구문), 서버 측을 빠르게 확인할 수 있습니다.
  • 응답을 기다리는 데 시간이 걸리고 코드 실행을 차단할 수 있습니다.
  • get_headers()에 의해 반환되는 모든 헤더의 형식이 올바른 것은 아닙니다.
  • 컬을 사용합니다(가능한 경우).
  • 전체 본문/콘텐츠 가져오기를 금지하고 헤더만 요청합니다.
  • URL을 리다이렉트 하는 것을 검토해 주세요.
  • 첫 번째 코드를 반환하시겠습니까?
  • 아니면 모든 리다이렉트를 따라 마지막 코드를 반환하시겠습니까?
  • 200이 될 수도 있지만 메타 태그나 자바스크립트를 사용하여 리다이렉트 할 수도 있습니다.그 후에 무슨 일이 일어날지 알아내는 것은 어렵다.

어떤 방법을 사용하든 응답을 기다리는 데 시간이 걸립니다.
모든 코드는 사용자가 결과를 알거나 요청이 타임아웃될 때까지 중지될 수 있습니다.

예를 들어, 다음 코드는 URL이 비활성화되거나 도달할 수 없는 경우 페이지를 표시하는 데 오랜 시간이 걸릴 수 있습니다.

<?php $urls = getUrls(); // some function getting say 10 or more external links
foreach($urls as $k=>$url){
// this could potentially take 0-30 seconds each
// (more or less depending on connection, target site, timeout settings...)
if( ! isValidUrl($url) ){
unset($urls[$k]);
} }
echo "yay all done! now show my site"; foreach($urls as $url){
echo "<a href="{$url}">{$url}</a><br/>"; } 

아래 함수는 도움이 될 수 있습니다.필요에 맞게 수정하는 것이 좋습니다.


function isValidUrl($url){
// first do some quick sanity checks:
if(!$url
!is_string($url)){
 return false;
}
// quick check url is roughly a valid http request: ( http://blah/... )
if( ! preg_match('/^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$/i', $url) ){
 return false;
}
// the next bit could be slow:
if(getHttpResponseCode_using_curl($url) != 200){ //
if(getHttpResponseCode_using_getheaders($url) != 200){
// use this one if you cant use curl
 return false;
}
// all good!
return true;
}
function getHttpResponseCode_using_curl($url, $followredirects = true){
// returns int responsecode, or false (if url does not exist or connection timeout occurs)
// NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings))
// if $followredirects == false: return the FIRST known httpcode (ignore redirects)
// if $followredirects == true : return the LAST
known httpcode (when redirected)
if(! $url
! is_string($url)){
 return false;
}
$ch = @curl_init($url);
if($ch === false){
 return false;
}
@curl_setopt($ch, CURLOPT_HEADER
,true);
// we want headers
@curl_setopt($ch, CURLOPT_NOBODY
,true);
// dont need body
@curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true);
// catch output (do NOT print!)
if($followredirects){
 @curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,true);
 @curl_setopt($ch, CURLOPT_MAXREDIRS
,10);
// fairly random number, but could prevent unwanted endless redirects with followlocation=true
}else{
 @curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,false);
} //
@curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5);
// fairly random number (seconds)... but could prevent waiting forever to get a result //
@curl_setopt($ch, CURLOPT_TIMEOUT
,6);
// fairly random number (seconds)... but could prevent waiting forever to get a result //
@curl_setopt($ch, CURLOPT_USERAGENT
,"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
// pretend we're a regular browser
@curl_exec($ch);
if(@curl_errno($ch)){
// should be 0
 @curl_close($ch);
 return false;
}
$code = @curl_getinfo($ch, CURLINFO_HTTP_CODE); // note: php.net documentation shows this returns a string, but really it returns an int
@curl_close($ch);
return $code;
}
function getHttpResponseCode_using_getheaders($url, $followredirects = true){
// returns string responsecode, or false if no responsecode found in headers (or url does not exist)
// NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings))
// if $followredirects == false: return the FIRST known httpcode (ignore redirects)
// if $followredirects == true : return the LAST
known httpcode (when redirected)
if(! $url
! is_string($url)){
 return false;
}
$headers = @get_headers($url);
if($headers && is_array($headers)){
 if($followredirects){

// we want the last errorcode, reverse array so we start at the end:

$headers = array_reverse($headers);
 }
 foreach($headers as $hline){

// search for things like "HTTP/1.1 200 OK" , "HTTP/1.0 200 OK" , "HTTP/1.1 301 PERMANENTLY MOVED" , "HTTP/1.1 400 Not Found" , etc.

// note that the exact syntax/version/output differs, so there is some string magic involved here

if(preg_match('/^HTTP/S+s+([1-9][0-9][0-9])s+.*/', $hline, $matches) ){// "HTTP/*** ### ***"

$code = $matches[1];

return $code;

}
 }
 // no HTTP/xxx found in headers:
 return false;
}
// no headers :
return false;
} 



$headers = @get_headers($this->_value); if(strpos($headers[0],'200')===false)return false; 

그래서 당신이 웹사이트에 연락해서 200개 이상의 것을 얻을 수 있을 때 언제든지 그것은 작동될 것입니다.




특정 서버에서는 컬을 사용할 수 없습니다.이 코드를 사용할 수 있습니다.

<?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';
} ?> 



다음 기능을 사용합니다.

/**
* @param $url
* @param array $options
* @return string
* @throws Exception
*/ function checkURL($url, array $options = array()) {
if (empty($url)) {
throw new Exception('URL is empty');
}
// list of HTTP status codes
$httpStatusCodes = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
208 => 'Already Reported',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Switch Proxy',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Payload Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I'm a teapot',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
449 => 'Retry With',
450 => 'Blocked by Windows Parental Controls',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended',
511 => 'Network Authentication Required',
599 => 'Network Connect Timeout Error'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if (isset($options['timeout'])) {
$timeout = (int) $options['timeout'];
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
}
curl_exec($ch);
$returnedStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (array_key_exists($returnedStatusCode, $httpStatusCodes)) {
return "URL: '{$url}' - Error code: {$returnedStatusCode} - Definition: {$httpStatusCodes[$returnedStatusCode]}";
} else {
return "'{$url}' does not exist";
} }