Home Projecten Diensten Portfolio Contact
EN / NL
PROJECTMODULE // GALERIJ.PHP

Galerijprojecten & Broncode

Directe link naar martijnzuidema.nl/galerij.php voor demonstratie voorbeeld.

Live Galerij Link

Open de live natuur- en vogelgalerij direct in een nieuw tabblad.

https://martijnzuidema.nl/galerij.php

Open martijnzuidema.nl/galerij.php ↗

Hoe galerij.php werkt (stap voor stap)

1. Mappen & datum uit bestandsnaam

Leest originele foto's uit /fotos en thumbnails uit /album. Het haalt ook datums tussen haakjes uit bestandsnamen (inclusief Nederlandse maanden zoals mrt, mei en okt) om netjes te sorteren.

2. Cache, veiligheid & 301-redirect

Gebruikt een HTML-cache in /album/cache voor snelle weergave, controleert paden met realpath() binnen /fotos en kan via een naam tussen [rechte haken] een 301-redirect uitvoeren.

3. Zoeken, SEO & PhotoSwipe

Ondersteunt zoeken op mapnaam vanaf 3 letters, bouwt kruimelpaden en JSON-LD-data op en opent grote foto's in de PhotoSwipe-viewer.

Broncode van galerij.php (met makkelijke uitleg)

Hieronder staat je galerij.php-broncode met duidelijke toelichting per onderdeel, zodat de werking makkelijk te volgen is.

<?php
// 1. Basisinstellingen: waar staan de foto's (/fotos) en thumbnails (/album)
define('BASE_DIR', __DIR__ . '/fotos');
define('THUMB_DIR', __DIR__ . '/album');
define('SORT_BY_TIME', false);
define('SORT_REVERSE', true);
define('SORT_BY_DATE_IN_FILENAME', true);

// Toont een 404-pagina als een map niet bestaat
function show404($message = 'Pagina niet gevonden') {
    http_response_code(404);
    include __DIR__ . '/404.php';
    exit;
}

// Zorgt dat de map voor thumbnails bestaat
if (!is_dir(THUMB_DIR)) mkdir(THUMB_DIR, 0755, true);

// Zoekt de meest recente/eerste afbeelding in een map (en eventuele submappen)
function find_first_image($folder) {
    $newestImage = null;
    $latestTime = -1;

    foreach (scandir($folder) as $f) {
        if ($f === '.' || $f === '..') continue;
        $p = "$folder/$f";

        if (is_file($p) && preg_match('/\.(jpe?g|png|gif|webp)$/i', $f)) {
            $currentTime = get_sort_date_from_filename($f);
            if ($currentTime === 0) {
                $currentTime = 1;
            }
            if ($currentTime > $latestTime) {
                $latestTime = $currentTime;
                $newestImage = $p;
            }
        } elseif (is_dir($p)) {
            $r = find_first_image($p);
            if ($r) {
                $rTime = get_sort_date_from_filename(basename($r));
                if ($rTime === 0) $rTime = 1;

                if ($rTime > $latestTime) {
                    $latestTime = $rTime;
                    $newestImage = $r;
                }
            }
        }
    }
    return $newestImage;
}

// Haalt een datum uit de bestandsnaam (bijv. "(15mei2025)") en zet NL-maanden om naar EN
function get_sort_date_from_filename($filename) {
    $nlToEnMonths = [
        'jan' => 'jan', 'feb' => 'feb', 'mrt' => 'mar',
        'apr' => 'apr', 'mei' => 'may', 'jun' => 'jun',
        'jul' => 'jul', 'aug' => 'aug',
        'sept' => 'sep', 'okt' => 'oct', 'nov' => 'nov', 'dec' => 'dec'
    ];

    if (preg_match('/\((.*?)\)/', $filename, $matches)) {
        $dateString = $matches[1];
        if (preg_match('/(\d{1,2})([a-zA-Z]{3,4})(\d{4})/', $dateString, $dateParts)) {
            $month = strtolower($dateParts[2]);
            $englishMonth = $nlToEnMonths[$month] ?? $month;
            $formattedDate = "{$dateParts[1]} {$englishMonth} {$dateParts[3]}";
            $timestamp = strtotime($formattedDate);
            if ($timestamp !== false) {
                return strtotime(date('Y-m-d', $timestamp));
            }
        }
        if (preg_match('/(\d{4})/', $dateString, $yearParts)) {
            $year = $yearParts[1];
            $timestamp = strtotime("1 January $year");
            if ($timestamp !== false) {
                return $timestamp;
            }
        }
    }
    return 0;
}

