Ciao a tutti.

Ho necessità di leggere gli header HTTP inviati da un sito internet; spulciando il manuale ho trovato la funzione get_headers : fa esattamente quello che mi serve, però è solo per PHP5.

Finchè sull'hosting ci sarà installato PHP4, mi devo arrangiare. Come mi si faceva notare in un altro thread, tra i commenti alla funzione ci sono dei codici che emulano la funzione se non esiste.
Ho fatto un taglia e cuci per recuperare di quel codice i pezzi migliori, e questo è il risultato:

Codice PHP:
if(!function_exists('get_headers')) {
   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$errstr30);
       if(
$fp) {
           
$head "HEAD ".@$url_info['path']."?".@$url_info['query'];
           
$head .= " HTTP/1.1\r\nHost: ".@$url_info['host']."\r\n\r\n";
           
fputs($fp$head);
           while(!
feof($fp)) {
               if(
$header=trim(fgets($fp1024))) {
                   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 {   
                        
$foo implode':'$h2 );
                        
$foo preg_replace'/[a-zA-Z- ]*: /'''$foo );
                        
$headers[strtolower($h2[0])] = trim$foo );
                        }
                   }
                   else {
                       
$headers[] = $header;
                   }
               }
           }
           return 
$headers;
       }
       else {
           return 
false;
       }
       
fclose($fp);
   }

Funziona bene sui siti "normali", per esempio:

$url = "http://www.html.it";
print_r(get_headers($url, 1));

ottengo:

Array ( [status] => HTTP/1.1 200 OK [date] => Tue, 18 Oct 2005 11:48:59 GMT [server] => Apache [x-powered-by] => PHP/4.1.2 [content-type] => text/html; charset=iso-8859-1 )

Ovvero quello che penso ottenga un PHPista usando la funzione get_headers del php5.

Quello che non funziona sono le richieste ai siti che utilizzano i redirect tramite header: tutti i 301, 302 mi riportano un errore 400 (bad request).

Qualcuno ha idea di come si possa aggiustare questo?

Grazie dell'attenzione e buona giornata a tutti