I recently had a long battle with file permissions, inconsistent file ownership, and writing files with PHP. Some of the files my site was generating were owned by one particular user, while other files generated were owned by another user on the system. Files that I uploaded were consistently one user, however.
Two days of creating test scripts and watching the file ownerships change as new test files were written to the file system yielded few clues as to what could be causing inconsistent file ownership - requiring the ugly, unsafe, and unsound permissions of '0777' on certain directories that contained generated files. Yuck.
At one point, I finally realized that it must be caused by two entirely separate instances of PHP running; one at times, and the other at times. Apache surely wouldn't switch instances of PHP back and forth arbitrarily; PHP wouldn't switch users at random, either. Something very strange was happening here.
Something *I* was doing on my end must have been changing instances of PHP within the site. Well, as it turns out, that's exactly what was going on - thanks to the nifty ForceType directive in my .htaccess files.
I use ForceType (and at other times, mod_rewrite) for 'clean' URLs (no query strings). Being a bit of a neat freak and striving to adhere to REST standards as much as possible, this was a must for the site re-design.
ForceType, however, when used to cause certain files to be parsed by PHP, does not necessarily call the same instance of PHP that Apache normally calls for .php files under most configurations.
Since I use suPHP, the user that Apache / PHP runs as is different than other configurations. Well, as it turns out, on site pages that weren't using ForceType, suPHP was being used by Apache. On the pages that did use ForceType, another instance of PHP was used; this other instance ran as a different user.
The result? I had files generated by PHP that were owned by two different users. File permissions problems were abundant, to say the least. The two users weren't even in the same group, so only permissions of 0777 (bad, bad, BAD!!!) would allow the files to be consistently writable.
After identifying ForceType as the problem, I did some research online and found out that the .htaccess file calling ForceType needed only a small change for ForceType to call the suPHP instance instead of the other one.
I changed the following:
The former only works for non-suPHP configurations, while the latter works for suPHP. After changing this, the same instance of PHP was called and my file ownership became consistent.
I hope other web developers working with suPHP and ForceType find this information faster than I did.