What best practices should be followed when handling file permissions in PHP?

When handling file permissions in PHP, it is important to follow best practices to ensure security and proper access control. One common practice is to set the correct permissions on files and directories to restrict access to only authorized users. This can be achieved using functions like chmod() to set permissions for files and directories.

// Set file permissions to restrict access
$file = 'example.txt';
$permissions = 0644; // Read and write for owner, read for others
if (file_exists($file)) {
    chmod($file, $permissions);
    echo "File permissions set successfully.";
} else {
    echo "File does not exist.";
}