Skip to content
PHP Logo

How can PHP be utilized to automatically generate links for navigating through multiple pages of images displayed from a folder?

To automatically generate links for navigating through multiple pages of images displayed from a folder in PHP, you can use a combination of file system functions and pagination logic. By retrieving the list of images in the folder, calculating the total number of pages based on the number of images per page, and generating links to navigate between pages, you can create a seamless browsing experience for users.

php
<?php
// Define the folder containing images
$folder = 'images/';

// Get list of images in the folder
$files = glob($folder . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

// Set number of images per page
$imagesPerPage = 10;

// Calculate total number of pages
$totalPages = ceil(count($files) / $imagesPerPage);

// Get current page number
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// Calculate starting index
$start = ($page - 1) * $imagesPerPage;

// Display images for current page
for ($i = $start; $i < min($start + $imagesPerPage, count($files)); $i++) {
    echo '<img src="' . $files[$i] . '" alt="Image ' . ($i + 1) . '">';
}

// Generate pagination links
for ($i = 1; $i <= $totalPages; $i++) {
    echo '<a href="?page=' . $i . '">' . $i . '</a> ';
}
?>