<?php

function make_gallery($folder_name) {

    $dirname = "images/$folder_name/";
    $images = glob($dirname . "*.jpg");

    foreach ($images as $image) {

        // Default title in case no EXIF title exists
        $title = 'Untitled';

        // Get EXIF data safely
        $exif = @exif_read_data($image, 0, true);

        if ($exif) {
            foreach ($exif as $key => $section) {
                foreach ($section as $name => $val) {
                    if ($key === 'IFD0' && $name === 'Title') {
                        // Strip special characters, allow a-z, A-Z, 0-9, spaces, dashes, and parentheses
                        $val = preg_replace('/[^A-Za-z0-9\- ()]/', '', $val);
                        $title = $val;
                    }
                }
            }
        }
?>
        <div class="responsive-gallery">
            <div class="gallery">
                <a href="<?php echo $image; ?>" class="big">
                    <img src="<?php echo $image; ?>" alt="<?php echo htmlspecialchars($title); ?>" title="<?php echo htmlspecialchars($title); ?>">
                </a>
            </div>
        </div>
<?php
    } // end foreach
} // end function

?>
