note 74591 added to function.get-headers
| From: | isurf23 at gmail dot com | Date: | Thu, 19 Apr 2007 03:57:01 +0000 |
| Subject: | note 74591 added to function.get-headers | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-125560@lists.php.net to get a copy of this message | ||
Seems from looking at the examples below, there are none that show how to follow redirects. So here
is a function (two actually but one works for the other) that tries to emulate get_headers() for use
with PHP4 or PHP5, that will follow redirects.
<?
function xget_headers($url, $format=false)
{
for( $i=0,$j=0; isset($url); )
{
$header = __get_headers($url);
unset($url);
if( is_array($header) )
{
foreach($header as $head)
{
list($label, $value) = explode(': ', $head);
if( !isset($value) )
$headers[$i++] = $head;
elseif( $format == true )
{
if( isset($headers[$label]) ) {
if(!is_array($headers[$label]))
$headers[$label] = array($headers[$label], $value);
else
array_push($headers[$label], $value);
if(is_array($headers["Location"]) and
!empty($headers["Location"][++$j]))
$url = $headers["Location"][$j];
} else {
$headers[$label] = $value;
if(!is_array($headers["Location"]) and
!empty($headers["Location"]))
$url = $headers["Location"];
}
} else {
$headers[$i++] = $head;
if( $label == "Location" )
$url = $value;
}
}
}
}
unset($head, $header, $match,
$url, $format, $i, $j);
return $headers;
}
function __get_headers($url)
{
if( !$url_info=parse_url($url) or empty($url_info['host']) )
return;
if( $fp=fsockopen($url_info['host'], 80, $errno, $errstr, 15) )
{
stream_set_timeout($fp, 10);
$head = "GET
".$url_info['path']."?".$url_info['query']."
HTTP/1.0\r\n" .
"Host: ".$url_info['host']."\r\n".
"Connection: Close\r\n".
"Accept: */*\r\n".
"\r\n";
fputs( $fp, $head );
while(!feof($fp) or ($eoh==true)) {
if($header=fgets($fp, 1024)) {
if($header == "\r\n") {
$eoh = true;
break;
}
$headers[]=trim($header);
}
}
fclose($fp);
unset($fp, $url_info, $head, $header,
$errno, $errstr, $eoh);
return $headers;
}
}
?>
----
Server IP: 69.39.81.135
Probable Submitter: 64.91.127.101
----
Manual Page -- http://www.php.net/manual/en/function.get-headers.php
Edit -- https://master.php.net/note/edit/74591
Del: integrated -- https://master.php.net/note/delete/74591/integrated
Del: useless -- https://master.php.net/note/delete/74591/useless
Del: bad code -- https://master.php.net/note/delete/74591/bad+code
Del: spam -- https://master.php.net/note/delete/74591/spam
Del: non-english -- https://master.php.net/note/delete/74591/non-english
Del: in docs -- https://master.php.net/note/delete/74591/in+docs
Del: other reasons-- https://master.php.net/note/delete/74591
Reject -- https://master.php.net/note/reject/74591
Search -- https://master.php.net/manage/user-notes.php