File.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // +----------------------------------------------------------------------
  12. // | 文件及文件夹处理类
  13. // +----------------------------------------------------------------------
  14. namespace util;
  15. use FilesystemIterator;
  16. use RecursiveDirectoryIterator;
  17. use RecursiveIteratorIterator;
  18. class File
  19. {
  20. /**
  21. * 创建目录
  22. * @param string $dir 目录名
  23. * @return bool true 成功, false 失败
  24. */
  25. public static function mk_dir(string $dir): bool
  26. {
  27. if (is_dir($dir)) {
  28. return true;
  29. }
  30. return mkdir($dir, 0755, true);
  31. }
  32. /**
  33. * 读取文件内容
  34. * @param string $filename 文件名
  35. * @return false|string
  36. */
  37. public static function read_file(string $filename): false | string
  38. {
  39. $content = '';
  40. if (function_exists('file_get_contents')) {
  41. @$content = file_get_contents($filename);
  42. } else {
  43. if (@$fp = fopen($filename, 'r')) {
  44. @$content = fread($fp, filesize($filename));
  45. @fclose($fp);
  46. }
  47. }
  48. return $content;
  49. }
  50. /**
  51. * 写文件
  52. * @param string $filename 文件名
  53. * @param string $writetext 要写入的字符串
  54. * @param string $openmod 打开方式
  55. * @return bool
  56. */
  57. public static function write_file(string $filename, string $writetext, string $openmod = 'w'): bool
  58. {
  59. if (@$fp = fopen($filename, $openmod)) {
  60. flock($fp, 2);
  61. fwrite($fp, $writetext);
  62. fclose($fp);
  63. return true;
  64. } else {
  65. return false;
  66. }
  67. }
  68. /**
  69. * 删除文件夹
  70. * @param string $dirname 目录
  71. * @param bool $withself 是否删除自身
  72. * @return boolean
  73. */
  74. public static function del_dir(string $dirname, bool $withself = true): bool
  75. {
  76. if (!is_dir($dirname)) {
  77. return false;
  78. }
  79. $files = new RecursiveIteratorIterator(
  80. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  81. RecursiveIteratorIterator::CHILD_FIRST
  82. );
  83. foreach ($files as $fileinfo) {
  84. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  85. $todo($fileinfo->getRealPath());
  86. }
  87. if ($withself) {
  88. @rmdir($dirname);
  89. }
  90. return true;
  91. }
  92. /**
  93. * 复制文件夹
  94. * @param string $source 源文件夹
  95. * @param string $dest 目标文件夹
  96. */
  97. public static function copy_dir(string $source, string $dest)
  98. {
  99. if (!is_dir($dest)) {
  100. self::mk_dir($dest);
  101. }
  102. foreach (
  103. $iterator = new RecursiveIteratorIterator(
  104. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  105. RecursiveIteratorIterator::SELF_FIRST
  106. ) as $item
  107. ) {
  108. if ($item->isDir()) {
  109. $sontDir = $dest . DS . $iterator->getSubPathName();
  110. if (!is_dir($sontDir)) {
  111. self::mk_dir($sontDir);
  112. }
  113. } else {
  114. copy($item, $dest . DS . $iterator->getSubPathName());
  115. }
  116. }
  117. }
  118. /**
  119. * 列出目录
  120. * @param string $dir 目录名
  121. * @return array 目录数组。列出文件夹下内容,返回数组 $result['dir']:存文件夹;$result['file']:存文件
  122. */
  123. public static function get_dirs(string $dir): array
  124. {
  125. $result = [
  126. 'dir' => [],
  127. 'file' => [],
  128. ];
  129. if (!is_dir($dir)) {
  130. return $result;
  131. }
  132. $iterator = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
  133. foreach ($iterator as $fileinfo) {
  134. $type = $fileinfo->isDir() ? 'dir' : 'file';
  135. $result[$type][] = $fileinfo->getFilename();
  136. }
  137. return $result;
  138. }
  139. /**
  140. * 取得目录下面的文件信息
  141. * @param string $pathname 路径
  142. * @param string $pattern
  143. * @return array
  144. */
  145. public static function listFile(string $pathname, string $pattern = '*'): array
  146. {
  147. if (str_contains($pattern, '|')) {
  148. $patterns = explode('|', $pattern);
  149. } else {
  150. $patterns[0] = $pattern;
  151. }
  152. $i = 0;
  153. $dir = [];
  154. foreach ($patterns as $pattern) {
  155. $list = glob($pathname . $pattern);
  156. if ($list !== false) {
  157. foreach ($list as $file) {
  158. //$dir[$i]['filename'] = basename($file);
  159. //basename取中文名出问题.改用此方法
  160. //编码转换.把中文的调整一下.
  161. $dir[$i]['filename'] = preg_replace('/^.+[\\\\\\/]/', '', $file);
  162. $dir[$i]['pathname'] = realpath($file);
  163. $dir[$i]['owner'] = fileowner($file);
  164. $dir[$i]['perms'] = fileperms($file);
  165. $dir[$i]['inode'] = fileinode($file);
  166. $dir[$i]['group'] = filegroup($file);
  167. $dir[$i]['path'] = dirname($file);
  168. $dir[$i]['atime'] = fileatime($file);
  169. $dir[$i]['ctime'] = filectime($file);
  170. $dir[$i]['size'] = filesize($file);
  171. $dir[$i]['type'] = filetype($file);
  172. $dir[$i]['ext'] = is_file($file) ? strtolower(substr(strrchr(basename($file), '.'), 1)) : '';
  173. $dir[$i]['mtime'] = filemtime($file);
  174. $dir[$i]['isDir'] = is_dir($file);
  175. $dir[$i]['isFile'] = is_file($file);
  176. $dir[$i]['isLink'] = is_link($file);
  177. //$dir[$i]['isExecutable']= function_exists('is_executable')?is_executable($file):'';
  178. $dir[$i]['isReadable'] = is_readable($file);
  179. $dir[$i]['isWritable'] = is_writable($file);
  180. $i++;
  181. }
  182. }
  183. }
  184. // 对结果排序 保证目录在前面
  185. usort($dir, function ($a, $b) {
  186. if (($a["isDir"] && $b["isDir"]) || (!$a["isDir"] && !$b["isDir"])) {
  187. return $a["filename"] > $b["filename"] ? 1 : -1;
  188. } else {
  189. if ($a["isDir"]) {
  190. return -1;
  191. } elseif ($b["isDir"]) {
  192. return 1;
  193. }
  194. if ($a["filename"] == $b["filename"]) {
  195. return 0;
  196. }
  197. return $a["filename"] > $b["filename"] ? -1 : 1;
  198. }
  199. });
  200. return $dir;
  201. }
  202. /**
  203. * 统计文件夹大小
  204. * @param string $dir 目录名
  205. * @return int 文件夹大小(单位 B)
  206. */
  207. public static function get_size(string $dir): int
  208. {
  209. $dirlist = opendir($dir);
  210. $dirsize = 0;
  211. while (false !== ($folderorfile = readdir($dirlist))) {
  212. if ($folderorfile != "." && $folderorfile != "..") {
  213. if (is_dir("$dir/$folderorfile")) {
  214. $dirsize += self::get_size("$dir/$folderorfile");
  215. } else {
  216. $dirsize += filesize("$dir/$folderorfile");
  217. }
  218. }
  219. }
  220. closedir($dirlist);
  221. return $dirsize;
  222. }
  223. /**
  224. * 检测是否为空文件夹
  225. * @param string $dir 目录名
  226. * @return bool true 空, fasle 不为空
  227. */
  228. public static function empty_dir(string $dir): bool
  229. {
  230. return (($files = @scandir($dir)) && count($files) <= 2);
  231. }
  232. /**
  233. * 移除空目录
  234. * @param string $dir 目录
  235. * @return void
  236. */
  237. public static function remove_empty_folder(string $dir): void
  238. {
  239. try {
  240. $isDirEmpty = !(new \FilesystemIterator($dir))->valid();
  241. if ($isDirEmpty) {
  242. @rmdir($dir);
  243. self::remove_empty_folder(dirname($dir));
  244. }
  245. } catch (\UnexpectedValueException $e) {
  246. } catch (\Exception $e) {
  247. }
  248. }
  249. /**
  250. * 判断文件或文件夹是否可写.
  251. * @param string $file 文件或目录
  252. * @return bool
  253. */
  254. public static function is_really_writable(string $file): bool
  255. {
  256. if (DIRECTORY_SEPARATOR === '/') {
  257. return is_writable($file);
  258. }
  259. if (is_dir($file)) {
  260. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  261. if (($fp = @fopen($file, 'ab')) === false) {
  262. return false;
  263. }
  264. fclose($fp);
  265. @chmod($file, 0777);
  266. @unlink($file);
  267. return true;
  268. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  269. return false;
  270. }
  271. fclose($fp);
  272. return true;
  273. }
  274. }