从php中的文件夹中获取所有图像

Sks*_*dip 32 php wordpress get image

我正在使用WordPress.我有一个像这样的图像文件夹mytheme/images/myimages.

我想从文件夹中检索所有图像名称 myimages

请指教,如何获取图片名称.

sha*_*008 83

试试这个

$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");

foreach($images as $image)
{
  echo $image;
}
Run Code Online (Sandbox Code Playgroud)

  • 要获得几种类型,有一个有用的选项:`$ images = glob("$ dir/*.{jpg,png,bmp}",GLOB_BRACE); (23认同)

zur*_*4ik 17

你可以使用PHP opendir函数来完成它.

例:

$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
  if($file !== '.' && $file !== '..'){
    echo '<img src="pictures/'.$file.'" border="0" />';
  }
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*lam 7

当您想从文件夹中获取所有图像时,请使用glob()内置功能帮助获取所有图像。但是,当获得全部内容时,有时需要检查所有内容是否有效,因此在这种情况下,此代码可以为您提供帮助。此代码还将检查它是否为图像

  $all_files = glob("mytheme/images/myimages/*.*");
  for ($i=0; $i<count($all_files); $i++)
    {
      $image_name = $all_files[$i];
      $supported_format = array('gif','jpg','jpeg','png');
      $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
      if (in_array($ext, $supported_format))
          {
            echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
          } else {
              continue;
          }
    }
Run Code Online (Sandbox Code Playgroud)

想要查询更多的信息

PHP手册