What are common pitfalls when using PHP to read directories and display specific file types?
One common pitfall when using PHP to read directories and display specific file types is not properly filtering the files based on their type before displaying them. This can result in displaying unwanted files or potentially harmful files to users. To solve this issue, you should check the file extension before displaying it to ensure it matches the desired file type.
<?php
$dir = 'path/to/directory';
$allowed_file_types = ['jpg', 'png', 'gif'];
$files = scandir($dir);
foreach ($files as $file) {
$file_info = pathinfo($file);
if (in_array($file_info['extension'], $allowed_file_types)) {
echo '<img src="' . $dir . '/' . $file . '" alt="' . $file . '">';
}
}
?>
Related questions
-
PHP code formatting indentation
-
PHP HTML dynamic content
-
foreach PHP arrays