What are the best practices for handling file permissions when using fopen in PHP?

When using fopen in PHP to open files, it is important to handle file permissions properly to ensure security and prevent unauthorized access. The best practice is to set appropriate file permissions using chmod before opening the file with fopen. This helps restrict access to the file based on the user's role and prevents potential security vulnerabilities.

$filename = 'example.txt';
$permissions = 0644; // Set appropriate permissions for the file
if (file_exists($filename)) {
    chmod($filename, $permissions);
} else {
    touch($filename);
    chmod($filename, $permissions);
}

$file = fopen($filename, 'r');
// Perform file operations
fclose($file);