What are some best practices for handling file output in PHP to ensure efficient and secure operations?

When handling file output in PHP, it is important to ensure both efficiency and security. One best practice is to use proper file handling functions such as fopen(), fwrite(), and fclose() to open, write to, and close files respectively. Additionally, always sanitize user input to prevent against malicious attacks such as directory traversal or code injection.

// Example of writing to a file in a secure and efficient manner
$file = 'output.txt';
$data = 'Hello, World!';

$handle = fopen($file, 'w');
if ($handle === false) {
    die('Cannot open file for writing');
}

if (fwrite($handle, $data) === false) {
    die('Cannot write to file');
}

fclose($handle);