note 74550 rejected from function.get-headers by bjori
| From: | bjori@php.net | Date: | Tue, 17 Apr 2007 09:30:47 +0000 |
| Subject: | note 74550 rejected from function.get-headers by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-125501@lists.php.net to get a copy of this message | ||
Note Submitter: isurf23 at gmail dot com
----
I created this version of get_headers() because PHPs version would break with certain urls, and
seeing I could not find a function that worked the same as get_headers() including following the
redirects, I ended up having to create my own.
Here is the function (actually two functions but one works for the other) that works exactly like
get_headers() except it doesn't support https requests. Although I'm sure it can be easily
added.
<?
function xget_headers($url, $format=false)
{
$loop = true;
for( $i=0,$j=0; $loop === true; )
{
$loop = false;
$header = __get_headers($url);
if( is_array($header) )
{
foreach($header as $head)
{
if( ! preg_match('/:/', $head) )
$headers[$i++] = $head;
elseif( preg_match('/^(.*?): (.*)/', $head, $match) )
{
if( $format == true ) {
if( isset($headers[$match[1]]) ) {
if(!is_array($headers[$match[1]])) {
$headers[$match[1]] = array($headers[$match[1]], $match[2]);
} else {
array_push($headers[$match[1]], $match[2]);
}
if(is_array($headers["Location"]) and
!empty($headers["Location"][++$j])) {
$url = $headers["Location"][$j];
$loop = true;
}
} else {
$headers[$match[1]] = $match[2];
if(!is_array($headers["Location"]) and
!empty($headers["Location"])) {
$url = $headers["Location"];
$loop = true;
}
}
} else {
$headers[$i++] = $match[0];
if( $match[1] == "Location" ) {
$url = $match[2];
$loop = true;
}
}
}
}
}
}
unset($head, $header, $match, $url, $loop, $format);
return $headers;
}
function __get_headers($url)
{
$url_info=parse_url($url);
$fp=fsockopen($url_info['host'], 80, $errno, $errstr, 30);
if($fp) {
$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 ($eoheader==true)) {
if($header=fgets($fp, 1024)) {
if($header == "\r\n") {
$eoheader = true;
break;
}
$headers[]=trim($header);
}
}
fclose($fp);
unset($fp, $url_info, $head, $header, $errno, $errstr);
return $headers;
}
}
?>