Подтвердить что ты не робот

Недопустимость get_headers

Запуск следующего кода

var_dump(get_headers("http://www.domainnnnnnnnnnnnnnnnnnnnnnnnnnnn.com/CraxyFile.jpg"));

Возвращает HTTP 200 вместо 404 Для любого домена или URL-адреса, который не существует

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Server: nginx/1.1.15
    [2] => Date: Mon, 08 Oct 2012 12:29:13 GMT
    [3] => Content-Type: text/html; charset=utf-8
    [4] => Connection: close
    [5] => Set-Cookie: PHPSESSID=3iucojet7bt2peub72rgo0iu21; path=/; HttpOnly
    [6] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
    [7] => Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    [8] => Pragma: no-cache
    [9] => Set-Cookie: bypassStaticCache=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; httponly
    [10] => Set-Cookie: bypassStaticCache=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; httponly
    [11] => Vary: Accept
)

Если вы запустите

var_dump(get_headers("http://www.domain.com/CraxyFile.jpg"));

Вы получаете

Array
(
    [0] => HTTP/1.1 404 Not Found
    [1] => Date: Mon, 08 Oct 2012 12:32:18 GMT
    [2] => Content-Type: text/html
    [3] => Content-Length: 8727
    [4] => Connection: close
    [5] => Server: Apache
    [6] => Vary: Accept-Encoding
)

Это так много случаев, когда get_headers доказано, что оно является решением для проверки существующего URL

Является ли это ошибкой или get_headers не является надежным способом проверки URL

Смотрите Live Demo

ОБНОВЛЕНИЕ 1

Чтобы узнать, что CURL также имеет ту же проблему

$curl = curl_init();
curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => true,CURLOPT_URL => 'idontexist.tld'));
curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
var_dump($info);

Также возвращает тот же результат

4b9b3361

Ответ 1

Проблема не связана с длиной имени домена, просто существует ли домен.

Вы используете службу DNS, которая разрешает несуществующие домены на сервере, который дает вам "дружественную" страницу ошибок, которую он возвращает с кодом ответа 200. Это означает, что это также не проблема с get_headers() в частности, это любая процедура с основополагающей зависимостью от разумного поиска DNS.

Способ справиться с этим без жесткого кодирования работы для каждой среды, в которой вы работаете, может выглядеть примерно так:

// A domain that definitely does not exist. The easiest way to guarantee that
// this continues to work is to use an illegal top-level domain (TLD) suffix
$testDomain = 'idontexist.tld';

// If this resolves to an IP, we know that we are behind a service such as this
// We can simply compare the actual domain we test with the result of this
$badIP = gethostbyname($testDomain);

// Then when you want to get_headers()
$url = 'http://www.domainnnnnnnnnnnnnnnnnnnnnnnnnnnn.com/CraxyFile.jpg';

$host = parse_url($url, PHP_URL_HOST);
if (gethostbyname($host) === $badIP) {
  // The domain does not exist - probably handle this as if it were a 404
} else {
  // do the actual get_headers() stuff here
}

Возможно, вам захочется как-то кэшировать возвращаемое значение первого вызова gethostbyname(), так как вы знаете, что ищете имя, которого не существует, и это может занять несколько секунд.