PHP를 통해 URL이 존재하는지 어떻게 확인할 수 있습니까?


답변:


296

여기:

$file = 'http://www.domain.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) {
    if (!$fp = curl_init($url)) return false;
    return true;
}

18
CURL-way가 이런 식으로 작동하지 않을까 걱정됩니다. 이것을 확인하십시오 : stackoverflow.com/questions/981954/…
viam0Zah

4
일부 웹 사이트는 $file_headers[0]오류 페이지 가 다릅니다 . 예를 들어 youtube.com과 같습니다. 해당 값을 가진 오류 페이지는 HTTP/1.0 404 Not Found(차이는 1.0과 1.1입니다). 그럼 어떻게해야합니까?
Krishna Raj K

21
아마도 사용하는 strpos($headers[0], '404 Not Found')트릭을 할 수
alexandru.topliceanu

12
@Mark는 동의했다! 명확히하는 strpos($headers[0], '404')것이 좋습니다!
alexandru.topliceanu

1
@ karim79는 SSRF 및 XSPA 공격을 조심하십시오
M Rostami

55

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

어떤 이유로 getHttpResponseCode_using_curl ()은 항상 200을 반환합니다.
TD_Nijboer

2
누군가 같은 문제가 발생하면 dns-nameservers를 확인하십시오. followredirects없이 opendns를 사용하십시오 stackoverflow.com/a/11072947/1829460
TD_Nijboer

리디렉션을 처리 할 수있는 유일한 답변 인 +1 성공 만 정렬 return $code하도록 변경if($code == 200){return true;} return false;
Birrel

@PKHunter : 아니요. 빠른 preg_match 정규식은 간단한 예이며 여기에 나열된 모든 URL과 일치하지는 않습니다. 이 테스트 URL을 참조하십시오. regex101.com/r/EpyDDc/2 더 나은 것을 원하면 diegoperini 의 링크 ( mathiasbynens.be/demo/url-regex ) 에 나열된 것으로 바꾸십시오 . 그것은 그들 모두와 일치하는 것 같습니다.이 테스트 링크를
MoonLite

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

그래서 당신이 웹 사이트에 연락하고 200이 아닌 다른 것을 얻으면 언제든지 작동합니다.


13
그러나 리디렉션이라면 어떻게 될까요? 도메인은 여전히 ​​유효하지만 생략됩니다.
Eric Leroy

4
위의 한 줄에 : return strpos(@get_headers($url)[0],'200') === false ? false : true. 유용 할 수 있습니다.
Dejv

$ this is PHP는 현재 객체에 대한 참조입니다. 참조 : php.net/manual/en/language.oop5.basic.php 입문서 : phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html 코드 스 니펫은 클래스에서 가져 왔으며 그에 따라 수정되지 않았습니다. .
Marc Witteveen

18

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

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


8
$url = 'http://google.com';
$not_url = 'stp://google.com';

if (@file_get_contents($url)): echo "Found '$url'!";
else: echo "Can't find '$url'.";
endif;
if (@file_get_contents($not_url)): echo "Found '$not_url!";
else: echo "Can't find '$not_url'.";
endif;

// Found 'http://google.com'!Can't find 'stp://google.com'.

2
allow-url-fopen이 해제되어 있으면 작동하지 않습니다. - php.net/manual/en/...
다니엘 폴 Searles

2
첫 번째 바이트 만 읽는 것이 좋습니다 ... if (@file_get_contents ($ url, false, NULL, 0,1))
Daniel

8
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;
}

8

이 기능을 사용합니다 :

