title: Get unread email count using PHP
body: <p><strong>My need:</strong>
  I want to get the count of unread email in my GMail account (or any other email service), and after I get that I need it to be displayed in a webpage on my local PHP server. So I need a scripting language, that would be PHP. But I tried many examples but none of them seems to work. So basically what I want is <strong>a PHP script that can access my GMail account and return the count of unread emails to a webpage</strong>. </p>
  
  <p>I have tried this script in vain, it always keeps showing "Error" on my webpage.</p>
  
  <pre><code>&lt;?php
  
  function CountUnreadMail($host, $login, $passwd) {
      $mbox = imap_open($host, $login, $passwd);
      $count = 0;
      if (!$mbox) {
          echo "Error";
      } else {
          $headers = imap_headers($mbox);
          foreach ($headers as $mail) {
              $flags = substr($mail, 0, 4);
              $isunr = (strpos($flags, "U") !== false);
              if ($isunr)
              $count++;
          }
      }
  
      imap_close($mbox);
      return $count;
  }
  
  $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
  $username = 'username';
  $password = 'password';
  
  $count = CountUnreadMail($hostname, $username, $password);
  
  ?&gt;
  </code></pre>
  
  <p>As <a href="https://stackoverflow.com/users/1359855/chris">Chris</a> helped, I tries this script but the only thing that I see is a blank page. Here is another script that I tried in vain:</p>
  
  <pre><code>&lt;?php
  
  function mailCount($host, $login, $passwd) {
      $mbox = imap_open($host, $login, $passwd);
      $mail = '';
  
      if($mail = imap_check($mbox)) {
          return $mail-&gt;Nmsgs;
      }
  }
  
  $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
  $username = 'phpimap123'; //GMail username
  $password = 'phptesting'; //Password
  
  $count = mailCount($hostname, $username, $password);
  
  echo $count;
  
  ?
  </code></pre>
  
  <p>PS: I have made a GMail account for <strong>testing purposes only</strong>.</p>
  
  <p>I am running Mac OS X Lion on a MacBook Air. with PHP enabled and running, and I also have MAMP and it is also running.</p>