Php get header


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.

For example:

<?php
$url
= 'http://google.com';
var_dump(get_headers($url,0));
/*array(18) {
  [0]=>  string(30) "HTTP/1.0 301 Moved Permanently"
  [1]=>  string(32) "Location: http://www.google.com/"
  [2]=>  string(38) "Content-Type: text/html; charset=UTF-8"
  [3]=>  string(35) "Date: Sun, 26 Sep 2010 00:59:50 GMT"
  [4]=>  string(38) "Expires: Tue, 26 Oct 2010 00:59:50 GMT"
  [5]=>  string(38) "Cache-Control: public, max-age=2592000"
....


r />  string(15) "HTTP/1.0 200 OK"
  [10]=>  string(35) "Date: Sun, 26 Sep 2010 00:59:51 GMT"
  [11]=>  string(11) "Expires: -1"
  [12]=>  string(33) "Cache-Control: private, max-age=0"
.....
}*/

/*===========================*/

var_dump(get_headers($url,1));
/*array(11) {
  [0]=>
  string(30) "HTTP/1.0 301 Moved Permanently"
  ["Location"]=>  string(22) "http://www.google.com/"
  ["Content-Type"]=>  array(2) {
    [0]=>    string(24) "text/html; charset=UTF-8"
    [1]=>    string(29) "text/html; charset=ISO-8859-1"
  }
  ["Date"]=>  array(2) {
  &.


92000"
    [1]=>    string(18) "private, max-age=0"
  }
.....
}*/
?>

php.net

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,


                           $headers[] = $header;
                       }
                       else
                       {
                          
$headers[$key]=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


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 если запрос не удался):

 $headers = get_headers('http://www.google.com'); $code = $headers ? intval(end(explode(' ', $headers[0], 2))) : 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:

Php get header

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 :

 
Host: localhost Connection: keep-alive User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: UTF-8,*;q=0.5 Cookie: username=admin; password=21232ffc3; PHPSESSID=o5m4e2td1m66c4pkjdag9vs0u2 

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 :

foreach (getallheaders() as $name => $value)  {  echo "$name: $valuen"; } 

and the output should be like this :

Host: localhost Connection: keep-alive User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: UTF-8,*;q=0.5 Cookie: username=admin; password=21232ffc3; PHPSESSID=o5m4e2td1m66c4pkjdag9vs0u2 

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 :

[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [HTTP_ACCEPT_CHARSET] => UTF-8,*;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8 [HTTP_CACHE_CONTROL] => max-age=0 [HTTP_CONNECTION] => keep-alive [HTTP_COOKIE] => __utmz=179618234.1309856897.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=179618234.703966342.1309856897.1309856897.1309856897.1 [HTTP_HOST] => www.yoursite.com [HTTP_USER_AGENT] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/11.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30 
      

The documentation mentions that the method would be available in FastCGI from php 5.4

Another method called apache_request_headers() gives the same results :

foreach (apache_request_headers() as $name => $value)  {  echo "$name: $valuen"; } 
Host: localhost Connection: keep-alive Cache-Control: max-age=0 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: UTF-8,*;q=0.5 Cookie: username=admin; password=21232f297a57a5801fc3; PHPSESSID=o5m4e2td1m66c4pkjdag9vs0u2 

This method is also unavailable in CGI mode and is available in FastCGI from php 5.4

www.binarytides.com


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.