Home » Php » php – Reading data from fsockopen using fgets/fread hangs

php – Reading data from fsockopen using fgets/fread hangs

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

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!";

Answer:

Your script should be working. In fact, it is working.

See the results below on my pc when I ran your code:

* OK Gimap ready for requests from xx.xx.xx.xx l5if4585958ebb.20
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY  SASL-IR AUTH=XOAUTH
C01 OK Thats all she wrote! l5if4585958ebb.20

Since gmail doesn’t disconnect you. No end of file occurs. And the page loading simply times out.

In other words: Your script will just keep waiting and waiting until gmail does disconnect, which unfortunately happens after your page load has already timed out.