What are best practices for setting file permissions in PHP scripts?

When setting file permissions in PHP scripts, it is important to follow best practices to ensure security and proper access control. One common approach is to use the chmod function to set the desired permissions for a file or directory. It is recommended to set permissions to the minimum necessary level required for the script to function properly, and to avoid giving unnecessary access to sensitive files.

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