What are some best practices for setting file permissions (chmod) in PHP to ensure write access for fwrite?

When using PHP's fwrite function to write to a file, it is important to ensure that the file has the correct permissions set to allow writing. To do this, you can use the chmod function to set the file permissions accordingly. A common approach is to set the file permissions to 0666, which allows both the owner and group to write to the file.

$filename = 'example.txt';
$file = fopen($filename, 'w');

// Set file permissions to allow writing
chmod($filename, 0666);

// Write to the file
fwrite($file, 'Hello, World!');

// Close the file
fclose($file);