file_put_contents not creating txt file

choppyfireballs picture choppyfireballs · Feb 15, 2013 · Viewed 32.6k times · Source

I currently have a php script that is running when a browser browser browses to the webpage. What I'm trying to do is write a text file when the script runs that stores a variable. The owner of the folder is apache, but everyone has read write, strictly for testing purposes. (I thought it might be a permissions issue) SELINUX is enabled on the server, and when I run the script from console it creates the text file just fine, and in the right directory.

file_put_contents("My working file location", $myString);

I'm using this line to try to write and create the text file, I know that my file location works becaus I can run it and create it in offline mode, I.E. running it through console. The problem is that the variable I'm trying to write is populated through HTTP Post, and when I run the script through the browser, or when apache runs the script, it does not write or create the file. What do I need to do to allow access to write/change syntax wise to get this script to write this text file?

Answer

Cory Klein picture Cory Klein · Feb 15, 2013

Your problem is likely due to apache not having permissions to write to the file location you specified. Go to that directory and check the permissions and group ownership with the ls command:

cd "My working file location"
ls -l .

There are three columns in the output that show the permissions, owner, and group for the directory. Most likely they are owned by root and don't have permissions for apache to write to the directory.

If this is the case, then you will see an error appear in your apache log when it tries to create the file. Try tailing your logs while running the script in your browser:

tail -f /var/log/apache2/error.log