What is the best method to automatically generate a gallery by reading a directory containing JPG files using PHP?

To automatically generate a gallery by reading a directory containing JPG files using PHP, you can use the `scandir()` function to read the files in the directory, filter out only the JPG files, and then display them in a gallery format on a webpage.

<?php
$dir = 'path/to/directory'; // Specify the directory containing JPG files
$files = array_diff(scandir($dir), array('..', '.')); // Get all files in the directory
$jpg_files = preg_grep('/\.(jpg|jpeg)$/', $files); // Filter only JPG files

echo '<div class="gallery">';
foreach ($jpg_files as $file) {
    echo '<img src="' . $dir . '/' . $file . '" alt="' . $file . '">';
}
echo '</div>';
?>