Tag Archives: file_put_contents: failed to open stream: Permission denied

[Solved] PHP write file permission failure: file_put_contents: failed to open stream: Permission denied

Questions

File is used in the method of writing log_ put_ Content this method, when executing the callback method to write the log today, prompts that there is no permission to write to the file, and reports an error

file_put_contents: failed to open stream: Permission denied

Solution process

Check the log folder permissions. Because it is generated on a daily basis, a scheduled task is executed on a regular basis, and the executing user is root. Therefore, both the generating folder user and the user group are root. In the callback method, the executing user is WWW, which is written to the log method

  if(!is_dir($dir)){
        mkdir($dir,0777,true);
    }

If the directory doesn’t exist, create a directory, but set 777 permission to create a folder in PHP’s MKDIR function. In fact, the created file still has 755 permission. In Linux system, there is a default permission when creating files/folders. This permission is affected by umask settings. We can find the following configuration in/etc/bashrc configuration file:

if [ $UID -gt 99 ] && [ "`id -gn`" = "`id -un`" ]; then
        umask 002
else
        umask 022
fi

The default umask in Linux system is 022, which is similar to our 777 & amp; After the operation, it becomes 755. That’s why. The setting here directly affects the default permission setting of Linux system, not just the problem of PHP. Therefore, it is not recommended to change 022 to 000 directly

Final solution

First create a directory, and then use Chmod to modify the permission to 777

mkdir('test', 0777);
chmod('test', 0777);