/**
 * @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";
    }
}

5

Pinterest로 미친 결과를 얻었을 때 karim79의 get_headers () 솔루션이 효과가 없었습니다.

get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Array
(
    [url] => https://www.pinterest.com/jonathan_parl/
    [exists] => 
)

get_headers(): Failed to enable crypto

Array
(
    [url] => https://www.pinterest.com/jonathan_parl/
    [exists] => 
)

get_headers(https://www.pinterest.com/jonathan_parl/): failed to open stream: operation failed

Array
(
    [url] => https://www.pinterest.com/jonathan_parl/
    [exists] => 
) 

어쨌든,이 개발자는 cURL이 get_headers ()보다 빠르다는 것을 보여줍니다.

http://php.net/manual/fr/function.get-headers.php#104723

많은 사람들이 karim79에게 cURL 솔루션을 고치라고 요청했기 때문에 오늘 구축 한 솔루션이 있습니다.

/**
* Send an HTTP request to a the $url and check the header posted back.
*
* @param $url String url to which we must send the request.
* @param $failCodeList Int array list of code for which the page is considered invalid.
*
* @return Boolean
*/
public static function isUrlExists($url, array $failCodeList = array(404)){

    $exists = false;

    if(!StringManager::stringStartWith($url, "http") and !StringManager::stringStartWith($url, "ftp")){

        $url = "https://" . $url;
    }

    if (preg_match(RegularExpression::URL, $url)){

        $handle = curl_init($url);


        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($handle, CURLOPT_HEADER, true);

        curl_setopt($handle, CURLOPT_NOBODY, true);

        curl_setopt($handle, CURLOPT_USERAGENT, true);


        $headers = curl_exec($handle);

        curl_close($handle);


        if (empty($failCodeList) or !is_array($failCodeList)){

            $failCodeList = array(404); 
        }

        if (!empty($headers)){

            $exists = true;

            $headers = explode(PHP_EOL, $headers);

            foreach($failCodeList as $code){

                if (is_numeric($code) and strpos($headers[0], strval($code)) !== false){

                    $exists = false;

                    break;  
                }
            }
        }
    }

    return $exists;
}

컬 옵션을 설명하겠습니다.

CURLOPT_RETURNTRANSFER : 화면에 호출 페이지를 표시하는 대신 문자열을 반환합니다.

CURLOPT_SSL_VERIFYPEER : cUrl이 인증서를 체크 아웃하지 않습니다

CURLOPT_HEADER : 문자열에 헤더를 포함

CURLOPT_NOBODY : 문자열에 본문을 포함하지 마십시오

CURLOPT_USERAGENT : 일부 사이트는 제대로 작동하기 위해 필요합니다 (예 : https://plus.google.com )


추가 사항 :이 기능에서는 요청을 보내기 전에 URL을 확인하기 위해 Diego Perini의 정규식을 사용하고 있습니다.

const URL = "%^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu"; //@copyright Diego Perini

추가 사항 2 : 반환 코드와 메시지 만 확인하기 위해 헤더 문자열과 사용자 헤더 [0]를 분해합니다 (예 : 200, 404, 405 등).

추가 사항 3 : 때로는 코드 404 만 검증하는 것만으로는 충분하지 않으므로 (단위 테스트 참조) 모든 코드 목록을 거부 할 수있는 선택적 $ failCodeList 매개 변수가 있습니다.

물론 내 코딩을 합법화하는 단위 테스트 (모든 인기있는 소셜 네트워크 포함)는 다음과 같습니다.

public function testIsUrlExists(){

//invalid
$this->assertFalse(ToolManager::isUrlExists("woot"));

$this->assertFalse(ToolManager::isUrlExists("https://www.facebook.com/jonathan.parentlevesque4545646456"));

$this->assertFalse(ToolManager::isUrlExists("https://plus.google.com/+JonathanParentL%C3%A9vesque890800"));

$this->assertFalse(ToolManager::isUrlExists("https://instagram.com/mariloubiz1232132/", array(404, 405)));

$this->assertFalse(ToolManager::isUrlExists("https://www.pinterest.com/jonathan_parl1231/"));

$this->assertFalse(ToolManager::isUrlExists("https://regex101.com/546465465456"));

$this->assertFalse(ToolManager::isUrlExists("https://twitter.com/arcadefire4566546"));

$this->assertFalse(ToolManager::isUrlExists("https://vimeo.com/**($%?%$", array(400, 405)));

$this->assertFalse(ToolManager::isUrlExists("https://www.youtube.com/user/Darkjo666456456456"));


//valid
$this->assertTrue(ToolManager::isUrlExists("www.google.ca"));

$this->assertTrue(ToolManager::isUrlExists("https://www.facebook.com/jonathan.parentlevesque"));

$this->assertTrue(ToolManager::isUrlExists("https://plus.google.com/+JonathanParentL%C3%A9vesque"));

$this->assertTrue(ToolManager::isUrlExists("https://instagram.com/mariloubiz/"));

$this->assertTrue(ToolManager::isUrlExists("https://www.facebook.com/jonathan.parentlevesque"));

$this->assertTrue(ToolManager::isUrlExists("https://www.pinterest.com/"));

$this->assertTrue(ToolManager::isUrlExists("https://regex101.com"));

$this->assertTrue(ToolManager::isUrlExists("https://twitter.com/arcadefire"));

$this->assertTrue(ToolManager::isUrlExists("https://vimeo.com/"));

$this->assertTrue(ToolManager::isUrlExists("https://www.youtube.com/user/Darkjo666"));
}

모두에게 큰 성공

몬트리올에서 온 Jonathan Parent-Lévesque


4
function urlIsOk($url)
{
    $headers = @get_headers($url);
    $httpStatus = intval(substr($headers[0], 9, 3));
    if ($httpStatus<400)
    {
        return true;
    }
    return false;
}

3

상당히 빠른:

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');

너무 복잡한 방법 :) stackoverflow.com/questions/981954/…
Ja͢ck

