PHP Get HTTP Headers
<?php
/* This code basically provides the "get_headers" function even on systems that are not running PHP 5.0. It uses strtolower() on the keys, as suggested. It uses the $h2 array instead of the $key, as suggested. It removes a line about unsetting the $key -- no reason to unset something which is no longer used. And I've changed the status header to be named "status" (instead of "0") in the array. Note that if more than one header is returned without a label, they'll be stuck in "status" -- but I think status is the only header that comes back without a label, so it works for me. So, first the code, then a sample of the usage:*/
if(!function_exists('get_headers')) {
/**
* @return array
* @param string $url
* @param int $format
* @desc Fetches all the headers
* @author cpurruc fh-landshut de
* @modified by dotpointer
* @modified by aeontech
*/
function get_headers($url,$format=0) {
$url_info=parse_url($url);
$port = isset($url_info['port']) ? $url_info['port'] : 80;
$fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
if($fp) {
$head = "HEAD ".@$url_info['path']."?".@$url_info['query'];
$head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
fputs($fp, $head);
while(!feof($fp)) {
if($header=trim(fgets($fp, 1024))) {
if($format == 1) {
$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['status'] = $header;
}
else {
$headers[strtolower($h2[0])] = trim($h2[1]);
}
}
else {
$headers[] = $header;
}
}
}
return $headers;
}
else {
return false;
}
}
}
?>