hackartist
hackartist

Reputation: 5264

file_put_contents php permissions

This is a question about my system configuration and how apache/php can be affected by that. Code that was working on my dev server failed to work when I moved to production and here is the problem I boiled the error down to. I want to use file_put_contents in php to simply make a file on my system. Here is the very simple code I am using:

print file_put_contents("testfile.txt","this is my test")?"made file":"failed";

No errors are thrown but it always prints "failed". When I run it in the normal directory no file is made but when I move it to a directory with 777 permission, it will make the file but still print "failed" and save nothing into it. If I change the php file itself to have 777 permission nothing changes. If I change the target file (testtext.txt) to have 777 permission nothing changes.

The when I change the owner of the php file to be the same as the created testfile.txt nothing changes. When I try relative vs. absolute paths nothing changes. For some reason I can have php make the file but it is always empty and using file_put_contents I can't write anything in.

The created file is in the owner and group of 'www-data' while I am acting as root if that helps. What can I do to get this working? I think that my version of php is using the suhosin extension if this could have anything to do with it (or if you think there is a way to fix this in php or suhosin ini files I can do that too).

I've been hunting this for hours the last few days.

EDIT: updates based on the comments below. When I run it in CLI mode it does work but since I need to run it through apache how can I use this fact? Does this tell us something about where or what is stopping the file writing? Also the file_put_contents call is actually returning "false" and not zero.

Upvotes: 2

Views: 15541

Answers (2)

Besnik
Besnik

Reputation: 6529

The function returns the number of bytes that were written to the file, or FALSE on failure.

Make sure that mydir is writable (by the apache user - apache2 or www-data). To check if content was written to file use the === operator:

$file = "mydir/testfile.txt";

$result = file_put_contents($file,"this is my test");

if ($result === false)
{
  echo "failed to write to $file";
}
else
{
  echo "successfully written $result bytes to $file";
}

For debugging i recommend to define this at the top of your php file:

error_reporting(-1);
ini_set('display_errors', true);

Upvotes: 1

Adam Fowler
Adam Fowler

Reputation: 1751

You have to set permissions as 777 for the apache user. Apache also needs to be able to 'create' new files. I'm sure that if you tried writing to a file with 777 permissions that it would work.

Upvotes: 1

Related Questions