Thursday, 4 June 2015

This gets the http response headers for a given url and returns them in an assoc array

 i.e. to test if a url exists $array = get_http_headers($url); if($array[result]=200) { }

<?php

function get_http_headers  ($url,$proto= "HTTP/1.0") {
         
        if(!eregi( "^http://", $url)) { $url = "http://".$url; }
        $uri = parse_url($url);
        $port = ( $uri[ "port"] ? $uri[ "port"] : 80 );
        # open a socket to the server
        $sock = fsockopen($uri[host],$port);
        if(!$sock) { return(-1); }
    if (!strlen($uri[path])) {$uri[path] = "/";}
    $req=sprintf( "HEAD %s %s\n\n", $uri[path], $proto);

        # send the request
        fputs($sock, $req);

        # get the headers
        while(!feof($sock)):
                $this_out = fgets($sock,100);
                $output.= $this_out;
        endwhile;
        fclose($sock);

        # parse them into a hash
        $hdr=split( "\n",$output);
        list($array[ "protocol"], $array[ "result"], $array[ "message"]) = split("[[:space:]]+", $hdr[0], 3);

        for($i=1,$num=count($hdr);$i<$num;$i++) {
                list($key, $val)=split( ":[[:space:]]*", $hdr[$i],2);
                $array[strtolower($key)]=$val;

                }

        return($array);
}
?>

0 comments:

Post a Comment