简体   繁体   中英

PHP - Loop through folders, open each docx file and replace string

I have a script that:

  • goes through each folder and subfolder of my "./sample/" directory
  • opens each .docx file
  • replaces a string such as "##PROPERTY##" with my $_POST['property'] variable
  • zips the folder content
  • launches a download

Now, running portions of the code individually, it does what is needed. However, when putting it all together, it dies while scanning the subfolders for docx files.

My folder structure is like this:

./sample/

  • /IT/it1.docx
  • /F&B/fb1.docx
  • /FO/fo1.docx
  • sample1.docx

The problem seems to occur during the is_dir($dir) part for the level 1 folders. Any ideas what could cause this?

    <?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    // form variables
    $holidex = strtoupper($_POST['holidex']);
    $property = $_POST['property'];
    $brand = $_POST['brand'];
    $division = $_POST['division'];
    $language = $_POST['language'];
    $date_issued = $_POST['date_issued'];
    $approved_by = $_POST['approved_by'];

    // script variables
    //$dir = './Sample_SOP_-_'.$brand.'_('.$language.')';   //dir to scan like ./sample/
    $dir = './sample/';                                     //dir to scan like ./sample/
    $archive = date("Y-m-d H-i-s");                         //UNIQUE name of zip file to create and download
    $zipfile = "./".$holidex." - ".$archive.".zip";         //path to zip file download
    $temp = "./temp/";                                      //directory to temp folder

    // string replacements
    $find = "##PROPERTY##";                                 // find and replace property information
    $replace = $_POST['property'];

    $find2 = "##BRAND##";                                   // find and replace brand information
    $replace2 = $_POST['brand'];

    $find3 = "##DATE##";                                    // find and replace effective date
    $replace3 = $_POST['date_issued'];

    $find4 = "##APPROVED_BY##";                             // find and replace approved by
    $replace4 = $_POST['approved_by'];

    //read dir
    $files = scandir($dir, 1);

    //create new archive name
    $zip_download = new ZipArchive();
    $zip_download->open("$zipfile", ZipArchive::CREATE);

    foreach($files as $file) {

      //docx
      $ext1 = ".docx";
      $checkextension = explode($ext1, $file);
      if (count($checkextension) > 1) {
        $zip = new ZipArchive;
        $zip->open("$file");

        $word = $zip->getFromName('word/document.xml');
        $word2 = str_replace($find, $replace, $word);
        $word2 = str_replace($find2, $replace2, $word);
        $word2 = str_replace($find3, $replace3, $word);
        $word2 = str_replace($find4, $replace4, $word);

        $zip->addFromString("word/document.xml", $word2);
        $zip->close();
      } else {
            die("Error - There are no files the directory..");
            }

      //folders level 1
      if (is_dir($file)) {
        $sub = $file . '/';
        $subfiles = scandir($sub, 1);
        if ($subfiles > 1) {
          if ($sub == "../" || $sub == "./") {
          }
          else {
            foreach($subfiles as $subfile) {

              //docx
              $ext1 = ".docx";
              $checkextensionsub = explode($ext1, $subfile);
              $subsubfile = $sub . $subfile;
              if (count($checkextensionsub) > 1) {
                $zipsub = new ZipArchive;
                $zipsub->open("$subsubfile");

                $wordsub = $zipsub->getFromName('word/document.xml');
                $word2sub = str_replace($find, $replace, $wordsub);
                $word2sub = str_replace($find2, $replace2, $wordsub);
                $word2sub = str_replace($find3, $replace3, $wordsub);
                $word2sub = str_replace($find4, $replace4, $wordsub);

                $zipsub->addFromString("word/document.xml", $word2sub);
                $zipsub->close();
              }

              //folders level 2
              $sub2 = $sub . $subfile;
              if (is_dir($sub2)) {
                $subfiles2 = scandir($sub2, 1);
                if ($subfiles2 > 1) {
                  if ($sub2 == $sub.".." || $sub2 == $sub.".") {
                  }
                  else {
                    foreach($subfiles2 as $subfile2) {
                      //docx
                      $ext1 = ".docx";
                      $checkextensionsub2 = explode($ext1, $subfile2);
                      $subsubfile2 = $sub2 . '/' . $subfile2;
                      if (count($checkextensionsub2) > 1) {
                        $zipsub2 = new ZipArchive;
                        $zipsub2->open("$subsubfile2");

                        $wordsub2 = $zipsub2->getFromName('word/document.xml');
                        $word2sub2 = str_replace($find, $replace, $wordsub2);
                        $word2sub2 = str_replace($find2, $replace2, $wordsub2);
                        $word2sub2 = str_replace($find3, $replace3, $wordsub2);
                        $word2sub2 = str_replace($find4, $replace4, $wordsub2);

                        $zipsub2->addFromString("word/document.xml", $word2sub2);
                        $zipsub2->close();
                      }

                      //more directories when needed
                      //****replicate code here****

                      //add files to archive
                      $zip_download->addFile($subsubfile2, $subsubfile2);
                    }
                  }
                }
              }

              //add files to archive
              $zip_download->addFile($subsubfile, $subsubfile);
            }
          }
        }
      } else    {
                die ("Error - No files in the directory");
                }
      }

      //add files to archive
      $zip_download->addFile($file, $file);

    }

    $zip_download->close();

    //download zip
    if (file_exists($zipfile) && is_readable($zipfile)) {
      header('Content-Type: application/octet-stream');
      header('Content-Length: '.filesize($zipfile));
      header('Content-Disposition: attachment; filename="'.basename($zipfile).'";');
      header('Content-Transfer-Encoding: binary');
      $file_download = @ fopen($zipfile, 'rb');
      if ($file_download) {
        fpassthru($file_download);
        exit;
      }

        echo ("ZIP generated successfully, download is starting...");

    } else  { 
            echo ("Error creating the ZIP archive!"); 
            }
}
?>

I think it's because Scandir() will produce something like

`Array
   (
      ...
      [9] => .
      [10] => ..`

at the end of the arrayand when you check those if they are folders maybe an error occurs and dies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM