2010-12-14 5 views

답변

24

당신은 HTTP 응답 상태 코드가 포함됩니다 Manual:

<?php 
// By default get_headers uses a GET request to fetch the headers. If you 
// want to send a HEAD request instead, you can do so using a stream context: 
stream_context_set_default(
    array(
     'http' => array(
      'method' => 'HEAD' 
     ) 
    ) 
); 
print_r(get_headers('http://example.com')); 

// gives 
Array 
(
    [0] => HTTP/1.1 200 OK 
    [Date] => Sat, 29 May 2004 12:28:14 GMT 
    [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux) 
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT 
    [ETag] => "3f80f-1b6-3e1cb03b" 
    [Accept-Ranges] => bytes 
    [Content-Length] => 438 
    [Connection] => close 
    [Content-Type] => text/html 
) 

첫 번째 배열 요소에서 get_headers($url)

예 2를 사용할 수 있습니다. 당신은 그것을 분석해야합니다.

예제의 get_headers 함수는 HTTP HEAD 요청을 발행하므로 URL 본문을 가져 오지 않습니다. 이것은 GET 요청을 사용하는 것보다 효율적이며 본문을 반환합니다.

기본값 인 컨텍스트를 설정하면 http 스트림 컨텍스트를 사용하는 모든 후속 호출이 이제 HEAD 요청을 발행합니다. 완료되면 다시 GET을 사용하도록 기본 컨텍스트를 재설정해야합니다.

PHP 또한 $http_response_header 어레이가 get_headers() 기능과 유사하다 variable $http_response_header

제공한다. HTTP wrapper을 사용할 때 $http_response_header은 HTTP 응답 헤더로 채워집니다. 로컬 범위에 $http_response_header이 생성됩니다.

원격 리소스의 콘텐츠를 다운로드하려는 경우 두 가지 요청 (하나는 리소스가 있고 다른 하나는 리소스를 가져 오는 것)을 원하지 않고 하나만 가져 오는 것입니다. 이 경우 file_get_contents과 같은 것을 사용하여 내용을 가져온 다음 변수에서 헤더를 검사하십시오.

+0

관련 : [? 하나는 원격 파일이 PHP를 사용하여 존재하는지 확인할 수 있습니다 방법] (http://stackoverflow.com/questions/981954/how-can-one-check-to-see-if -a-remote-file-exists-php) (다음을 통해 : [PHP Streams의 첫머리] (http://hakre.wordpress.com/2011/09/17/head-first-with-php-streams/)) – hakre

+0

처음에 @ 문자를 추가하여 테스트중인 URL이 존재하지 않을 때 PHP 경고를 표시하지 않습니다. 그렇게하면 사용자 정의 예외를 던질 수 있습니다. –

+1

@ FranciscoLuz 적절한 오류 처리기를 사용하여 오류 제거 기능을 사용하지 않는 것이 좋습니다. – Gordon

0

@Gordon - 답변을 바탕으로 한보다 완벽한 라이브러리 루틴입니다. 여기에는 URL 유효성, 일부 오류 처리 및 반환 된 헤더 구문 분석에 대한 예비 검사가 포함됩니다. 또한 합리적인 단계 수의 리디렉션 체인을 따릅니다.

@FranciscoLuz에 사과와
class cLib { 
    static $lasterror = 'No error set yet'; 
    /** 
    * @brief See with a URL is valid - i.e. a page can be successfully retrieved from it without error 
    * @param string $url The URL to be checked 
    * @param int $nredirects The number of redirects check so far 
    * @return boolean True if OK, false if the URL cannot be fetched 
    */ 
    static function checkUrl($url, $nredirects = 0) { 
     // First, see if the URL is sensible 
     if (filter_var($url, FILTER_VALIDATE_URL) === false) { 
      self::$lasterror = sprintf('URL "%s" did not validate', $url); 
      return false; 
     } 
     // Now try to fetch it 
     $headers = @get_headers($url); 
     if ($headers == false) { 
      $error = error_get_last(); 
      self::$lasterror = sprintf('URL "%s" could not be read: %s', $url, $error['message']); 
      return false; 
     } 
     $status = $headers[0]; 
     $rbits = explode(' ', $status); 
     if (count($rbits) < 2) { 
      self::$lasterror = sprintf('Cannot parse status "%s" from URL "%s"', $status, $url); 
      return false; 
     } 
     if (in_array($rbits[1], array(301, 302, 304, 307, 308))) { 
      // This URL has been redirected. Follow the redirection chain 
      foreach ($headers as $header) { 
       if (cLib::startsWith($header, 'Location:')) { 
        if (++$nredirects > 10) { 
         self::$lasterror = sprintf('URL "%s" was redirected over 10 times: abandoned check', $url); 
         return false; 
        } 
        return self::checkUrl(trim(substr($header, strlen('Location:'))), $nredirects); 
       } 
      } 
      self::$lasterror = sprintf('URL "%s" was redirected but location could not be identified', $url); 
      return false; 
     } 
     if ($rbits[1] != 200) { 
      self::$lasterror = sprintf('URL "%s" returned status "%s"', $url, $status); 
      return false; 
     } 
     return true; 
    } 
} 

은 - 당신이 사용자 입력에 따라 오류를 기대하는 경우는 "@ 및 error_get_last"방법은 나에게 완벽하게 합리적인 것 같다 - 난 아무것도 더 적절한 set_error_handler를 사용하는 방법에 대한이 있다고 보지 않는다 .

아직 따로 대답하지 않고 @ Gordon의 답변으로 편집해야했는지 확실하지 않습니다. 누군가 조언 할 수 있습니까?

0
public function isLink($url) 
{ 
    $result = false; 
    if (!filter_var($url, FILTER_VALIDATE_URL) === false) { 
     $getHeaders = get_headers($url); 
     $result = strpos($getHeaders[0], '200') !== false; 
    } 
    return $result; 
} 
관련 문제