What are the best practices for setting file permissions in PHP, especially when dealing with sensitive data like passwords?

When dealing with sensitive data like passwords in PHP, it is crucial to properly set file permissions to ensure that unauthorized users cannot access the information. The best practice is to restrict access to files containing sensitive data by setting appropriate permissions. This can be done by using the chmod() function in PHP to set the file permissions to allow only the owner to read and write the file, while denying access to others.

// Set file permissions to restrict access to sensitive data
$file = 'passwords.txt';
$permissions = 0600; // Owner can read and write, others have no permissions

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