2016-11-14 4 views
0

У меня есть папка с именем «инспекции», которая имеет несколько подпапок с именем «местоположение 1», «местоположение 2», «местоположение 3» и т. Д. 10-20 изображений в нем.PHP - папка для чтения, все подпапки и файлы в подпапках

Что я пытаюсь сделать, это прочитать каталоги папки «инспекции», а затем прочитать все файлы изображений в каждой из папок, прежде чем возвращать их в качестве галереи на моем сайте index.php. Проблема в том, что я не получаю сообщение об ошибке, но скрипт ничего не возвращает. Я считаю, что проблема заключается в генерации переменной $ files для каждой подпапки, когда я развертываю один и тот же скрипт для чтения содержимого папки на другом сайте.

Возможно, кто-то может указать мне в правильном направлении?

<?php 
$dir = './inspections/'; 
if ($handle = opendir($dir)) 
{ 
    $blacklist = array('.', '..', 'default', 'default.php', 'desc.txt'); 
    while (false !== ($folder = readdir($handle))) 
    { 
     if (!in_array($folder, $blacklist)) 
     { 
      if (file_exists($dir . $folder . '/desc.txt')) 
       { 
        while (false !== ($file = readdir($handle))) 
        { 
         if (!in_array($file, $blacklist)) 
         { 
          $chain = file_get_contents($dir . $folder . '/chain.txt'); 
          $website = file_get_contents($dir . $folder . '/website.txt'); 
          $location = file_get_contents($dir . $folder . '/location.txt'); 
          $desc = file_get_contents($dir . $folder . '/desc.txt', NULL, NULL, 0, 250) . '...'; 
          echo " 
           <!-- Post --> 
           <div class=\"post\"> 
            <div class=\"user-block\"> 
            <img class=\"img-circle img-bordered-sm\" src=\"../dist/img/logo/logo_".$chain."\" alt=\"\"> 
             <span class=\"username\"> 
              <a href=\"".$website."\" target=\"_blank\">".$folder."</a> 
             </span> 
            <span class=\"description\"><i class=\"fa fa-map-pin\"></i> ".$location." - Posted on ". $date . "</span> 
            </div> 
            <!-- /.user-block --> 
            <p>".$desc."</p> 
            <div class=\"lightBoxGallery\"> 
            <a href=\"".$dir . $folder . "/".$file."\" title=\"".$file."\" data-gallery=\"\"><img src=\"".$dir . $folder . "/".$file."\" style=\"height:100px; width:100px;\"></a> 
            </div> 
          "; 
         } 
        } 
       } 
     } 
    } 
    closedir($handle); 
} 
?> 

EDIT: следующее @JazZ предложения, я поправил код и он хорошо работает в настоящее время, однако, при условии, что один не хочет, чтобы отобразить с измененными размерами фотографий себя, а скорее эскизы хранятся в папке (например, ./location1/thumbs/), как бы я это сделал?

<?php     
$dir = './inspections/'; 
if ($handle = opendir($dir)) { 
    $blacklist = array('.', '..', 'default', 'default.php', 'desc.txt'); 
    while (false !== ($folder = readdir($handle))) { 
     if (!in_array($folder, $blacklist)) { 

        echo " 
         <!-- Post --> 
         <div class=\"post\"> 
          <div class=\"user-block\"> 
          <img class=\"img-circle img-bordered-sm\" src=\"../dist/img/logo/gallery_icon_".$chain.".jpg\" alt=\"\"> 
           <span class=\"username\"> 
            <a href=\"".$website."\" target=\"_blank\">".$hotel_name."</a>".$status." 
           </span> 
          <span class=\"description\"><i class=\"fa fa-map-pin\"></i> ".$location." - Posted on ".date('jS F, Y - H:m', strtotime($posted_on))."</span> 
          </div> 
          <!-- /.user-block --> 

          <p>".$desc."</p> 
          <div class=\"lightBoxGallery\"> 
        "; 

        foreach (glob($dir . $folder . "/*.jpg") as $filename) { 
         echo " 
          <a href=\"".$filename."\" title=\"\" data-gallery=\"\"><img src=\"".$filename."\" style=\"height:100px; width:100px;\"></a>"; 
        } 
        echo "</div> 
         </div> 
         <!-- /. POST --> 

         "; 

     } 
    } 
    closedir($handle); 
} 
?> 

ответ

1

Я думаю, что ваш вопрос приходит отсюда:

while (false !== ($file = readdir($handle))) // it reads again the same directory as it did in the first while loop 

Try, чтобы заменить его

if ($sub_handle = opendir($dir . $folder)) { 
    while (false !== ($file = readdir($sub_handle))) { 
     ... 
    } 
    closedir($sub_handle); 
} 

Кроме того, в вашем случае, я хотел бы использовать PHP glob() function

Посмотреть рабочий пример для вашего дела:

$dir = './inspections/'; 
if ($handle = opendir($dir)) { 
    $blacklist = array('.', '..', 'default', 'default.php', 'desc.txt'); 
    while (false !== ($folder = readdir($handle))) { 
     if (!in_array($folder, $blacklist)) { 
      foreach (glob($dir . $folder . "/*.png") as $filename) { 
       echo "$filename was found !"; 
       echo "\r\n"; 
      } 
     } 
    } 
    closedir($handle); 
} 

