What are some best practices for reading and displaying data from a text file using PHP?
When reading and displaying data from a text file using PHP, it is important to properly handle file opening, reading, and closing operations. It is also essential to sanitize and validate the data before displaying it to prevent any security vulnerabilities.
<?php
// Open the text file for reading
$filename = "data.txt";
$file = fopen($filename, "r");
// Read and display each line of the file
if ($file) {
while (($line = fgets($file)) !== false) {
// Sanitize and validate the data before displaying
$data = htmlspecialchars($line);
echo $data . "<br>";
}
fclose($file);
} else {
echo "Error opening the file.";
}
?>
Keywords
Related Questions
- How can PHP be used to generate an MD5 hash of form input without compromising security?
- How can the order of operations in a PHP script affect the renaming and hashing process for uploaded files?
- How can PHP sessions be utilized to track form submission times and prevent spam or automated submissions?