PHPでサブディレクトリ内のファイルも含めてZipファイルを作成する方法

このQ&Aのポイント
  • PHPでサブディレクトリ内のファイルも含めてZipファイルを作成する方法について説明します。
  • 指定したディレクトリ内のファイルを再帰的に取得し、Zipファイルに追加する処理を行います。
  • 生成したZipファイルをダウンロードする際には、ヘッダー情報を設定してファイルをストリームに出力します。
回答を見る
  • ベストアンサー

PHP 再帰的 ZipArchive

現在サブディレクトリの中のファイルも含めZipファイルを作成していのですがうまくいきません 説明がうまくできませんが下記のサブディレクトリのtestだけが表示されファイルが取得できません。できればpath_uploadの中を階層を変えずzipで圧縮して取得したいです。 なにとぞよろしくお願いします。 path_upload----test-----test.txt |--test2.txt |--test3.txt コード define("file_zone","C:/MAMP/htdocs/upload/path_upload"); if(isset($_POST["download"])){ $path = file_zone; $files = scandir($path); $zip = new ZipArchive($files); // Zipファイル名 $zipFileName = date("Ymd") .'.zip'; // Zipファイル一時保存ディレクトリ $zipTmpDir = file_zone; // Zipファイルオープン $result = $zip->open($zipTmpDir.$zipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE); if ($result !== true) { // 失敗した時の処理 } // 処理制限時間を外す set_time_limit(0); foreach ($files as $filepath) { $filename = basename($filepath); // 取得ファイルをZipに追加していく $zip->addFromString($filename,file_get_contents($filepath)); } $zip->close(); // ストリームに出力 if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); header('Content-Type: application/zip; name="' . $zipFileName . '"'); header('Content-Disposition: attachment; filename="' . $zipFileName . '"'); header('Content-Length: '.filesize($zipTmpDir.$zipFileName)); echo file_get_contents($zipTmpDir.$zipFileName); // 一時ファイルを削除しておく // unlink($zipTmpDir.$zipFileName); }

  • PHP
  • 回答数1
  • ありがとう数1

質問者が選んだベストアンサー

  • ベストアンサー
回答No.1

scandir()は、ディレクトリ内にサブディレクトリがあっても、その下までは潜ってくれません。 よって階層下を全て取り出したいなら、 scandirで取り出したファイルリスト中に ディレクトリタイプがあれば、さらにそれをscandir()する必要があります。 このとき階層数がいくつあってもよいように、アーカイブに追加する部分のみを関数化して その関数内で、ファイルならアーカイブし、ディレクトリならば自分自身の関数を呼び出すようにしておくのが再帰的処理ですが 添付されたのコードには、そのような再帰的な処理はありませんよ。

関連するQ&A

  • PHP ZIP 展開できない

    PHPで作成したZipファイルが展開できません ダブルクリックで展開すると無効ですと表示されます。 よろしくお願いします。 define("file_zone","C:/MAMP/htdocs/upload/test/"); if(isset($_POST["download"])){ $path = file_zone; $files = scandir($path); $zip = new ZipArchive($files); // Zipファイル名 $zipFileName = "file_" . date("Ymds") .'.zip'; // Zipファイル一時保存ディレクトリ $zipTmpDir = file_zone; // Zipファイルオープン $result = $zip->open($zipTmpDir.$zipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE); if ($result !== true) { // 失敗した時の処理 } // 処理制限時間を外す set_time_limit(0); foreach ($files as $filepath) { $filename = basename($filepath); // 取得ファイルをZipに追加していく $zip->addFromString($filename,file_get_contents($filepath)); } $zip->close(); // ストリームに出力 header('Content-Type: application/zip; name="' . $zipFileName . '"'); header('Content-Disposition: attachment; filename="' . $zipFileName . '"'); header('Content-Length: '.filesize($zipTmpDir.$zipFileName)); echo file_get_contents($zipTmpDir.$zipFileName); // 一時ファイルを削除しておく // unlink($zipTmpDir.$zipFileName); }

    • ベストアンサー
    • PHP
  • PHP zipファイルのダウンロード

    下記のようなPHPスクリプトにおいて、zip フォルダに画像ファイルの圧縮ファイルを 保存し、ダウンロードしたいんです。ダウンロードの動作はChrome上で確認できてますが、圧縮した、ダウンロードファイルのサイズが0KB で、空なのです。 どこが間違っているか教えていただけますか? [file_zip.php] <?php mb_internal_encoding("UTF-8"); $ftp = ftp_connect("~"); ftp_login($ftp, "~", "~"); $dir = '/storage2/zip'; ftp_chdir($ftp, $dir); // ディレクトリ移動 // Zipクラスロード $zip = new ZipArchive(); // Zipファイル名 $zipFileName = $_POST['zip_filename']; var_dump($zipFileName); // Zipファイル一時保存ディレクトリ $zipTmpDir = '/storage2/zip'; // Zipファイルオープン $result = $zip->open($zipTmpDir.$zipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE); if ($result !== true) { // 失敗した時の処理 echo '圧縮ファイルをオープンできませんでした'; exit(); } // ここでDB等から画像イメージ配列を取ってくる $image_data_array = array(); array_unshift($image_data_array, $zipTmpDir.$zipFileName); // 処理制限時間を外す set_time_limit(0); foreach ($image_data_array as $filepath) { $filename = basename($filepath); // 取得ファイルをZipに追加していく $zip->addFromString($filename,file_get_contents($filepath)); } $zip->close(); // ストリームに出力 header('Content-Type: application/zip; name="' . $zipFileName . '"'); header('Content-Disposition: attachment; filename="' . $zipFileName . '"'); header('Content-Length: '.filesize($zipTmpDir.$zipFileName)); echo file_get_contents($zipTmpDir.$zipFileName); // 一時ファイルを削除しておく unlink($zipTmpDir.$zipFileName); // header("Location: storage.php"); ?>

    • 締切済み
    • PHP
  • PHPで複数ファイルのダウンロード

    はじめまして、PHPについて質問させていただきます。 PHPでファイルを複数ダウンロードできるようしたいと思っています。 色々調べ、header関数を使用し、以下のように記述すると ファイルのダウンロードは成功しました。 /*****************************************/ // ダウンロードさせる元ファイル(絶対パス) $filepath = 'test_01.pdf'; // 保存時のファイル名(デフォルト) $filename = 'download001.pdf'; // HTTPヘッダ送信 header("Content-length: " . filesize($filepath)); header("Content-type: application/pdf"); header("Content-Disposition: attachment; filename=\"{$filename}\""); // ファイルを読み込んで出力 readfile($filepath); /*****************************************/ 一つのファイルのダウンロードに成功したので、 次に複数のファイルを順番にダウンロードをさせる為にループ処理をしました。 /*****************************************/ //配列 複数ファイル $downfile = array("test_01","test_02","test_03"); //データ数 $max = count($downfile); // ダウンロードさせるディレクトリ(絶対パス) $filepath = "/home/sites/www.eshop-himawari.com/web/test_nihon/form_down/file/"; // 保存時のファイル名(デフォルト) $filename = "download"; $filetype = ".pdf"; $kazu = 1; //ループ処理 for( $i = 0; $i < count( $max ); $i++ ){ $downpath = $filepath.$downfile[$i].$filetype; $filename = $filename.$kazu.$filetype; $kazu = $kazu++; // HTTPヘッダ送信 header("Content-length: " . filesize($downpath)); header("Content-type: application/pdf"); header("Content-Disposition: attachment; filename=\"{$filename}\""); // ファイルを読み込んで出力 readfile($downpath); // $fp = fopen( "$downpath", "rb" ); // @fpassthru( $fp ); } /*****************************************/ しかし実行すると最初のファイルはダウンロードしますが 2つ目からのファイルはダウンロードされませんでした。 きちんとループ処理をされて、2つ目以降のファイルをダウンロード するには、どうすればいいのでしょうか?

    • 締切済み
    • PHP
  • PHP CSV 出力

    失礼します。 現在PHPで指定したパスに置いてあるCSVを出力したいのですが、 CSVは出力できているのですが、HTMLが先頭に入ってしまいます。 htmlファイルに設置したボタンに対して phpファイルで処理をしています。 どこかおかしい部分があればご教授頂きたいです。 HTMLファイル <?php $self = $_SERVER["SCRIPT_NAME"]; ?> <form method='POST' action='<?php $self ?>'> <input type='submit' value='CSV出力' name='get_csv'> </form> PHPファイル function This_Month(){ $filepath = 'hoge.csv'; //ダウンロードしたいファイルパス $filename = 'test.csv'; //ダウンロードした際のファイル名 if(!file_exists($filepath)){ die("Error:File(".$filepath.") does not exist"); } //オープンできるか確認 if(!($fp = fopen($filepath,"r"))) { die("Error:Cannot open the file(".$filepath.")"); } fclose($fp); //ファイルサイズの確認 if(($content_length = filesize($filepath)) == 0){ die("Error:File size is 0.(".$filepath.")"); } //ファイルの処理方法 header('Content-Disposition: attachement; filename="'.$filename.'"'); //ファイルタイプ指定 header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding:binary'); //ファイルサイズ header('Content-Length: '.filesize($filepath)); mb_convert_encoding($filepath,'utf-8','shift-jis'); readfile($filepath); exit(); } //ボタンに合わせて条件を変えていく if(isset($_POST["get_csv"])){ //ユーザーから来たデータをエスケープする $csv_output = htmlspecialchars($_POST["get_csv"], ENT_QUOTES, "UTF-8"); switch ($csv_output) { case "CSV出力": ”This_Month();  break; default: echo "エラー"; exit; } }

    • ベストアンサー
    • PHP
  • PHP Zip 開かない

    よろしくお願いします。現在ZIPにしたものをheaderで出力したいのですが、 その場で解凍した際にフォルダを開くことができません無効ですと表示されます。 原因がわからず困っています。ヒントでも頂ければ助かります。 if(isset($_POST["upload"])){ $dir = file_zone; // Zipファイルの保存先 $file = "./Zipfile/" . date("his") .'.zip'; $root = ""; zipDirectory($dir, $file,$root); } function zipDirectory($dir, $file, $root){ $zip = new ZipArchive(); $res = $zip->open($file, ZipArchive::CREATE); if($res){ // $rootが指定されていればその名前のフォルダにファイルをまとめる if($root != "") { $zip->addEmptyDir($root); $root .= DIRECTORY_SEPARATOR; } $baseLen = mb_strlen($dir); $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir, FilesystemIterator::SKIP_DOTS |FilesystemIterator::KEY_AS_PATHNAME |FilesystemIterator::CURRENT_AS_FILEINFO ), RecursiveIteratorIterator::SELF_FIRST ); $list = array(); foreach($iterator as $pathname => $info){ $localpath = $root . mb_substr($pathname, $baseLen); if( $info->isFile() ){ $zip->addFile($pathname, $localpath); } else { $res = $zip->addEmptyDir($localpath); } } $zip->close(); } else { return false; } header('Content-Type: application/octet-stream'); header(sprintf('Content-Disposition: attachment; filename="%s"',basename($file))); header(sprintf('Content-Length: %d', filesize($file)) ); readfile($file); }

    • ベストアンサー
    • PHP
  • Zip名 日付

    失礼します、現在指定したディレクトリにzipファイルを作成しているのですが、Zip名の頭に日付を付けたいです。 dateを使用しているのですが上手くいきませんストリームに出力する際のファイル名にdateはうまくいきましたが指定したディレクトリに保存した際のファイル名がうまくいきません。 自身でZipファイルの保存先にdateを使用してみましたがエラーが出てしまいます。 よろしくお願いします。 if(isset($_POST["upload"])){ $dir = file_zone; // Zipファイルの保存先 $file = './Zipfile/test.zip'; $root = ""; zipDirectory($dir, $file,$root); } function zipDirectory($dir, $file, $root){ $zip = new ZipArchive(); $res = $zip->open($file, ZipArchive::CREATE); if($res){ // $rootが指定されていればその名前のフォルダにファイルをまとめる if($root != "") { $zip->addEmptyDir($root); $root .= DIRECTORY_SEPARATOR; } $baseLen = mb_strlen($dir); $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir, FilesystemIterator::SKIP_DOTS |FilesystemIterator::KEY_AS_PATHNAME |FilesystemIterator::CURRENT_AS_FILEINFO ), RecursiveIteratorIterator::SELF_FIRST ); $list = array(); foreach($iterator as $pathname => $info){ $localpath = $root . mb_substr($pathname, $baseLen); if( $info->isFile() ){ $zip->addFile($pathname, $localpath); } else { $res = $zip->addEmptyDir($localpath); } } $zip->close(); } else { return false; } header('Content-Type: application/octet-stream'); header(sprintf('Content-Disposition: attachment; filename="%s"', date(ymdhis).basename($file))); header(sprintf('Content-Length: %d', filesize($file)) ); readfile($file); }

    • ベストアンサー
    • PHP
  • IEだと・・・だめなんです

    Zipファイルに固めてダウンロードさせようとしているのですが、Firefoxだとダウンロードできて、IEだとエラーが出てこけてしまいます。 まず、Header部分が原因だと思うのですが、原因分かる方いらっしゃいますか?教えてください。 header("Content-type: application/octet-stream"); header('Content-Disposition: attachment; filename="' . zip_file_name . '"'); header("Content-length: " . filesize($zip_file_name)); readfile($zip_file_name);

    • ベストアンサー
    • PHP
  • phpプログラミングについて

    php初心者です。 ファイルをダウンロードして保存するプログラムを作成しています。 ダイアログを表示させる形式をとっているのですが、保存されたファイルが正しく開けないんです。 ワードの場合だとファイルが壊れ、テキストファイルの場合、htmlのコードが一緒に入ってしまいます。 以下にソースコードと、ファイルの表示結果も載せるので、アドバイスお願いします。 [download.php] <html> <head> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"> <title>testdownload</title> </head> <body> テキストリンクの場合<br> <a href = "sample.php">sampleファイルをダウンロードする</a> <br><br> フォームボタンの場合<br> <form method = "post" action = "sample.php"><input type = "submit" value = "download"></form> </body> </html> [sample.php] <html> <head> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"> <title>downloadphp</title> </head> <body> <?php $path_file = "./test2.txt"; $path_file = mb_convert_encoding($path_file,"Shift_JIS","AUTO"); /* ファイルの存在確認 */ if (!file_exists($path_file)) { die("Error: File(".$path_file.") does not exist"); } /* オープンできるか確認 */ if (!($fp = fopen($path_file, "r"))) { die("Error: Cannot open the file(".$path_file.")"); } fclose($fp); /* ファイルサイズの確認 */ if (($content_length = filesize($path_file)) == 0) { die("Error: File size is 0.(".$path_file.")"); } /* ダウンロード用のHTTPヘッダ送信 */ header("Content-Disposition: attachment; filename=\"".basename($path_file)."\""); header("Content-Length: ".$content_length); header("Content-Type: application/octet-stream"); /* ファイルを読んで出力 */ if (!readfile($path_file)) { die("Cannot read the file(".$path_file.")"); } ?> </body> </html> [test2.txt] これはテストです。 [ダウンロード後のtest2.txt] <html> <head> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"> <title>downloadphp</title> </head> <body> これはテストです。 </body> </html> 以上、よろしくお願いします。

    • 締切済み
    • PHP
  • PHP 画像の表示

    プログラミング初心者です。 PHPでブラウザに画像を表示したいのですが映らなくて 以下のソースコードは間違っているでしょうか? <?php $fileName = "img/test.jpg"; //ファイル名 if (file_exists($fileName)) { header('Content-type: image/jpeg'); header('Content-Length: '.filesize("http://localhost:8080/test.jpg")); //あった方が良い readfile("http://localhost:8080/test.jpg"); //ファイルを読み込んで標準出力に書き出し exit; } ?>

    • ベストアンサー
    • PHP
  • PHPからファイルアップロードの実現

    ブラウザからファイルをアップロードするように、PHP内で同じことを実現させたいと考えています。 fsockopenを使用してGETやPOSTをすることは実現できていますが、ファイルのアップロードとなると少々勝手が違い、うまいことできません。 現状では下記のようなものを送信させているのですが、受け取り側のPHPで認識できません。 POST /upload.php HTTP/1.0 host: 127.0.0.1 Content-Type: multipart/form-data; boundary=---test Connection: close Content-Length: 120 ---test Content-Disposition: form-data; name="test"; filename="test.txt" Content-Type: text/plain testtest ---test 現状、テスト用に upload.php というので受け取っているのですが、$_FILES 変数は空の状態です。 基本的なところを理解していないので、根本的に間違っていたり、足りないところがあるような気がするのですが…。 よろしくお願いします。

    • ベストアンサー
    • PHP

専門家に質問してみよう