Выход:

./inspections/location_4/img_1.png was found ! 
./inspections/location_4/img_2.png was found ! 
./inspections/location_4/img_3.png was found ! 
./inspections/location_4/img_4.png was found ! 
./inspections/location_4/img_5.png was found ! 
./inspections/location_4/img_6.png was found ! 
./inspections/location_3/img_1.png was found ! 
./inspections/location_3/img_2.png was found ! 
./inspections/location_3/img_3.png was found ! 
./inspections/location_3/img_4.png was found ! 
./inspections/location_3/img_5.png was found ! 
./inspections/location_3/img_6.png was found ! 
./inspections/location_2/img_1.png was found ! 
./inspections/location_2/img_2.png was found ! 
./inspections/location_2/img_3.png was found ! 
./inspections/location_2/img_4.png was found ! 
./inspections/location_2/img_5.png was found ! 
./inspections/location_2/img_6.png was found ! 
./inspections/location_1/img_1.png was found ! 
./inspections/location_1/img_2.png was found ! 
./inspections/location_1/img_3.png was found ! 
./inspections/location_1/img_4.png was found ! 
./inspections/location_1/img_5.png was found ! 
./inspections/location_1/img_6.png was found ! 

EDIT

Для цикла в/проверок/LOCATION1/пальцы/директорий, это будет работать:

foreach (glob($dir . $folder . "/thumbs/*.png") as $filename) { 
    echo "$filename was found !"; 
    echo "\r\n"; 
} 

RE-EDIT

Чтобы шарик несколько папок с функцией glob(), ваш код должен выглядеть следующим образом:

foreach (glob($dir.$folder."{/thumbs/*.png,/*.png}", GLOB_BRACE) as $filename) { 
    echo "$filename was found !"; 
    echo "\r\n"; 
} 
+0

работала безупречно, спасибо. Единственное, что я рекомендую, - это настроить сценарий для приема всех видов изображений, а не только для * .png (хотя это все, что мне нужно, и попросил, просто предложение). большое спасибо! – Armitage2k

+0

Предполагая, что в каждой папке есть папка '/ thumbs /', как включить эту папку в массив $ filename?Я хотел бы отобразить $ thumb для каждого найденного имени файла, но это означает, что для этого массива потребуется несколько переменных для цикла foreach, это можно сделать? – Armitage2k

+0

Можете ли вы обновить свой вопрос с новым требованием, пожалуйста. Посмотрите на это сегодня днем. – JazZ

0

Возможно ниже функция помогает. Это также несколько прокомментировано. Он рекурсивно сканирует каталог (в этом случае извлекает файлы изображений из каждого каталога/подкаталога).

<?php 

    $rootPath = './inspections/'; 
    $regex  = "#(\.png$)|(\.jpg$)|(\.jpeg$)|(\.tiff$)|(\.gif$)#"; 


    /** 
    * @param string $directory => DIRECTORY TO SCAN 
    * @param string $regex  => REGULAR EXPRESSION TO BE USED IN MATCHING FILE-NAMES 
    * @param string $get   => WHAT DO YOU WANT TO GET? 'dir'= DIRECTORIES, 'file'= FILES, 'both'=BOTH FILES+DIRECTORIES 
    * @param bool $useFullPath => DO YOU WISH TO RETURN THE FULL PATH TO THE FOLDERS/FILES OR JUST THEIR BASE-NAMES? 
    * @param array $dirs   => LEAVE AS IS: USED DURING RECURSIVE TRIPS 
    * @return array 
    */ 
    function scanDirRecursive($directory, $regex=null, $get="file", $useFullPath=false, &$dirs=[], &$files=[]) { 
     $iterator    = new DirectoryIterator ($directory); 
     foreach($iterator as $info) { 
      $fileDirName  = $info->getFilename(); 

      if ($info->isFile() && !preg_match("#^\..*?#", $fileDirName)) { 
       if($get == 'file' || $get == 'both'){ 
        if($regex) { 
         if(preg_match($regex, $fileDirName)) { 
          if ($useFullPath) { 
           $files[] = $directory . DIRECTORY_SEPARATOR . $fileDirName; 
          } 
          else { 
           $files[] = $fileDirName; 
          } 
         } 
        }else{ 
         if($useFullPath){ 
          $files[] = $directory . DIRECTORY_SEPARATOR . $fileDirName; 
         }else{ 
          $files[] = $fileDirName; 
         } 
        } 
       } 
      }else if ($info->isDir() && !$info->isDot()) { 
       $fullPathName = $directory . DIRECTORY_SEPARATOR . $fileDirName; 
       if($get == 'dir' || $get == 'both') { 
        $dirs[]  = ($useFullPath) ? $fullPathName : $fileDirName; 
       } 
       scanDirRecursive($fullPathName, $regex, $get, $useFullPath, $dirs, $files); 
      } 
     } 

     if($get == 'dir') { 
      return $dirs; 
     }else if($get == 'file'){ 
      return $files; 
     } 
     return ['dirs' => $dirs, 'files' => $files]; 
    } 

    $images = scanDirRecursive($rootPath, $regex, 'file', true); 
    var_dump($images); 
Смежные вопросы