使用PHP从目录读取图像 [英] Read images from a directory using PHP

查看:137
本文介绍了使用PHP从目录读取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解WordPress内的PHP是否可以实现以下功能.

I am wanting to find out if the following is possible with PHP inside WordPress.

基本上,如果我的站点中有一个名为"promos"的目录,其中包含1到许多图像(因为这些图像可以更改),那么我想将其从PHP文件中读取到轮播设置中,即类似的内容对此:

Basically if I have a directory in my site called "promos" that consists of 1 to many images (as these images can change), that I would like to read from within a PHP file into a carousel setup, i.e. something similar to this:

   <div class="scrollable" id="browsable">   

   <div class="items"> 

          <?php 
            $tot_images_from_promo_dir = [get_total_image_count_in_promos_dir]; 

            for ( $counter = 1; $counter <= $tot_images_from_promo_dir; $counter ++) {
                echo "<div>";
                    echo "<a href="#"><img src="[image_from_promo_directory]" /></a>
                echo "</div>";
            }
          ?>
    </div>
</div>

基本上想用php读取促销目录中的图像总数,然后在循环最大值中使用该总数,并读取促销目录中的每个图像文件名,并传递到我的<img src=[image_name_from_promo_dir]中.

Basically want to somehow with php read total amount of images in my promo directory and then use this total in my loop max value and read each image file name in the promo directory and pass into my <img src=[image_name_from_promo_dir].

推荐答案

假定promos目录中的所有文件都是图像:

Assuming that all files in the promos directory are images:

<div class="scrollable" id="browsable">   
   <div class="items"> 
      <?php 
        if ($handle = opendir('./promos/')) {

            while (false !== ($file = readdir($handle))) {
                echo "<div>";
                    echo "<a href='#'><img src='".$file."' /></a>";
                echo "</div>";
            }
            closedir($handle);
        }
      ?>
    </div>
</div>

但是,如果目录中有不是图像的文件,则需要在显示之前进行检查. while循环将需要更改为以下内容:

If, however, there are files in the directory that are not images, you would need to check that before showing it. The while loop would need to change to something like:

while (false !== ($file = readdir($handle))) {
    if ((strpos($file, ".jpg")) || (strpos($file, ".gif"))) {
        echo "<div>";
            echo "<a href='#'><img src='".$file."' /></a>";
        echo "</div>";
    }
}

这篇关于使用PHP从目录读取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