views:

106

answers:

4

The code chokes at fopen():

<?php 
  ini_set('display_errors',1);
  error_reporting(E_ALL);
  $fp = fopen("/path/to/file/some_file.txt","a") or die("can't open file");
  fwrite($fp,"some text");
  fclose($fp);
?>

And the resulting web page says:

"Warning: fopen(/path/to/file/some_file.txt) [function.fopen]: failed to open stream: Permission denied in /var/www/html/test.php on line 5 can't open file"

I tried to play with the file permissions, but to no avail. I changed the user/group with chown apache:apache some_file.txt and changed permissions with chmod 755 some_file.txt. Here is the relevant result of ls -l /path/to/file/:

-rwxr-xr-x 1 apache apache 0 Apr 12 04:16 some_file.txt
+3  A: 

You're sure that apache is the user actually running your PHP?`

And: make sure that the apache user can reach some_file.txt in the file system and that it isn't blocked by some access restriction on directories above some_file.txt.

Stefan Gehrig
I'm not sure that apache is the user, it was just an educated guess, since I saw that apache existed. I wanted to try checking if apache can read the file. However, when I tried to su apache, it told me "This account is currently not available." Ideas?
ehsanul
my apache process is run by www-data, this is in ubuntu linux. If you're running your server on linux, type sudo ps aux | less to figure out who is running what.
Matt Ellen
+1  A: 

"a" means you want to append, the same permissions as for write are needed.

You need at least 666 permissions to write by everybody. Or change file owner to server group (www-data on Ubuntu). And set the required permission.

Here is Permission calculator

If this does not helps, check the safe_mode too.

takeshin
+1  A: 

Before you go to fix an error, it would be nice to know, which error to fix.
Add these lines at the top of your script and then try again

ini_set('display_errors',1);
error_reporting(E_ALL);

PHP will tell you, what is the problem

Col. Shrapnel
Thanks. That confirmed it was an issue with permissions.
ehsanul
+2  A: 

Don't forget that even if Apache's been granted permissions to read the file, you also have to grant Apache access to ALL of the parent directories.

/path/to/file/
/path/to
/path

all need to grant Apache at least 'Read' permission.

Marc B
Thanks, that was it!
ehsanul