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 22
This 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.
You can use chmod() to do this.
Set php files to 640. For maximum security you should set minimum permissions, which is 640. The owner 6 would be the one uploading the files.
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.
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.
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.
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
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