What are common pitfalls when setting file permissions in PHP scripts?

Common pitfalls when setting file permissions in PHP scripts include setting overly permissive permissions, such as 777, which can pose security risks. It is important to set the minimum necessary permissions to ensure that only authorized users can access or modify the file. Additionally, not properly sanitizing user input before using it to set file permissions can lead to vulnerabilities.

// Example of setting proper file permissions
$filename = 'example.txt';
$desired_permissions = 0644; // Set read and write permissions for owner, read permissions for group and others

if (file_exists($filename)) {
    chmod($filename, $desired_permissions);
    echo "File permissions set successfully.";
} else {
    echo "File does not exist.";
}