What are the best practices for handling file opening and writing in PHP?

When handling file opening and writing in PHP, it is important to follow best practices to ensure security and efficiency. Always check if the file exists before opening it, handle errors properly, and close the file after writing to it. Additionally, consider using file locking to prevent concurrency issues when multiple processes are writing to the same file.

// Check if the file exists before opening it
$filename = 'example.txt';
if (file_exists($filename)) {
    // Open the file for writing
    $file = fopen($filename, 'w');
    
    // Handle errors if the file cannot be opened
    if ($file === false) {
        die('Unable to open file');
    }
    
    // Write to the file
    fwrite($file, 'Hello, world!');
    
    // Close the file
    fclose($file);
} else {
    echo 'File does not exist';
}