Php – Not able to open a file in php

apachefile-iofopenpermissionsPHP

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

Best Answer

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.