Reading data from fsockopen using fgets/fread hangs

victor_golf picture victor_golf · May 4, 2012 · Viewed 22.6k times · Source

Here is the code that I am using:

if (!($fp = fsockopen('ssl://imap.gmail.com', '993', $errno, $errstr, 15)))
    echo "Could not connect to host";
$server_response = fread($fp, 256);
echo $server_response;

fwrite($fp, "C01 CAPABILITY"."\r\n");
while (!feof($fp)) {
    echo fgets($fp, 256);
}

I get the first response:

OK Gimap ready for requests from xx.xx.xx.xx v3if9968808ibd.15 

but then the page times out. I have searched through stream_set_blocking, stream_set_timeout, stream_select, fread, etc. but could not get it to work. I need to read all the data that the server sends and then proceed with other commands (I would be retrieving emails using imap).

Thanks

Answer

DaveRandom picture DaveRandom · May 4, 2012

Your script is hanging in the while loop at the end. This is because you have used !feof() as the condition for the loop, and the server is not closing the connection. This means the feof() will always return false and the loop will continue forever.

This will not be problem when your write a full implementation, as you will be looking for response codes and can break out of the loop accordingly, for example:

<?php

  // Open a socket
  if (!($fp = fsockopen('ssl://imap.gmail.com', 993, $errno, $errstr, 15))) {
      die("Could not connect to host");
  }

  // Set timout to 1 second
  if (!stream_set_timeout($fp, 1)) die("Could not set timeout");

  // Fetch first line of response and echo it
  echo fgets($fp);

  // Send data to server
  echo "Writing data...";
  fwrite($fp, "C01 CAPABILITY\r\n");
  echo " Done\r\n";

  // Keep fetching lines until response code is correct
  while ($line = fgets($fp)) {
    echo $line;
    $line = preg_split('/\s+/', $line, 0, PREG_SPLIT_NO_EMPTY);
    $code = $line[0];
    if (strtoupper($code) == 'C01') {
      break;
    }
  }

  echo "I've finished!";