Search code examples
phpsocketspop3fsockopen

fsockopen - how to detect end of message?


I have code:

$f = fsockopen('mail.myserver.com', 110); //POP3
echo fgets($f, 4096) . '<hr>';
fputs($f, "USER login@myserver.com\r\n");
echo fgets($f) . '<br>';
fputs($f, "PASS mypass\r\n");
echo fgets($f) . '<br>';
fputs($f, "LIST\r\n");
echo fgets($f) . '<br>';
fputs($f, "RETR 1\r\n");

So far so good, but then I have a loop to receive the whole message:

while (!feof($f)) 
{
echo fgets($f, 1280);
}

and it takes forever because the script waits for timeouts to kick in—it NEVER detects EOF by itself.

How can I detect EOF and break the loop before it times out? If I use telnet then everything works—somehow telnet clients know when to stop receiving.


Solution

  • See:

    Warning If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:

    On: feof

    The workaround essentially waits default_socket_timeout and then terminates the while-loop.