【问题标题】:PHP script not displaying all images from directoryPHP脚本不显示目录中的所有图像
【发布时间】:2018-07-31 05:03:55
【问题描述】:

我正在尝试构建一个网页,该网页使用 PHP 显示来自文件夹的图像。但由于某种原因,它停止显示图像文件夹中的所有图像,并且只显示部分图像。我在函数中有分页,但并非所有图像都显示。我检查了目录以确保文件在那里并且它们在那里。

根据 php.ini 计算文件时,我总共得到 76 个文件。该目录有 74 个图像。但我的页面只显示 60 张图片。请帮我解决这个问题!

这是我正在使用的代码:

<?php
            function show_pagination($current_page, $last_page){
                echo '<br><div>';
                if( $current_page > 1 ){
                    echo ' <button class="button" type="button"><a href="?page='.($current_page-1).'">&lt;&lt;Previous</a></button> ';
                }

                    for($i = 1; $i <= $last_page; $i++){
                            echo ' <button class="button" type="button"><a href="?page='.$i.'">'.$i.'</a></button> ';
                    }

                if( $current_page < $last_page ){
                    echo ' <button class="button" type="button"><a href="?page='.($current_page+1).'">Next&gt;&gt</a></button> ';
                }
                echo '</div><br>';
                    echo '<div><p>Page '.$current_page.' out of '.$last_page.'</p></div><br>';
            }


            $folder = 'images/';
            $filetype = '*.*';
            $files = glob($folder.$filetype);
            $total = count($files);
            $per_page = 20;
            $last_page = (int)($total / $per_page);
            if(isset($_GET["page"])  && ($_GET["page"] <= $last_page) && ($_GET["page"] > 0) ){
                $page = $_GET["page"];
                $offset = ($per_page * ($page - 1)) + 1;
            }else{
                //echo "Page out of range showing results for page one";
                $page=1;
                $offset=0;
            }
            $max = $offset + $per_page;
            if($max>$total){
                $max = $total;
            }
            echo "Total number of files is $total";

            show_pagination($page, $last_page);
            for($i = $offset; $i< $max; $i++){
                $file = $files[$i];
                $path_parts = pathinfo($file);
                $filename = $path_parts['filename'];
                        echo "<a href='$file'><img src='$file' alt='$filename' style='height: 30%; width: 30%; border-style: solid;border-width: 2px;border-color: #000000; margin: 5px'></a>";
            }
            show_pagination($page, $last_page);

        ?>

这在某些时候对我有用,但现在不行了,所以我想知道我的 PHP 代码是否存在固有问题。我是 php 新手。

【问题讨论】:

  • 你查看图片源了吗?
  • 尝试在$last_page = (int)($total / $per_page);中使用ceil()而不是int
  • 感谢@Sinto 的帮助

标签: php html image


【解决方案1】:

问题在于您的代码行中使用的int

$last_page = (int)($total / $per_page);

使用ceil() 代替:

$last_page = ceil($total / $per_page);

原因是总图像 74/20 给出 3.7,如果我们使用 int 结果将是 3。但不止于此。如果我们使用ceil(),即使是3.1也会被转换为4。所以你不会错过任何图像。

【讨论】:

  • 在这里我添加了这个作为你的答案。
猜你喜欢
  • 2020-01-21
  • 2011-08-28
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 2018-03-08
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多