How can PHP be used to filter out specific file types when generating links?
When generating links in PHP, you may want to filter out specific file types to ensure that only certain types of files are included in the links. One way to achieve this is by using the pathinfo() function to extract the file extension and then checking if it matches the allowed file types. You can then generate the link only for the files that meet the criteria.
<?php
$files = ['file1.jpg', 'file2.pdf', 'file3.txt', 'file4.docx'];
$allowedTypes = ['jpg', 'png', 'gif'];
foreach ($files as $file) {
$fileExt = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($fileExt, $allowedTypes)) {
echo '<a href="' . $file . '">' . $file . '</a><br>';
}
}
?>