title: PHP fopen() fails on files even with wide-open permissions
body: <p>I'm currently migrating my LAMP from my Windows Server to a VPS running Debian 6.  Most everything is working, however, one of the PHP scripts was failing to write to its configured log file.  I could not determine why, so I wrote a new, simple, contrived PHP script to test the problem.</p>
  
  <pre><code>&lt;?php
          ini_set('display_errors', 1);
          error_reporting(E_ALL);
          echo exec('whoami');
          $log = fopen('/var/log/apache2/writetest/writetest.log', 'a');
          if ($log != NULL)
          {
                  fflush($log);
                  fclose($log);
                  $log = NULL;
          }
  ?&gt;
  </code></pre>
  
  <p>However, it fails with the result:</p>
  
  <pre><code>www-data Warning: fopen(/var/log/apache2/writetest/writetest.log): failed to open stream: Permission denied in /var/www/_admin/phpwritetest.php on line 5 
  </code></pre>
  
  <ul>
  <li>While I would never do it normally, to help diagnose, I set <code>/var/log/apache2/writetest/writetest.log</code> to chmod 777.  </li>
  <li>Both the directory and the file are owned by <code>www-data:www-data</code>.  </li>
  <li>The file was created with <code>touch</code>.</li>
  </ul>
  
  <p>I ran <code>strace</code> to verify which process was performing the open:</p>
  
  <pre><code>[pid 21931] lstat("/var/log/apache2/writetest/writetest.log", 0x7fff81677d30) = -1 EACCES (Permission denied)
  [pid 21931] lstat("/var/log/apache2/writetest", 0x7fff81677b90) = -1 EACCES (Permission denied)
  [pid 21931] open("/var/log/apache2/writetest/writetest.log", O_RDWR|O_CREAT|O_TRUNC, 0666) = -1 EACCES (Permission denied)
  </code></pre>
  
  <p>I checked and pid 21931 was indeed one of the apache2 child processes running under <code>www-data</code>.  As you can see, I also included <code>echo exec('whoami');</code> in the script which confirmed the script was being run by <code>www-data</code>.</p>
  
  <p>Other notes:</p>
  
  <ul>
  <li>PHP is not running in safe mode</li>
  <li>PHP <code>open_basedir</code> is not set</li>
  <li>Version info: <code>Apache/2.2.16 (Debian) PHP/5.3.3-7+squeeze3 with Suhosin-Patch mod_ssl/2.2.16 OpenSSL/0.9.8o</code></li>
  <li>uname -a: <code>2.6.32-238.19.1.el5.028stab092.2 #1 SMP Thu Jul 21 19:23:22 MSD 2011 x86_64 GNU/Linux</code></li>
  <li>This is on a VPS running under OpenVZ</li>
  <li>ls -l (file): <code>-rwxrwxrwx 1 www-data www-data 0 Sep  8 18:13 writetest.log</code></li>
  <li>ls -l (directory): <code>drwxr-xr-x 2 www-data www-data     4096 Sep  8 18:13 writetest</code></li>
  <li>Apache2's parent process runs under <code>root</code>, and the child processes under <code>www-data</code></li>
  <li>selinux is not installed (thanks to Fabio for reminding me to mention this)</li>
  <li>I have restarted apache many times and rebooted the server as well</li>
  </ul>