Note that get_headers **WILL follow redirections** (HTTP redirections). New headers will be appended to the array if $format=0. If $format=1 each redundant header will be an array of multiple values, one for each redirection.
<? $h2 = explode(':',$header); // the first element is the http header type, such as HTTP/1.1 200 OK, // it doesn't have a separate name, so we have to check for it. if($h2[0] == $header) { $headers
n class="keyword">[ $h2[0] ] = trim($h2[1]); } ?>
I think it looks a bit nicer :)
php.svchat.ru
aeontech, I'd edit your function a little... How about replacing this:
<? $key = array_shift(
or it. if($key == $header) { $headers[] = $header; } else {
} ?>
with this:
<? $h2 = explode(':',$header); // the first element is the http header type, such as HTTP/1.1 200 OK, // it doesn't have a separate name, so we have to check for it. if($h2[0 nbsp; } else { $headers[ $h2[0] ] = trim($h2[1]); } ?>
I think it looks a bit nicer :)
php.theraven7.com
aeontech, I'd edit your function a little... How about replacing this:
<? $key = array_shift(explode(':',$header)); // the first element is the http header type, such as HTTP 200 OK, // it doesn't have a separate name, so we have to check for it. if($key == $header) { $headers[] = $header;  .
efault">substr($header,strlen($key)+2); } ?>
with this:
<? $h2 = explode(':',$header); // the first element is the http header type, such as HTTP/1.1 200 OK, // it doesn't have a separate name, so we have to check for it. if($h2[0] == $header) { $headers[] = $header; } else { $headers[ $h2[0] ] = trim($h2[1]); } ?>
I think it looks a bit nicer :)
www.theserverpages.com
Обновление: чем больше я думаю об этом, тем менее он выглядит. Я расширил свой первоначальный ответ, который в ретроспективе был наивным.
Это нормально для базового использования, но вы можете также проверить код ответа HTTP, а не просто проверить, есть ли у вас ответ. То, как код прямо сейчас, он просто говорит вам, что кто-то слушал на другой стороне, что далеко от того, что большинство людей считают «сайт вверх».
Вот как легко изолировать код ответа HTTP (или получить false если запрос не удался):
Кроме того, есть также вопрос о перенаправлении: что вы будете делать, если увидите перенаправление? Сервер, который вы запросили, может быть в порядке, но сервер, на который вы перенаправлены, может быть отключен. Если кто-то набрал URL-адрес в браузере, он будет перенаправлен и, в конечном счете, тайм-аут, в то время как одноэтапный тест сказал бы, что все в порядке. Что делать, если есть цикл перенаправления? Браузер обнаружил бы это и, в конечном итоге, тайм-аут, но вам нужно написать довольно много кода, чтобы сделать то же самое.
Таким образом, cURL действительно выглядит как единственное верное решение, потому что оно делает все это прозрачно.
ruphp.com
How to get headers using cURL in PHP? We can know the health of a web page without visiting a link. We can get the information about link status whether is returning response 200 or it is moved it somewhere else or it is dead.
<?php /** * Script to check link validity * * @author Satya Prakash * */ $links = array(); $links[] = 'http://www.satya-weblog.com/2007/04/dynamically-populate-select-list-by.html'; $links[] = 'http://www.satya-weblog.com/2009/11/setting-site-restriction-to-google-ajax-search-api.html'; $links[] = 'http://www.satya-weblog.com/2009/08/jquery-ajax-example-of-select-values.html'; $links[] = 'http://www.satya-weblog.com/2007/05/php-file-upload-and-download-script.html'; $links[] = 'http://www.satya-weblog.com/2008/02/header-for-xml-content-in-php-file.html'; $links[] = 'http://www.satya-weblog.com/2010/02/add-input-fields-dynamically-to-form-using-javascript.html'; $links[] = 'http://www.satya-weblog.com/2007/06/javascript-show-hide-div-p-input-or-any.html'; $links[] = 'http://www.satya-weblog.com/2007/05/php-and-javascript-cookie.html'; $links[] = 'http://goo.gl/IbKHP'; foreach ($links as $link) { $ch = curl_init($link); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); // return header curl_setopt($ch, CURLOPT_NOBODY, 1); // no body return. it will faster $linkHeaders = curl_exec($ch); $curlInfo = curl_getinfo($ch); curl_close($ch); switch(intval($curlInfo['http_code']/100)) { case 2: // Status is 2xx. Page is in correct health $status = 'OK'; break; case 3: // Status is 3xx. It means redirection // Page has moved $status = 'MOVED'; if (preg_match('@^Location: (.*)$@m', $linkHeaders, $matches)) { $location = trim($matches[1]); $status .= ": $location"; } break; default: // any error $status = "Error: $curlInfo[http_code]"; break; } echo "<p> $link: $status </p> "; } ?>
Output from the above cURL code:
www.satya-weblog.com
When a browser makes a request to a php script, the browser sends some http headers which can look like this :
The php script under request , may want to access these http headers. PHP has a method getallheaders() which provides these headers. So the code should be like this :
However the method getallheaders is available only when PHP is running as a Apache Module which is the Apache2handler. When PHP is being run via CGI , this method would be unavailable. Calling it would give a :
Fatal error: Call to undefined function getallheaders()
In this case a workaround can be used which is as follows :
/** The following function gets the http headers of a client request when php is running as CGI */ if(!function_exists('getallheaders')) { function getallheaders() { foreach($_SERVER as $name => $value) { if(substr($name, 0, 5) == 'HTTP_') { $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; } } return $headers; } }
The above method provides the http headers by fetching them from the $_SERVER variable, since they are present in the server variables in the form :