I'm trying to use PHP to create a file, but it isn't working. I am assuming this is because it doesn't have write access (it's always been the problem before). I tried to test if this was the problem by making the folder chmod 0777, but that just ended up making every script in that directory return a 500 error message until I changed it back. How do I give PHP write access to my file system so it can a create a file?
Edit: It is hosted on Hostgator shared hosting using Apache.
Edit 2: Someone asked for the code: The code is a GD image script. I know the rest of it works as previously I was creating the image every ime it was called. Now I am trying to create them when new text is added and save them to a folder. The write line I have is: imagejpeg(null,$file,85);
I also created a test file to check if it was just a broken script (mainly copied from tizag): http://gearboxshow.info/rkr/lesig.jpg/testfile.txt (I don't know if/how to post the code here properly. Here is the contents of the PHP script, minus PHP tags.)
It returns 13,13,1 (separate lines), so it looks as if it thinks it wrote something, but the testfile.txt is blank (I uploaded a blank one), or non-existent (if I delete it).
Edit 3: The server runs CentOS.
You can use chmod() to do this.
The chmod() function in PHP is an inbuilt function which is used to change the mode of a specified file to a specific mode given by the user. The chmod() function changes the permissions of the specified file and returns true on success and false on failure.
Change chmod($fileRequest, '0777') to chmod($fileRequest, 0777) . The string '0777' will be converted to a numeric value, which will be 777 decimal, which is not what you expect; what you really want is 0777 octal.
An easy way is to let PHP create the directory itself in the first place.
<?php $dir = 'myDir'; // create new directory with 744 permissions if it does not exist yet // owner will be the user/group the PHP script is run under if ( !file_exists($dir) ) { mkdir ($dir, 0744); } file_put_contents ($dir.'/test.txt', 'Hello File');
This saves you the hassle with permissions.
Set the owner of the directory to the user running apache. Often nobody on linux
chown nobody:nobody <dirname>
This way your folder will not be world writable, but still writable for apache :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With