How to give PHP write permission to a directory?
P粉512363233
2023-08-27 15:25:11
<p>I'm trying to create a file using PHP but it's not working. I'm assuming this is because it doesn't have write access (has been this problem before). I tried to test if this was the problem by chmod 0777 the folder, but this ended up causing every script in that directory to return a 500 error message until I changed it back.
How do I give PHP write access to my file system so it can create files? </p>
<p>EDIT: It is hosted on Hostgator shared hosting using Apache. </p>
<p>Edit 2: Someone asked about the code:
The code is a GD image script. I know the rest of it works just like before when I created the image every time I called it. Now I try to create them when adding new text and save them to a folder. My write line is:
imagejpeg(null,$file,85);</p>
<p>I also created a test file to check if it was just a broken script (mostly copied from tizag):
http://gearboxshow.info/rkr/lesig.jpg/testfile.txt (I don't know if/how to post the code here correctly. This is the content of the PHP script, minus the PHP tags.)</p>
<p> It returns 13,13,1 (separate lines), so it looks like it thinks it wrote something, but testfile.txt is blank (I uploaded a blank one), or doesn't exist (if I delete it)). </p>
<p>Edit 3: The server is running CentOS. </p>
Simple three-step solution
Step 1: Identify PHP User
Create a PHP file with the following content:
Upload it to your web server. The output should resemble the following:
Therefore, the PHP user is
www-data
.Step 2: Determine the directory owner
Next, check the details of the web directory via the command line:
The result should look similar to the following:
Therefore, the owner of this directory is
exampleuser1
.Step 3: Change directory owner to PHP user
Then, change the owner of the web directory to the PHP user:
Verify that the owner of the web directory has changed:
The result should look similar to the following:
At this point, the owner of
example-folder
has been successfully changed to the PHP user:www-data
.Finish! PHP should now be able to write to the directory.
A simple way is to have PHP create the directory itself first.
This can save you trouble with permissions.