Search code examples
phphttpheaderfgets

Parse HTTP Header from fsockopen with PHP?


I have a script set up that for reasons of necessity gets both the HTTP Response header and then content of a GET request using fsock.

function checkUrl($host,$url,$port) {
$fp = fsockopen($host, $port, $errno, $errstr, 10);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET $url HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $response = fgets($fp, 1024);
        print(substr($response,9,3));
    }
    fclose($fp);
}
}

I call it and get all the proper data back if I simply echo it all out. But actually all I need to return from the function is the HTTP STATUS Code.

i.e. 404 or 200 or 301 etc

But the code above gives the error code sure, but then with a load of gibberish at the end which I don't understand when I have limited to 3 chars!

e.g.

404, 2BM_n: Encype HThe tp-me=srcsrclanstaPre> lanmg=[0][1][2][3][4][5][6][7][8][9][10[11[12 swt.i> ypeeleamiize#99eco#66ade#33izeine#CCize { #66izeeig tmardespath=th=th=th=th=th=th=spardeolordeignign bocol widwidwid col bler> td Sorabl> e> rdeolordespath=th=th= bo spardeoloe="lanSen>

Which leads me to believe that my response is actually more complex than just a string right? Something special with the header or am I misunderstanding how fgets is working? Any help much appreciated


Solution

  • The problem is you are printing out that substring for every block of 1024 characters instead of just the first. The solution is to not do the loop. Change this:

    while (!feof($fp)) {
        $response = fgets($fp, 1024);
        print(substr($response,9,3));
    }
    

    To just this:

    $response = fgets($fp, 1024);
    print(substr($response,9,3));
    

    Or even just this, really, since you only need the first 13 characters, not the first 1024:

    $response = fgets($fp, 13);
    print(substr($response,9,3));