Permission denied when opening or creating files with PHP
Solution 1
The folder your PHP script is trying to write to will probably be owned by the root user. Your PHP script is more than likely running under the www-data user if you're using a default Ubuntu/Apache/PHP setup.
As such you need to:
chown -R www-data:www-data folder
chmod -R g+w folder
If you find PHP is running under a user that is different from www-data then just change the user a group in the first line of code.
PS. change "folder" for your actual folder name.
Solution 2
The user running PHP (usually the apache user) doesn't have write permission on the folder the script is running in. Try using an absolute path, like "/tmp/test.txt" -- tmp is usually writable by any user, but the contents tend to be wiped out on reboot.
Solution 3
I am using Ubuntu and i solved it by running the command below in one directory up from the folder(.i.e uploads) i was writing the files in.
sudo chmod 777 ./uploads
Kalle Jillheden
Just so you know; the website Ninety7Seven.com is under construction right now. I hope it will be finished between 2012 and 2013!
Updated on July 09, 2022Comments
-
Kalle Jillheden almost 2 years
I can't create files with php, because the file dosent got permission for that. I get this error:
Warning: fopen(test.txt): failed to open stream: Permission denied in /web/com/example.com/index.php on line 20
Warning: fwrite() expects parameter 1 to be resource, boolean given in /web/com/example.com/index.php on line 21
Warning: fclose() expects parameter 1 to be resource, boolean given in /web/com/example.com/index.php on line 22This is the code I was using:
<?php $file = fopen("test.txt","w"); echo fwrite($file,"Hello World. Testing!"); fclose($file); ?>
Simple as that! This is example code from w3schools.
So I need help to find out how to give the file the needed permissions. I'm uploading files to my site with the net2ftp FTP web application, if it matters.
-
Kalle Jillheden about 12 yearsWhere do I type in that? When I tried to send that code to the ftp server, it responsed: 500 unknown command
-
Kalle Jillheden about 12 yearsIt didn't know what "chown" command was, but it did know the "chmod" command, BUT! When I changed "folder" to any file or folder (for example "/index.php" or "/test" (I tested with and without the quotation marks and slashes)) it respnded this: 550 Could not change perms on g+w /test: No such file or directory
-
Garry Welding about 12 yearsI assumed you were on the command line, not using an FTP client. You'd need to be on the command line to run a chown command really. The only other thing I can suggest in that case if to chmod the folder to 0777, but this isn't something I would really recommend.
-
Kalle Jillheden about 12 yearsI was using an FTP client! link! I go to "Advanced", then "Send arbitrary FTP commands to the FTP server", and in the box I type the commands...