How can you ensure that your PHP code is secure when dealing with file permissions?

When dealing with file permissions in PHP, it is important to ensure that sensitive files are not accessible to unauthorized users. One way to do this is by setting appropriate file permissions using the chmod() function. It is also important to validate user input and sanitize file paths to prevent directory traversal attacks.

// Set appropriate file permissions
$filename = 'sensitive_file.txt';
chmod($filename, 0600);

// Validate user input and sanitize file paths
$user_input = $_POST['file_path'];
$clean_path = realpath('./uploads/' . $user_input);
if (strpos($clean_path, realpath('./uploads/')) !== 0) {
    die('Invalid file path');
}