What are some best practices for reading and manipulating content in files using PHP?

When reading and manipulating content in files using PHP, it's important to handle file operations carefully to avoid errors and security vulnerabilities. Some best practices include using file handling functions like fopen(), fread(), fwrite(), and fclose() properly, checking for file existence before reading or writing, sanitizing user input to prevent injection attacks, and using file locking to prevent race conditions.

// Example of reading content from a file
$filename = 'example.txt';

if (file_exists($filename)) {
    $file = fopen($filename, 'r');
    $content = fread($file, filesize($filename));
    fclose($file);

    // Manipulate the content here

    echo $content;
} else {
    echo 'File does not exist.';
}