note 74591 rejected from function.get-headers by bjori

From: Date: Fri, 20 Apr 2007 09:12:13 +0000
Subject: note 74591 rejected from function.get-headers by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-125588@lists.php.net to get a copy of this message
Note Submitter: isurf23 at gmail dot com ---- 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; } } ?>

« previous php.notes (#125588) next »