Permission Denied on File Operation
Warning: file_put_contents(/var/log/app.log): Failed to open stream: Permission deniedQuick Answer
PHP does not have permission to read or write the specified file. Check file ownership and permissions, and ensure the web server user has appropriate access.
Why This Happens
File operations fail with permission denied when the PHP process does not have the required filesystem permissions. The web server typically runs as a user like www-data, apache, or nginx, which may not have access to the target file or directory.
The Problem
file_put_contents('/var/log/app.log', $logMessage, FILE_APPEND);The Fix
$logDir = '/var/www/app/storage/logs';
$logFile = $logDir . '/app.log';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
file_put_contents($logFile, $logMessage, FILE_APPEND);Step-by-Step Fix
- 1
Check file permissions
Run ls -la on the file and directory to see the current ownership and permission bits.
- 2
Identify the PHP user
Check which user PHP runs as with whoami in a PHP script or by checking the web server configuration.
- 3
Fix permissions
Use chown to set the correct owner or chmod to set appropriate permissions. Write to a directory the web server user owns, like a storage or tmp directory.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free