URL이 존재하는 경우에 나는이 exceptionn를 얻을 다음 CURLOPT_HEADERFUNCTION 호출 할 수 없습니다
safiot

3

위의 모든 솔루션 + 여분의 설탕. (궁극의 AIO 솔루션)

/**
 * Check that given URL is valid and exists.
 * @param string $url URL to check
 * @return bool TRUE when valid | FALSE anyway
 */
function urlExists ( $url ) {
    // Remove all illegal characters from a url
    $url = filter_var($url, FILTER_SANITIZE_URL);

    // Validate URI
    if (filter_var($url, FILTER_VALIDATE_URL) === FALSE
        // check only for http/https schemes.
        || !in_array(strtolower(parse_url($url, PHP_URL_SCHEME)), ['http','https'], true )
    ) {
        return false;
    }

    // Check that URL exists
    $file_headers = @get_headers($url);
    return !(!$file_headers || $file_headers[0] === 'HTTP/1.1 404 Not Found');
}

예:

var_dump ( urlExists('http://stackoverflow.com/') );
// Output: true;

3

URL이 온라인 또는 오프라인인지 확인하기 ---

function get_http_response_code($theURL) {
    $headers = @get_headers($theURL);
    return substr($headers[0], 9, 3);
}


2

다음은 소스 코드의 첫 번째 바이트 만 읽는 해결책입니다. file_get_contents가 실패하면 false를 반환합니다. 이것은 이미지와 같은 원격 파일에서도 작동합니다.

 function urlExists($url)
{
    if (@file_get_contents($url,false,NULL,0,1))
    {
        return true;
    }
    return false;
}

0

간단한 방법은 컬입니다 (그리고 더 빠릅니다)

<?php
$mylinks="http://site.com/page.html";
$handlerr = curl_init($mylinks);
curl_setopt($handlerr,  CURLOPT_RETURNTRANSFER, TRUE);
$resp = curl_exec($handlerr);
$ht = curl_getinfo($handlerr, CURLINFO_HTTP_CODE);


if ($ht == '404')
     { echo 'OK';}
else { echo 'NO';}

?>

0

URL이 유효한지 확인하는 다른 방법은 다음과 같습니다.

<?php

  if (isValidURL("http://www.gimepix.com")) {
      echo "URL is valid...";
  } else {
      echo "URL is not valid...";
  }

  function isValidURL($url) {
      $file_headers = @get_headers($url);
      if (strpos($file_headers[0], "200 OK") > 0) {
         return true;
      } else {
        return false;
      }
  }
?>

0

get_headers () 는 HTTP 요청에 대한 응답으로 서버에서 보낸 헤더가있는 배열을 반환합니다.

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

0

cURL은 HTTP 코드를 반환 할 수 있습니다. 추가 코드가 모두 필요하다고 생각하지 않습니까?

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

0

404의 헤더를 확인할 때 고려해야 할 사항은 사이트에서 404를 즉시 생성하지 않는 경우입니다.

