开发者

problem communicating with gmail imap server using fsockopen in php

i m able to communicate using the imap functions in php and also using the openssl from commandline ,i just wanted to try this doing fsockopen() in php. my code is :

<?php

$sock=fsockopen('ssl://im开发者_StackOverflow中文版ap.gmail.com', '993',$errno, $errstr);
if(!$sock){
   echo $errstr;
}
else{
   fputs($sock,"a LOGIN user@gmail.com password\r\n");
   $out=fgets($sock,2000);
   fclose($sock);
   echo $out;
}

?>

the problem is i get just the first response from the server in $out

      * OK Gimap ready for requests from **.***.63.101 jj5if832612pbc.164 

and when i change the code with the while loop for fgets ,it keeps on loading and in the end time's out without showing anything.

  <?php

  $sock=fsockopen('ssl://imap.gmail.com', '993', $errno, $errstr);
  if(!$sock){
      echo $errstr;
  }
  else{
      fputs($sock,"a LOGIN user@gmail.com password\r\n");
      while(!feof($sock)){
      $out.=fgets($sock,2000);
      }
 fclose($sock);
 echo $out;
 }

 ?>

i want to see the reply of the server in $out after i fputs the login credentials. i m able to view my emails from command line using openssl ,so i think the problem isnt my handling of imap . maybe i m missing something basic about file streams .

thanks.


The reason your loop is hanging is because feof never returns true since the socket is alive until the server closes the connection. If you wait long enough, eventually the loop will break with server answering "* BYE connection closed".

fputs($sock,"a LOGIN user@gmail.com password\r\n");

Provided you used "a" before the login command, the approach I used can be very unpleasant, so change "a" to something like "1a23ef" or anything else, so that when fetching data you won't break the loop too early, also remember to use this same key before every new command with the following:

fputs($sock,"a1fd20 LOGIN user@gmail.com password\r\n");
while(true){
 $r = fgets($sock);
  $out .= $r;
  if(strpos($r, 'a1fd20 ') === 0){
   break;
  }
}
echo $out;

This worked pretty well with FETCH 1:1 RFC822 command, but if the message being fetched has the string "a1fd20 " in position 0, the loop will still break too early as well (which I don't think will happen anyways!).


I think it's better to use standard PHP library for interaction with IMAP. Look at http://www.php.net/manual/en/book.imap.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