ZipHelper.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace common\helpers;
  3. use ZipArchive;
  4. use yii\web\UnprocessableEntityHttpException;
  5. /**
  6. * Class ZipHelper
  7. * @package common\helpers
  8. * @author jianyan74 <751393839@qq.com>
  9. */
  10. class ZipHelper
  11. {
  12. /**
  13. * 将指定文件添加到 zip 中
  14. *
  15. * @param string $zipPath zip 文件
  16. * @param string $filePath 文件路径
  17. * @param string $fileName 重命名文件名
  18. * @return void
  19. */
  20. public static function addFile($zipPath, $filePath, $fileName = '')
  21. {
  22. $zip = new ZipArchive;
  23. if ($zip->open($zipPath, ZipArchive::CREATE) !== true) {
  24. throw new UnprocessableEntityHttpException('打不开指定文件');
  25. }
  26. $zip->addFile($filePath, $fileName);
  27. $zip->close();
  28. }
  29. /**
  30. * 批量添加文件目录到 zip
  31. *
  32. * @param string $zipPath
  33. * @param string $fileDirectory 文件目录
  34. * @param string $replacePrefix 替换前缀
  35. * @return void
  36. * @throws UnprocessableEntityHttpException
  37. */
  38. public static function addFileByPath($zipPath, $fileDirectory, $replacePrefix = '')
  39. {
  40. $zip = new ZipArchive;
  41. if ($zip->open($zipPath, ZipArchive::CREATE) !== true) {
  42. throw new UnprocessableEntityHttpException('打不开指定文件');
  43. }
  44. // 将目录下所有文件添加到 zip 中
  45. if ($handle = opendir($fileDirectory)) {
  46. // 添加目录中的所有文件
  47. while (false !== ($entry = readdir($handle))) {
  48. if ($entry != "." && $entry != ".." && !is_dir($fileDirectory.'/'.$entry)) {
  49. if ($replacePrefix) {
  50. $zip->addFile($fileDirectory.'/'.$entry, StringHelper::replace($replacePrefix, '', $fileDirectory).'/'.$entry);
  51. } else {
  52. $zip->addFile($fileDirectory.'/'.$entry);
  53. }
  54. }
  55. }
  56. closedir($handle);
  57. }
  58. $zip->close();
  59. }
  60. /**
  61. * 解压到指定目录
  62. *
  63. * @param $zipPath
  64. * @param $fileDirectory
  65. * @return void
  66. */
  67. public static function unZip($zipPath, $fileDirectory, $deleteOriginalFile = false)
  68. {
  69. $zip = new ZipArchive;
  70. if ($zip->open($zipPath) !== true) {
  71. throw new UnprocessableEntityHttpException('打不开指定文件');
  72. }
  73. // 解压
  74. $zip->extractTo($fileDirectory);
  75. $zip->close();
  76. // 删除源文件
  77. if ($deleteOriginalFile) {
  78. unlink($zipPath);
  79. }
  80. }
  81. }
粤ICP备19079148号