Are there any potential pitfalls to be aware of when using PHP to read and display files from a directory on a website?
One potential pitfall when using PHP to read and display files from a directory on a website is the risk of exposing sensitive files or directories to users. To mitigate this risk, it is important to properly sanitize user input and validate file paths before processing them. Additionally, setting appropriate file permissions and using secure coding practices can help prevent unauthorized access to files.
$directory = "path/to/directory/";
if (isset($_GET['file'])) {
$file = $_GET['file'];
// Validate file path to prevent directory traversal
if (strpos($file, "..") === false && file_exists($directory . $file)) {
// Display the file content
echo file_get_contents($directory . $file);
} else {
echo "Invalid file path";
}
} else {
// Display list of files in the directory
$files = scandir($directory);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
echo "<a href='?file=$file'>$file</a><br>";
}
}
}