What are some security considerations when reading text files in PHP?

When reading text files in PHP, it is important to consider security vulnerabilities such as directory traversal attacks and malicious file content. To mitigate these risks, it is recommended to validate and sanitize file paths before opening them, as well as properly handle and filter file contents to prevent code injection attacks.

// Validate and sanitize file path
$filename = '/path/to/file.txt';
if (strpos($filename, '..') !== false || !file_exists($filename)) {
    die('Invalid file path');
}

// Read file contents and filter for security
$file_contents = file_get_contents($filename);
$file_contents = htmlspecialchars($file_contents);

echo $file_contents;