#php
Вопрос:
Функция php get_headers () — есть ли способ запретить этой функции следовать перенаправлениям?
$headers = get_headers("http://example.com/test", 1);
var_dump($headers);
ответ:
Ответ №1:
Вам нужно установить параметр max_redirects
контекста равным 1 или просто отключить follow_location
:
$context = stream_context_create(
[
'http' => [
'follow_location' => 0,
],
]
);
$headers = get_headers("http://example.com/test", true, $context);
var_dump($headers);
follow_location
интСледуйте перенаправлениям заголовка местоположения. Установите значение 0, чтобы отключить.
По умолчанию равно 1.
max_redirects
интМаксимальное количество перенаправлений, за которыми нужно следить. Значение 1 или меньше означает, что перенаправления не выполняются.
По умолчанию установлено значение 20.
Ответ №2:
Это не похоже get_headers()
на поддержку этого. Вот способ сделать это с помощью curl вместо этого:
<?php
function getHeadersDontFollowRedirects($url) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 1,
CURLOPT_FOLLOWLOCATION => false,
));
$response = curl_exec($curl);
curl_close($curl);
$headers = explode("n", $response);
$headers = array_reduce($headers, function($carry, $item) {
$pieces = explode(":", $item);
if (count($pieces) === 1) {
$carry[] = $item;
} else {
$carry[$pieces[0]] = $pieces[1];
}
return $carry;
}, []);
$headers = array_map('trim', $headers);
$headers = array_filter($headers);
return $headers;
}
var_dump(getHeadersDontFollowRedirects('http://localhost:3000/redirect.php'));
Выходы:
array(7) {
[0]=>
string(18) "HTTP/1.1 302 Found"
["Host"]=>
string(9) "localhost"
["Date"]=>
string(19) "Sat, 10 Jul 2021 00"
["Connection"]=>
string(5) "close"
["X-Powered-By"]=>
string(9) "PHP/8.0.0"
["Location"]=>
string(11) "/target.php"
["Content-type"]=>
string(24) "text/html; charset=UTF-8"
}