【问题标题】:Reading file directly from folder in php直接从php中的文件夹读取文件
【发布时间】:2021-01-18 20:01:04
【问题描述】:

我希望我的代码直接从文件夹中读取文件(图像)。但是它只读取了一个文件(图像)并且仍然再次读取它(无穷大)它并没有停止显示一个相同的文件(图像)。但并非所有其他五个不同的文件(图片)。

<?php

    $dir_path = "image/gundam/";
    $extensions_array = array('jpg','png','jpeg');

    if(is_dir($dir_path)){
         $files = scandir($dir_path);

         for($i = 0; $i < count($files); $i++){
             while($files[$i] !='.' && $files[$i] !='..'){
                  // get file name
                  echo "File Name -> $files[$i]<br>";

                  // get file extension
                  $file = pathinfo($files[$i]);
                  $extension = $file['extension'];
                  echo "File Extension-> $extension<br>";

                  // check file extension
                  if(in_array($extension, $extensions_array)){
                  // show image
                      echo "<img src='$dir_path$files[$i]' style='width:100px;height:100px;'><br>";
                  }
              }
          }
     }
 ?>

【问题讨论】:

  • 所以你想显示该文件夹中的所有图像?
  • 是的,我想显示文件夹中的所有图像

标签: php html css web


【解决方案1】:

要非常具体地解决您的问题,您可以使用GLOB 查找文件夹中的文件,然后将它们与您的扩展名列表进行匹配,然后显示图像。您可以使用以下代码显示给定文件夹中具有特定扩展名的所有图像。

$FILES = glob($PATH."/*.*");
for ($i=0; $i<count($FILES); $i++) {
    $fileName = $FILES[$i];
    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    if (in_array($fileExtension, $ALLOWEDTYPES)) {
        echo "<img style='margin: 10px auto' height='150' width='150' src='".$fileName ."' alt='".$fileName."' />";
    } else {
        continue;
    }
}

一般来说,您也可以像上面帖子中提到的其他用户一样使用 scandir 来实现类似的结果,以显示给定文件夹中的所有图像。

$FILES = scandir($PATH);
foreach ($FILES as $index => $imageUrl) {
    echo "<img style='margin: 10px auto' height='150' width='150' src='".$PATH."/".$imageUrl."' alt='".$imageUrl."' />";
}

我在这里有一个托管在 phpsandbox 上的工作示例:https://phpsandbox.io/n/lucky-pond-poov

【讨论】:

    【解决方案2】:

    这对我有用,我在本地测试过,你不需要 for 循环来做这个

    $dir = 'var/images/';
    $extensions = array('jpg', 'jpeg', 'png', 'gif');
    
    if( false !== is_dir($dir) ) {
    
        $dir_contents = scandir( $dir );
    
        foreach($dir_contents as $images) {
    
            $file_ext = pathinfo($images, PATHINFO_EXTENSION);
    
            if( ($images !== '.') && 
                ($images !== '..') && 
                (in_array($file_ext,$extensions))
    
            ) {
    
                echo "<img src='$dir$images' style='width:100px;height:100px;'><br>";
    
            }
        }
    
    } else {
    
        echo "Path is not directory";
    
    }
    

    【讨论】:

    • 谢谢大家的帮助,我昨天刚刚试错了。唯一的问题是将while 更改为if
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    相关资源
    最近更新 更多