Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permission denied when opening or creating files with PHP

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.

like image 369
Kalle Jillheden Avatar asked Feb 08 '12 20:02

Kalle Jillheden


People also ask

How do I give PHP permission to 777?

You can use chmod() to do this.

What permissions do PHP files need?

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.

How do I change permissions in PHP?

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.


3 Answers

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.

like image 148
Garry Welding Avatar answered Oct 08 '22 16:10

Garry Welding


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.

like image 44
kitti Avatar answered Oct 08 '22 18:10

kitti


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
like image 21
HRWNdR Avatar answered Oct 08 '22 17:10

HRWNdR