Are there any best practices for securely handling file paths when reading and displaying text files in PHP?
When reading and displaying text files in PHP, it is important to securely handle file paths to prevent directory traversal attacks. One way to do this is by using the `realpath()` function to resolve the full path of the file before reading or displaying its contents. This ensures that the file path is normalized and prevents access to files outside of the intended directory.
$file = realpath('path/to/file.txt');
if ($file && strpos($file, 'path/to/') === 0) {
$content = file_get_contents($file);
echo $content;
} else {
echo "Invalid file path";
}