2

Why is this fsockopen so slow compared to the same request from a browser?

php fsockopen: 0.254 secs

browser: 0.070 secs

fsockopen request

$time = microtime(true);

if($fp = fsockopen('ssl://domain.com', 443, $errno, $errstr, 20)){
    echo "\n".(microtime(true) - $time);
    $this->request = 'POST '.$path.' HTTP/1.1'.$crlf
        .'Host: '.$this->host.$crlf
        .'Content-Type: application/x-www-form-urlencoded'.$crlf
        .'Content-Length: '.$content_length.$crlf
        .'Connection: Close'.$crlf.$crlf
        .$body;
    fwrite($fp, $this->request);

    while($line = fgets($fp)){
        if($line !== false){
            $this->response .= $line;
        }
    }

    fclose($fp);
}

echo "\n".(microtime(true) - $time);

fsockopen results

0.18865990638733
0.25424790382385

request from browser

enter image description here

clarkk
  • 27,151
  • 72
  • 200
  • 340

2 Answers2

0

It could be EOF problem, your fopen wait until timeout.

Try a lower timeout for faster return, but is not an elegant solution.

Other solution is to query connection manually with a bucle, like this example:

while (!feof($conn)) {
    print fgets($conn, 1024);
}

Source of example: https://stackoverflow.com/a/1319434/3518053

Community
  • 1
  • 1
manuelbcd
  • 3,106
  • 1
  • 26
  • 39
  • I'm performing tests but I can't reproduce the problem, with some example pages the fopen connection is very fast. May be you could give me an url which can reproduce problem? – manuelbcd May 27 '15 at 10:30
-1

I found a solution here

if connection is keep alive how to read until end of stream php

Community
  • 1
  • 1
clarkk
  • 27,151
  • 72
  • 200
  • 340