include __DIR__ . '/cookie.php';

// 2. Cache-systeem: bewaart opgeslagen HTML zodat normale pagina's razendsnel laden
$isSearch = isset($_GET['search']) && strlen($_GET['search']) >= 3;

if (!$isSearch) {
    $currentDirParam = $_GET['dir'] ?? 'hoofdpagina';
    $cacheKey = md5($currentDirParam);

    $cacheDir = THUMB_DIR . '/cache';
    if (!is_dir($cacheDir)) {
        mkdir($cacheDir, 0755, true);
    }

    $cacheFile = $cacheDir . "/cache_" . $cacheKey . ".html";

    if (file_exists($cacheFile) && $banner_akkoord_gegeven) {
        readfile($cacheFile);
        exit;
    }
    ob_start();
}

// 3. Mapkeuze controleren; lukt dat niet, dan zoeken op wetenschappelijke naam tussen [...] voor 301-redirect
$dir = $_GET['dir'] ?? '';
$dir = str_replace(['..', './', '\\'], '', $dir);
$full = realpath(BASE_DIR . '/' . $dir);

if (!$full || strpos($full, realpath(BASE_DIR)) !== 0 || !is_dir($full)) {
    $new_dir_path = null;

    if (preg_match('/\[([^\]]+)\]/', $dir, $matches)) {
        $sci_name = trim($matches[1]);

        $finder = function($base, $target) use (&$finder) {
            $iterator = new DirectoryIterator($base);
            foreach ($iterator as $fileinfo) {
                if ($fileinfo->isDir() && !$fileinfo->isDot()) {
                    $folderName = $fileinfo->getFilename();
                    if (strpos($folderName, "[$target]") !== false) {
                        return $fileinfo->getPathname();
                    }
                    $found = $finder($fileinfo->getPathname(), $target);
                    if ($found) return $found;
                }
            }
            return null;
        };

        $foundAbsolutePath = $finder(BASE_DIR, $sci_name);

        if ($foundAbsolutePath) {
            $new_dir_path = ltrim(str_replace(realpath(BASE_DIR), '', $foundAbsolutePath), '/\\');
            $new_dir_path = str_replace('\\', '/', $new_dir_path);
        }
    }

    if ($new_dir_path) {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: galerij.php?dir=" . urlencode($new_dir_path));
        exit;
    }

    show404('Map bestaat niet.');
}
?>

Hoe ImageObject JSON-LD & PhotoSwipe samenwerken

Elke foto combineert drie onderdelen: een lichte .webp-thumbnail op de pagina, gestructureerde ImageObject-data voor zoekmachines en de volledige foto in PhotoSwipe.

<!-- 1. Gestructureerde ImageObject-data voor zoekmachines -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "ImageObject",
  "name": "<?= htmlspecialchars($aiTitle) ?>",
  "caption": "<?= $caption ?>",
  "contentUrl": "https://www.martijnzuidema.nl/fotos/<?= urlencode($dir) ?>/<?= urlencode($img['file']) ?>",
  "thumbnail": "https://www.martijnzuidema.nl/album/<?= urlencode($dir) ?>/<?= urlencode(pathinfo($img['file'], PATHINFO_FILENAME)) ?>.webp",
  "author": {
    "@type": "Person",
    "name": "Martijn Zuidema",
    "url": "https://www.martijnzuidema.nl"
  }
}
</script>

<!-- 2. Link naar grote foto + licht .webp-thumbnail in het raster -->
<a href="<?= $full_src ?>"
   class="item"
   data-pswp-width="<?= $w ?>"
   data-pswp-height="<?= $h ?>"
   data-pswp-caption="<?= $caption ?>">
  <img class="thumb lazy"
       src="<?= htmlspecialchars($directThumbWebPath) ?>"
       data-src="<?= htmlspecialchars($directImageWebPath) ?>"
       width="<?= $w ?>"
       height="<?= $h ?>"
       alt="<?= htmlspecialchars($aiTitle) ?> op martijnzuidema.nl"
       loading="lazy">
</a>

<!-- 3. PhotoSwipe-lichtbokser initialiseert op #photo-gallery -->
<script type="module">
import PhotoSwipeLightbox from '/js/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
  gallery: '#photo-gallery',
  children: 'a.item',
  pswpModule: () => import('/js/photoswipe.esm.js')
});
lightbox.init();
</script>