What best practices should be followed when reading and writing to text files in PHP?

When reading and writing to text files in PHP, it is important to follow best practices to ensure efficient and secure file operations. One common best practice is to use file handling functions like fopen, fread, fwrite, and fclose to properly open, read, write, and close files. Additionally, it is important to handle errors gracefully by checking for file existence, permissions, and other potential issues before performing any file operations.

// Example of reading a text file in PHP
$filename = 'example.txt';

if (file_exists($filename)) {
    $file = fopen($filename, 'r');
    
    if ($file) {
        while (($line = fgets($file)) !== false) {
            echo $line;
        }
        
        fclose($file);
    } else {
        echo 'Error opening file.';
    }
} else {
    echo 'File does not exist.';
}