[英]PHP pagination using glob to retrieve images
我正在尝试使用glob()从文件夹中检索图像,我希望将其分页,因此每页仅显示3张图像。
通过在Internet上进行挖掘以及在此处进行搜索,我得到了下面的代码。 问题在于它仅从目录中提取三个图像,当我单击下一页时,它会显示相同的3个图像。
使用glob为每个页面获取不同图像的最佳方法是什么?
$imagesDir = 'uploadedImages/thumbs/*';
$itemsPerPage = 3;
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$totalItems = getTotalItems($imagesDir);
$totalPages = ceil($totalItems / $itemsPerPage);
getItemsFromPage($currentPage, $itemsPerPage, $imagesDir);
getPager($totalPages, $currentPage);
//counts the number of files in the dir
function getTotalItems($imagesDir) {
$numImages = count(glob($imagesDir));
return $numImages;
}
//gets the files from the dir
function getItemsFromPage($page, $numItems, $dir) {
$x = 0;
//get the first 3 items from the
foreach(glob($dir) as $image)
{
if($x < $numItems)
{
echo "<li><img src=\"$image\" alt=\"$image\" /></li>";
$x++;
}
else
{
break;
}
}
}
//creates the pages and the links
function getPager($totalPages, $currentPage) {
// if we're not on the first page, show the previous page and first page links
if($currentPage > 1)
{
$prevPage = $currentPage - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevPage'><</a> ";
}
$range = 1;
// show what page we're on and the page numbers surround this page
for($x = ($currentPage - $range); $x < ($currentPage + $range) +1; $x++)
{
if(($x > 0) && ($x <= $totalPages))
{
if($x == $currentPage)
{
echo " [<b>$x</b>] ";
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?currentPage=$x'>$x</a> ";
}
}
}
// if we're not on the last page show the next page and last page links
if($currentPage != $totalPages)
{
$nextPage = $currentPage + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextPage'>></a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalPages'>>></a> ";
}
}
function getItemsFromPage($page, $numItems, $dir) {
$offset = ($page - 1) * $numItems;
$x = 0;
//get the first 3 items from the
foreach(glob($dir) as $image)
{
if($x < $offset)
{
$x++;
}
elseif($x < $numItems + $offset)
{
echo "<li><img src=\"$image\" alt=\"$image\" /></li>";
$x++;
}
else
{
break;
}
}
}
问题出在getItemsFromPage函数中。 它总是从$x = 0;
$ x应该有所不同,取决于页码
如果有人要检索不带文件扩展名的图像文件名,请使用pathinfo
返回有关文件路径的信息。
$dirname = "cards/";
$images = glob($dirname . "*.png");
foreach ($images as $image) {
$title = pathinfo($image);
echo $title['filename'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.