What are common reasons for the "Permission denied" error when trying to write to a file in PHP?

The "Permission denied" error occurs when the PHP script does not have the necessary permissions to write to the specified file. This can happen if the file or directory is owned by a different user or if the permissions are set to read-only. To solve this issue, you can change the file permissions to allow the PHP script to write to it, or you can run the PHP script with elevated privileges.

// Example code snippet to fix "Permission denied" error when writing to a file
$file = 'example.txt';
$data = 'Hello, World!';

// Change file permissions to allow writing
chmod($file, 0644);

// Write data to file
file_put_contents($file, $data);