0

The php script is unable to create file owing to denial of permissions.

PHP Script:

<?
echo exec('whoami');
file_put_contents('/var/www/html/sample.txt','Some random Text');
?>

Output :

apache
**Warning**: file_put_contents(/var/www/html/test/samds.txt): failed to open stream: Permission denied in **/var/www/html/index.php** on line **3**

The directory permissions are all 777

Pranjal
  • 796
  • 1
  • 8
  • 24
  • 1
    Try and use a relative path instead `file_put_contents('sample.txt'...` and (*a sidenote*) make sure that short tags are "on". Or `file_put_contents('test/samds.txt'...` as per your error message and running code from root. – Funk Forty Niner Mar 07 '14 at 15:47
  • 1
    Also, your error does not match with your `file_put_content` filepath above - the error says you're trying to place it into `/var/www/html/test/samds.txt`, but your code says different. Please show us what code you're using to get that error. – toomanyredirects Mar 07 '14 at 15:48
  • ^ Ignore that glitch. I wrote a sample script. – Pranjal Mar 07 '14 at 15:50
  • @Fred-ii- Nope, I already tried relative paths. – Pranjal Mar 07 '14 at 15:52
  • I tested your code on my server, and it worked. Are you running this on a local machine, or hosted site? @Pranjal and try to change folder permission to 755 – Funk Forty Niner Mar 07 '14 at 15:54
  • Try turning off selinux with `setenforce 0` If the file becomes accessible it is an selinux permission issue. – Andrew Feb 17 '15 at 15:56

1 Answers1

0

I have had same issue and i misplaced some configuration.Firstly remeber that the user who created the php file can read the file and if the user who created php file is different than the apache user in your case it is apache in that case you will get this exception if you try to write from different users.So what you have to do is simply,and i would suggest you to revoke the 777 permissions as i do not like idea of your files being publicity available on read and write to the world,so get it back to 755 and do the next on the command line of your server.

cd /var/www

change the user of the HTML only as we need it to be writable only,so do not touch the var and www,so basically as soon as you have navigated to he www directory you are going to change the HTML directory owner to the one who is currently running the apache server,and you got that info already,in your case it is apache so we are going to do the next,

chown apache:apache html

At this stage the html file owner will be apache so you will be able to write onto it.Anyway and meanwhile i would strongly suggest you to create separate directory inside html lets say testDir and try there,i would not suggest to change the root folder permissions,i had bad experience with them.Anyway i hope it will help as i suffer more then hour and just now got the right way to do it.This got my issue fixed,hope it will fix your's too.!

Jean Allen
  • 63
  • 3
  • 14