What are the best practices for handling file permissions and writing to files in PHP to avoid errors and security risks?

When handling file permissions and writing to files in PHP, it is important to ensure that the appropriate permissions are set to prevent unauthorized access and potential security risks. One best practice is to use the correct file permissions (e.g., 0644 for files and 0755 for directories) and to sanitize user input to prevent injection attacks. Additionally, it is recommended to use PHP functions like `file_put_contents()` that handle file writing securely.

// Example of securely writing to a file with proper file permissions
$filename = 'example.txt';
$data = 'Hello, World!';

// Set appropriate file permissions
$permissions = 0644;

// Write data to the file
file_put_contents($filename, $data, LOCK_EX);

// Set file permissions
chmod($filename, $permissions);