In the context of PHP file manipulation, what are some best practices for reading, writing, and updating file contents to ensure data integrity and security?

When reading, writing, and updating file contents in PHP, it is important to validate user input, sanitize data, and use secure file handling functions to prevent vulnerabilities such as directory traversal attacks and file injections. Always validate file paths and user input to prevent malicious code execution.

// Example of reading a file with validation and sanitization
$filename = 'example.txt';
if (strpos($filename, '..') === false && file_exists($filename)) {
    $content = file_get_contents($filename);
    // Process the file content here
} else {
    echo 'Invalid file path';
}