Automatic Folder Menu PHP

13 hours ago 3
ARTICLE AD BOX

I am building a dynamic web gallery that reads subfolders from a main directory and generates a navigation menu. Once a folder is selected, the code should display image names, but they must be grouped by their file format (JPG, PNG, GIF). If, in any way, you can simplify it, please let me know!

<!DOCTYPE html> <html lang="sk"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Arimo:wght@400;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="style.css"> <title>Gallery</title> </head> <body> <?php $dir = './images'; $folders = array_diff(scandir($dir), array('..', '.')); $selectedFolder = isset($_GET['folder']) ? $_GET['folder'] : ''; ?> <header> <ul class="header-ul"> <?php foreach($folders as $f){ $filters = ['-', '_', '~']; $cleanName = ucfirst(strtolower(str_replace($filters, ' ', $f))); $activeClass = ($selectedFolder === $f) ? 'class="selected"' : ''; echo '<li><a href="index.php?folder='. $f .'" '.$activeClass.'>' .$cleanName. '</a></li>'; } ?> </ul> </header> <main> <?php if($selectedFolder && is_dir($dir . '/' . $selectedFolder)){ $files = array_diff(scandir($dir . '/' . $selectedFolder), array('..', '.')); $images = ['JPG' => [], 'PNG' => [], 'GIF' => []]; foreach ($files as $file) { $ext = strtoupper(pathinfo($file, PATHINFO_EXTENSION)); if(isset($images[$ext])){ $images[$ext][] = $file; } } foreach($images as $type => $fileList){ if(!empty($fileList)){ echo "<h2>Pictures $type</h2>"; echo '<div class="gallery-grid">'; foreach($fileList as $img){ $filters = ['-', '_', '~']; $cleanImgName = str_replace($filters, ' ', pathinfo($img, PATHINFO_FILENAME)); echo '<div class="img-container">'; echo '<a href="images/'.$selectedFolder.'/'.$img.'" target="_blank">'; echo '<img src="images/'.$selectedFolder.'/'.$img.'" alt="'.$cleanImgName.'" style="width:150px;">'; echo '<p>'.ucfirst($cleanImgName).'</p>'; echo '</a>'; echo '</div>'; } echo '</div>'; } } } ?> </main> </body> </html>
Read Entire Article