DirHelper.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2022/8/10
  6. * Time: 18:39
  7. */
  8. namespace file;
  9. class DirHelper
  10. {
  11. /**
  12. * 创建多级目录
  13. * @param $path [目录路径]
  14. * @return bool
  15. */
  16. public static function makeDir($path)
  17. {
  18. if (!file_exists($path)) {//不存在则建立
  19. $mk = @mkdir($path, 0777, true); //权限
  20. @chmod($path, 0777);
  21. }
  22. return true;
  23. }
  24. /**
  25. * 不经过回收站,递归删除文件夹(本机测试时请慎用)
  26. * @param $dir [目录路径]
  27. */
  28. public static function delDir($dir)
  29. {
  30. if (file_exists($dir)) {
  31. $mydir = dir($dir);
  32. while (false !== ($file = $mydir->read())) {
  33. if ($file != "." && $file != "..") {
  34. $path = $dir . DS . $file;
  35. is_dir($path) ? self::delDir($path) : @unlink($path);
  36. }
  37. }
  38. $mydir->close();
  39. @rmdir($dir);
  40. }
  41. }
  42. /**
  43. * 复制目录
  44. * @param $source [源目录路径]
  45. * @param $dest [目标目录路径]
  46. * @param $cover [拷贝并覆盖同名文件]
  47. */
  48. public static function copyDir($source, $dest, $cover = true)
  49. {
  50. if (!file_exists($dest)) self::makeDir($dest);
  51. $handle = opendir($source);
  52. while (($item = readdir($handle)) !== false) {
  53. if ($item == '.' || $item == '..') continue;
  54. $_source = $source . DS . $item;
  55. $_dest = $dest . DS . $item;
  56. if (is_dir($_source)) {
  57. self::copyDir($_source, $_dest, $cover);
  58. } else if (is_file($_source)) {
  59. if ($cover || (!$cover && !file_exists($_dest))) {
  60. copy($_source, $_dest);
  61. }
  62. }
  63. }
  64. closedir($handle);
  65. }
  66. /**
  67. * 读取出一个文件夹及其子文件夹下所有文件
  68. * @param $path
  69. * @return array|mixed|string
  70. */
  71. public static function scanDirs($path)
  72. {
  73. global $result;
  74. $files = scandir($path);
  75. foreach ($files as $file) {
  76. if ($file != '.' && $file != '..') {
  77. if (is_dir($path . '/' . $file)) {
  78. $result[] = $path . '/' . $file;
  79. self::scanDirs($path . '/' . $file);
  80. } else {
  81. $result[] = $path . '/' . $file;
  82. }
  83. }
  84. }
  85. return $result;
  86. }
  87. }