[Solved] PHP fopen() Error: failed to open stream: Permission denied

By Game Changer → Monday, December 7, 2015


Finally You have fethed the error. Is it?

Warning: fopen(/path/to/file.ext) [function.fopen]: failed to open stream: Permission denied

NOTE: You are opening a file. Make sure the correct file permissions you have.

In Ubuntu the php user group is www-data:www-data and for centos is apache:apache
- Ensure your user www-data is a member of root
adduser www-data root
Then use this command in terminal
chmod g+rw /path/to/file/

Try with php fopen again:

$myFilePath = "/path/to/file.ext";
$file_handle = fopen( $myFilePath, 'r+' );
Also! You can chmod 775 for you directory.
chmod 0775 /path/to/file/

Check the followings:

  • The directory has the correct file permissions (755) and the correct ownership. This is true all the way up the path to /home.
  • Ensure correct directory as confirmed by getcwd()
  • The test PHP script hash the same ownership as the path trying to write to and correct permission (644).
  • PHP safe mode is disabled in php.ini.
  • fopen is not a disallowed PHP function.
  • The use of open_basedir is disabled.
  • A parent directory has the wrong permissons.

Yet Not?

Remember that in order to reach a file, ALL parent directories must be readable by www-data. You strace output seems to indicate that even accessing /var/log/apache2/writetest is failing. Make sure that www-data has permissions on the following directories:
  • / (r-x)
  • /var (r-x)
  • /var/log (r-x)
  • /var/log/apache2 (r-x)
  • /var/log/apache2/writetest (rwx)
  • /var/log/apache2/writetest/writetest.log (rw-)

Yet Not Again?

Could be a SELinux issue, even if Debian doesn't ship it in the default installation your provider could have enabled it. Look for messages in /var/log with
grep -i selinux /var/log/{syslog,messages}
If that's the cause and you need to disable it, here are instructions: look for file /etc/selinux/config, here it's default content. Change SELINUX directive to disabled and reboot the system.
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#   enforcing - SELinux security policy is enforced.
#   permissive - SELinux prints warnings instead of enforcing.
#   disabled - SELinux is fully disabled.
SELINUX=disabled
# SELINUXTYPE= type of policy in use. Possible values are:
#   targeted - Only targeted network daemons are protected.
#   strict - Full SELinux protection.
SELINUXTYPE=targeted
Sael

I'm Sael. An expert coder and system admin. I enjoy to make codes easy for novice.

Website: fb/Fujael

No Comment to " [Solved] PHP fopen() Error: failed to open stream: Permission denied "