많은 사이트가 페이지가 PHP / ASP (et cetera) 소스에 있는지 여부를 확인하고 404 페이지로 안내합니다. 이러한 경우 헤더는 기본적으로 생성 된 404의 헤더에 의해 확장됩니다. 이 경우 404 오류는 헤더의 첫 번째 줄이 아니라 열 번째입니다.

$array = get_headers($url);
$string = $array[0];
print_r($string) // would generate:

Array ( 
[0] => HTTP/1.0 301 Moved Permanently 
[1] => Date: Fri, 09 Nov 2018 16:12:29 GMT 
[2] => Server: Apache/2.4.34 (FreeBSD) LibreSSL/2.7.4 PHP/7.0.31 
[3] => X-Powered-By: PHP/7.0.31 
[4] => Set-Cookie: landing=%2Freed-diffuser-fig-pudding-50; path=/; HttpOnly 
[5] => Location: /reed-diffuser-fig-pudding-50/ 
[6] => Content-Length: 0 
[7] => Connection: close 
[8] => Content-Type: text/html; charset=utf-8 
[9] => HTTP/1.0 404 Not Found 
[10] => Date: Fri, 09 Nov 2018 16:12:29 GMT 
[11] => Server: Apache/2.4.34 (FreeBSD) LibreSSL/2.7.4 PHP/7.0.31 
[12] => X-Powered-By: PHP/7.0.31 
[13] => Set-Cookie: landing=%2Freed-diffuser-fig-pudding-50%2F; path=/; HttpOnly 
[14] => Connection: close 
[15] => Content-Type: text/html; charset=utf-8 
) 

0

내 사이트의 링크가 유효한지 확인하기 위해 몇 가지 테스트를 실행합니다. 타사가 링크를 변경하면 알려줍니다. 인증서가 잘못 구성된 사이트에서 PHP의 get_headers가 작동하지 않는 문제가 발생했습니다.

그래서 컬이 더 빠르다는 것을 읽었고 그 결정을 내리기로 결정했습니다. 그런 다음 링크 된 문제에 999 오류가 발생하여 사용자 에이전트 문제로 판명되었습니다.

인증서가이 테스트에 유효하지 않은지 상관하지 않았으며 응답이 리디렉션인지 상관하지 않았습니다.

그런 다음 컬이 실패하면 어쨌든 get_headers를 사용하는 것으로 나타났습니다 ....

가자 ....

/**
 * returns true/false if the $url is present.
 *
 * @param string $url assumes this is a valid url.
 *
 * @return bool
 */
private function url_exists (string $url): bool
{
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_NOBODY, TRUE);             // this does a head request to make it faster.
  curl_setopt($ch, CURLOPT_HEADER, TRUE);             // just the headers
  curl_setopt($ch, CURLOPT_SSL_VERIFYSTATUS, FALSE);  // turn off that pesky ssl stuff - some sys admins can't get it right.
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  // set a real user agent to stop linkedin getting upset.
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36');
  curl_exec($ch);
  $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  if (($http_code >= HTTP_OK && $http_code < HTTP_BAD_REQUEST) || $http_code === 999)
  {
    curl_close($ch);
    return TRUE;
  }
  $error = curl_error($ch); // used for debugging.
  curl_close($ch);
  // just try the get_headers - it might work!
  stream_context_set_default(array('http' => array('method' => 'HEAD')));
  $file_headers = @get_headers($url);
  if ($file_headers)
  {
    $response_code = substr($file_headers[0], 9, 3);
    return $response_code >= 200 && $response_code < 400;
  }
  return FALSE;
}

-2

오래된 실의 일종이지만 .. 나는 이것을한다.

$file = 'http://www.google.com';
$file_headers = @get_headers($file);
if ($file_headers) {
    $exists = true;
} else {
    $exists = false;
}

하지만 ... 정확히는 아닙니다.
hackdotslashdotkill

대답이 어떻게 나아지나요?
Jah

@Jah it & # 39; s는 분명히 -2입니다. 하루 종일 화면을 응시 한 후 잠이 절반 때 나는 아마이 늦은 밤 게시 ..
hackdotslashdotkill
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.