PHP under Apache2 Not Writing to File
Here’s the deal, I want to write a simple PHP script that writes some data into a file. For example, I have data “x=10, y=20, z=30” and want to write it into a file periodically. It is a simple task.
I looked at various tutorial and copied PHP examples on how to write text / data into a file with PHP. None worked. It does not complain, but file was not created. What’s going on? I intentionally created a file which directory that I cannot write, PHP complained. Good. But when I tried to create a file in directory that I am allowed to write, PHP did not complain but file was not created.
Most of the examples and the discussions in various forums (including stackoverflow) does not answer my question. Most of the people have problems with “permission” in writing the file. I knew that so I make sure that the directory is writeable by the (process) owner of Apache2 (it may be www-data or root). I have take good care of that, but my script is still not working. I even make the file points to “/tmp” directory. That is I make my file “/tmp/test.txt”. Did not work. That file was not created even Apache / PHP did not complain. The file was just not there.
I re-read the Apache2 configuration file and found out that under current version, Apache2 won’t let the user go outside “/var/www/” directory. Even “/tmp” is writeable, it is outside the “/var/www” directory. So it cannot be written. (Apache2 should complain! it does not.)
Solution!
So in the end, I created a directory under /var/www/html. Call it “/var/www/html/test”. Now if you try to write into “test/data.txt”, it will be created under that directory. (It is relative to the /var/www/html directory.”) Problem solved.
I have not talked about the security aspect of doing this, but at least now my problem of “cannot write into a file with PHP under Apache2” solved. Hopefully this post will help those who have similar case.