Are there best practices for handling file permissions in PHP scripts?

When handling file permissions in PHP scripts, it is important to follow best practices to ensure security and proper access control. One common practice is to set appropriate file permissions using chmod() function to restrict access to sensitive files and directories. It is also recommended to use file_exists() function to check if a file exists before performing any operations on it. Additionally, it is good practice to avoid using 777 permissions as it gives full access to everyone, which can pose security risks.

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