What are the potential pitfalls of not properly filtering file types in PHP when reading from a directory?
If file types are not properly filtered when reading from a directory in PHP, it can lead to security vulnerabilities such as executing malicious scripts or accessing sensitive files. To mitigate this risk, it is crucial to only allow specific file types to be read from the directory by checking the file extension before processing it.
$directory = "/path/to/directory/";
$allowed_file_types = array("jpg", "png", "pdf");
$files = scandir($directory);
foreach($files as $file){
$file_extension = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($file_extension, $allowed_file_types)){
// Process the file
}
}