What best practices should be followed when working with file handling in PHP?

When working with file handling in PHP, it is important to follow best practices to ensure security and efficiency. This includes using proper file permissions, validating user input, and sanitizing data before writing to files. Additionally, it is recommended to close files after reading or writing to them to free up system resources.

// Example of best practices for file handling in PHP

// Open a file for writing with proper permissions
$file = fopen("example.txt", "w");
if ($file) {
    // Write sanitized user input to the file
    $data = filter_var($_POST['data'], FILTER_SANITIZE_STRING);
    fwrite($file, $data);
    
    // Close the file after writing
    fclose($file);
} else {
    echo "Error opening file for writing.";
}