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

When handling file permissions in PHP scripts, it is important to follow best practices to ensure security and prevent unauthorized access to files. One common practice is to set appropriate file permissions using the chmod function to restrict access to specific users or groups. It is also recommended to avoid using overly permissive permissions, such as 777, as this can pose a security risk.

// Set file permissions to restrict access to specific users or groups
$filename = 'example.txt';
$permissions = 0644; // Set permissions to read and write for owner, read for group and others
chmod($filename, $permissions);