phphttpfwritefsockopen

PHP HTTP Request via fsockopen and fwrite not working as expected on linux


We are currently using sockets to open and write to a http connection, requests that we don't necessarily care about the response! Like tracking pings etc

This worked on our old servers and on our windows developments environments but not on our new ubuntu servers.

The code we use is as follows

        $aUrlParts = parse_url($sUrl);

        $fp = fsockopen(
            $aUrlParts['host'],
            isset($aUrlParts['port']) ? $aUrlParts['port'] : 80,
            $errno, $errstr, 30
        );

        $sHeader = "GET {$aUrlParts['path']}?{$aUrlParts["query"]} HTTP/1.1\r\n";
        $sHeader.= "Host: {$aUrlParts['host']}\r\n";
        $sHeader.= "Connection: Close\r\n\r\n";

        fwrite($fp, $sHeader);
        fclose($fp);

if I do a read after the fwrite i can get it all to work from the servers but this defeats the point of doing the request this way compared to just curling the URL

I have tried flush the socket and setting it to non blocking but non of that works! Just doing a read after is the only thing that works!

Any help is appreciated

Edit: I will mention these new servers are AWS based and I have a feeling the socket implementation on them may be different


Solution

  • I am not sure that this is worthy as an answer but I had the exact same problem and that's how I came here. My only difference was that I was trying to execute a request against the server itself.

    My solution was in the access management of the server. I had an htaccess file that was blocking anyone from viewing except for my own network and the hitch was that it was also blocking my server from requesting itself.

    So maybe it has something to do with the servers access management. Let me know if this helps.