What are some best practices for opening, editing, and saving files using PHP?

When working with files in PHP, it is important to follow best practices to ensure proper file handling and security. When opening, editing, and saving files, always check for file existence, permissions, and errors to prevent data loss or security vulnerabilities.

// Example of opening, editing, and saving a file in PHP
$filename = 'example.txt';

// Check if the file exists and is writable
if (file_exists($filename) && is_writable($filename)) {
    // Open the file for editing
    $file = fopen($filename, 'r+');
    
    // Edit the file content
    fwrite($file, 'New content to add to the file');
    
    // Close the file after editing
    fclose($file);
    
    echo 'File edited and saved successfully.';
} else {
    echo 'Error: File does not exist or is not writable.';
}