search
HomeBackend DevelopmentPHP TutorialFile directory operation class implemented by php

  1. /**
  2. * File directory operation class
  3. * Editor: bbs.it-home.org
  4. * Example:
  5. * $fileutil = new fileDirUtil();
  6. * $fileutil->createDir('a/1/2/3') ; To test the creation folder, create a/1/2/3 folder
  7. * $fileutil->createFile('b/1/2/3'); To test the creation file, create it under the b/1/2/ folder A 3-file
  8. * $fileutil->createFile('b/1/2/3.txt'); To test the creation file, create a 3.exe file under the b/1/2/ folder
  9. * $fileutil-> ;writeFile('b/1/2/3.txt','this is something i write!'); Write content in the file
  10. * $arr = $fileutil->readFile2array('example/mysql.txt') ;
  11. * $arr = $fileutil->readsFile('example/mysql.txt');
  12. * $size=$fileutil->bitSize($fileutil->getDirSize("example")); Get the file or The size of the directory
  13. * $fileutil->copyDir('b','d/e'); Test the copy folder to create a d/e folder and copy the contents of the b folder into it
  14. * $fileutil-> ;copyFile('b/1/2/3.exe','b/b/3.exe'); Test copy the file to create a b/b folder, and put 3. in the b/1/2 folder. Copy the exe file into it
  15. * $fileutil->moveDir('a/','b/c'); Test the moving folder, create a b/c folder, move the contents of the a folder into it, and delete it a folder
  16. * $fileutil->moveFile('b/1/2/3.exe','b/d/3.exe'); Test moving files to create a b/d folder and put b/ Move the 3.exe in 1/2 in
  17. * $fileutil->unlinkFile('b/d/3.exe'); Test deletion of the file and delete the b/d/3.exe file
  18. * $fileutil->unlinkDir ('d'); Test deletion folder to delete d folder
  19. * $list = $fileutil->dirList("E:example"); Test list folder to list all files in the directory
  20. * $list = $fileutil ->dirTree("/"); Test list folder tree lists the direct tree relationship of all files in the directory
  21. */
  22. class fileDirUtil {
  23. /**
  24. * Create folder
  25. *
  26. * @param string $aimUrl
  27. * @return viod
  28. */
  29. function createDir($aimUrl, $mode = 0777) {
  30. $aimUrl = str_replace ( '', '/', $aimUrl );
  31. $aimDir = '';
  32. $arr = explode ( '/', $aimUrl );
  33. foreach ( $arr as $str ) {
  34. $aimDir .= $str . '/';
  35. if (! file_exists ( $aimDir )) {
  36. mkdir ( $aimDir, $mode );
  37. }
  38. }
  39. }
  40. /**
  41. * Create file
  42. *
  43. * @param string $aimUrl
  44. * @param boolean $overWrite This parameter controls whether to overwrite the original file
  45. * @return boolean
  46. */
  47. function createFile($aimUrl, $overWrite = false) {
  48. if (file_exists ( $aimUrl ) && $overWrite == false) {
  49. return false;
  50. } elseif (file_exists ( $aimUrl ) && $overWrite == true) {
  51. $this->unlinkFile ( $aimUrl );
  52. }
  53. $aimDir = dirname ( $aimUrl );
  54. $this->createDir ( $aimDir );
  55. touch ( $aimUrl );
  56. return true;
  57. }
  58. /**
  59. * Move folder
  60. *
  61. * @param string $oldDir
  62. * @param string $aimDir
  63. * @param boolean $overWrite This parameter controls whether to overwrite the original file
  64. * @return boolean
  65. */
  66. function moveDir($oldDir, $aimDir, $overWrite = false) {
  67. $aimDir = str_replace ( '', '/', $aimDir );
  68. $aimDir = substr ( $aimDir, - 1 ) == '/' ? $aimDir : $aimDir . '/';
  69. $oldDir = str_replace ( '', '/', $oldDir );
  70. $oldDir = substr ( $oldDir, - 1 ) == '/' ? $oldDir : $oldDir . '/';
  71. if (! is_dir ( $oldDir )) {
  72. return false;
  73. }
  74. if (! file_exists ( $aimDir )) {
  75. $this->createDir ( $aimDir );
  76. }
  77. @$dirHandle = opendir ( $oldDir );
  78. if (! $dirHandle) {
  79. return false;
  80. }
  81. while ( false !== ($file = readdir ( $dirHandle )) ) {
  82. if ($file == '.' || $file == '..') {
  83. continue;
  84. }
  85. if (! is_dir ( $oldDir . $file )) {
  86. $this->moveFile ( $oldDir . $file, $aimDir . $file, $overWrite );
  87. } else {
  88. $this->moveDir ( $oldDir . $file, $aimDir . $file, $overWrite );
  89. }
  90. }
  91. closedir ( $dirHandle );
  92. return rmdir ( $oldDir );
  93. }
  94. /**
  95. * Move file
  96. *
  97. * @param string $fileUrl
  98. * @param string $aimUrl
  99. * @param boolean $overWrite This parameter controls whether to overwrite the original file
  100. * @return boolean
  101. */
  102. function moveFile($fileUrl, $aimUrl, $overWrite = false) {
  103. if (! file_exists ( $fileUrl )) {
  104. return false;
  105. }
  106. if (file_exists ( $aimUrl ) && $overWrite = false) {
  107. return false;
  108. } elseif (file_exists ( $aimUrl ) && $overWrite = true) {
  109. $this->unlinkFile ( $aimUrl );
  110. }
  111. $aimDir = dirname ( $aimUrl );
  112. $this->createDir ( $aimDir );
  113. rename ( $fileUrl, $aimUrl );
  114. return true;
  115. }
  116. /**
  117. * Delete folder
  118. *
  119. * @param string $aimDir
  120. * @return boolean
  121. */
  122. function unlinkDir($aimDir) {
  123. $aimDir = str_replace ( '', '/', $aimDir );
  124. $aimDir = substr ( $aimDir, - 1 ) == '/' ? $aimDir : $aimDir . '/';
  125. if (! is_dir ( $aimDir )) {
  126. return false;
  127. }
  128. $dirHandle = opendir ( $aimDir );
  129. while ( false !== ($file = readdir ( $dirHandle )) ) {
  130. if ($file == '.' || $file == '..') {
  131. continue;
  132. }
  133. if (! is_dir ( $aimDir . $file )) {
  134. $this->unlinkFile ( $aimDir . $file );
  135. } else {
  136. $this->unlinkDir ( $aimDir . $file );
  137. }
  138. }
  139. closedir ( $dirHandle );
  140. return rmdir ( $aimDir );
  141. }
  142. /**
  143. * Delete file
  144. *
  145. * @param string $aimUrl
  146. * @return boolean
  147. */
  148. function unlinkFile($aimUrl) {
  149. if (file_exists ( $aimUrl )) {
  150. unlink ( $aimUrl );
  151. return true;
  152. } else {
  153. return false;
  154. }
  155. }
  156. /**
  157. * Copy folder
  158. *
  159. * @param string $oldDir
  160. * @param string $aimDir
  161. * @param boolean $overWrite This parameter controls whether to overwrite the original file
  162. * @return boolean
  163. */
  164. function copyDir($oldDir, $aimDir, $overWrite = false) {
  165. $aimDir = str_replace ( '', '/', $aimDir );
  166. $aimDir = substr ( $aimDir, - 1 ) == '/' ? $aimDir : $aimDir . '/';
  167. $oldDir = str_replace ( '', '/', $oldDir );
  168. $oldDir = substr ( $oldDir, - 1 ) == '/' ? $oldDir : $oldDir . '/';
  169. if (! is_dir ( $oldDir )) {
  170. return false;
  171. }
  172. if (! file_exists ( $aimDir )) {
  173. $this->createDir ( $aimDir );
  174. }
  175. $dirHandle = opendir ( $oldDir );
  176. while ( false !== ($file = readdir ( $dirHandle )) ) {
  177. if ($file == '.' || $file == '..') {
  178. continue;
  179. }
  180. if (! is_dir ( $oldDir . $file )) {
  181. $this->copyFile ( $oldDir . $file, $aimDir . $file, $overWrite );
  182. } else {
  183. $this->copyDir ( $oldDir . $file, $aimDir . $file, $overWrite );
  184. }
  185. }
  186. return closedir ( $dirHandle );
  187. }
  188. /**
  189. * Copy file
  190. *
  191. * @param string $fileUrl
  192. * @param string $aimUrl
  193. * @param boolean $overWrite This parameter controls whether to overwrite the original file
  194. * @return boolean
  195. */
  196. function copyFile($fileUrl, $aimUrl, $overWrite = false) {
  197. if (! file_exists ( $fileUrl )) {
  198. return false;
  199. }
  200. if (file_exists ( $aimUrl ) && $overWrite == false) {
  201. return false;
  202. } elseif (file_exists ( $aimUrl ) && $overWrite == true) {
  203. $this->unlinkFile ( $aimUrl );
  204. }
  205. $aimDir = dirname ( $aimUrl );
  206. $this->createDir ( $aimDir );
  207. copy ( $fileUrl, $aimUrl );
  208. return true;
  209. }
  210. /**
  211. * Write string to file
  212. *
  213. * @param string $filename file name
  214. * @param boolean $str character data to be written
  215. */
  216. function writeFile($filename, $str) {
  217. if (function_exists ( file_put_contents )) {
  218. file_put_contents ( $filename, $str );
  219. } else {
  220. $fp = fopen ( $filename, "wb" );
  221. fwrite ( $fp, $str );
  222. fclose ( $fp );
  223. }
  224. }
  225. /**
  226. * Read the entire file content into a string
  227. *
  228. * @param string $filename file name
  229. * @return array
  230. */
  231. function readsFile($filename) {
  232. if (function_exists ( file_get_contents )) {
  233. return file_get_contents ( $filename );
  234. } else {
  235. $fp = fopen ( $filename, "rb" );
  236. $str = fread ( $fp, filesize ( $filename ) );
  237. fclose ( $fp );
  238. return $str;
  239. }
  240. }
  241. /**
  242. * Read the file content into an array
  243. *
  244. * @param string $filename file name
  245. * @return array
  246. */
  247. function readFile2array($filename) {
  248. $file = file ( $filename );
  249. $arr = array ();
  250. foreach ( $file as $value ) {
  251. $arr [] = trim ( $value );
  252. }
  253. return $arr;
  254. }
  255. /**
  256. * Convert to /
  257. *
  258. * @param string $path path
  259. * @return string path
  260. */
  261. function dirPath($path) {
  262. $path = str_replace ( '\', '/', $path );
  263. if (substr ( $path, - 1 ) != '/')
  264. $path = $path . '/';
  265. return $path;
  266. }
  267. /**
  268. * Convert all file encoding formats under the directory
  269. *
  270. * @param string $in_charset original character set
  271. * @param string $out_charset target character set
  272. * @param string $dir directory address
  273. * @param string $fileexts converted File format
  274. * @return string If the original character set and the target character set are the same, return false, otherwise true
  275. */
  276. function dirIconv($in_charset, $out_charset, $dir, $fileexts = 'php|html|htm|shtml|shtm|js|txt|xml') {
  277. if ($in_charset == $out_charset)
  278. return false;
  279. $list = $this->dirList ( $dir );
  280. foreach ( $list as $v ) {
  281. if (preg_match ( "/.($fileexts)/i", $v ) && is_file ( $v )) {
  282. file_put_contents ( $v, iconv ( $in_charset, $out_charset, file_get_contents ( $v ) ) );
  283. }
  284. }
  285. return true;
  286. }
  287. /**
  288. * List all files in the directory
  289. *
  290. * @param string $path path
  291. * @param string $exts extension
  292. * @param array $list added file list
  293. * @return array all files that meet the conditions
  294. */
  295. function dirList($path, $exts = '', $list = array()) {
  296. $path = $this->dirPath ( $path );
  297. $files = glob ( $path . '*' );
  298. foreach ( $files as $v ) {
  299. $fileext = $this->fileext ( $v );
  300. if (! $exts || preg_match ( "/.($exts)/i", $v )) {
  301. $list [] = $v;
  302. if (is_dir ( $v )) {
  303. $list = $this->dirList ( $v, $exts, $list );
  304. }
  305. }
  306. }
  307. return $list;
  308. }
  309. /**
  310. * Set the access and modification time of all files under the directory
  311. *
  312. * @param string $path path
  313. * @param int $mtime modification time
  314. * @param int $atime access time
  315. * @return array Return when it is not a directory false, otherwise return true
  316. */
  317. function dirTouch($path, $mtime = TIME, $atime = TIME) {
  318. if (! is_dir ( $path ))
  319. return false;
  320. $path = $this->dirPath ( $path );
  321. if (! is_dir ( $path ))
  322. touch ( $path, $mtime, $atime );
  323. $files = glob ( $path . '*' );
  324. foreach ( $files as $v ) {
  325. is_dir ( $v ) ? $this->dirTouch ( $v, $mtime, $atime ) : touch ( $v, $mtime, $atime );
  326. }
  327. return true;
  328. }
  329. /**
  330. * Directory list
  331. *
  332. * @param string $dir path
  333. * @param int $parentid parent id
  334. * @param array $dirs passed in directory
  335. * @return array returns directory and subdirectory list
  336. */
  337. function dirTree($dir, $parentid = 0, $dirs = array()) {
  338. global $id;
  339. if ($parentid == 0)
  340. $id = 0;
  341. $list = glob ( $dir . '*' );
  342. foreach ( $list as $v ) {
  343. if (is_dir ( $v )) {
  344. $id ++;
  345. $dirs [$id] = array ('id' => $id, 'parentid' => $parentid, 'name' => basename ( $v ), 'dir' => $v . '/' );
  346. $dirs = $this->dirTree ( $v . '/', $id, $dirs );
  347. }
  348. }
  349. return $dirs;
  350. }
  351. /**
  352. * Directory list
  353. *
  354. * @param string $dir path
  355. * @return array Return directory list
  356. */
  357. function dirNodeTree($dir) {
  358. $d = dir ( $dir );
  359. $dirs = array();
  360. while ( false !== ($entry = $d->read ()) ) {
  361. if ($entry != '.' and $entry != '..' and is_dir ( $dir . '/' . $entry )) {
  362. $dirs[] = $entry;
  363. }
  364. }
  365. return $dirs;
  366. }
  367. /**
  368. * Get the directory size
  369. *
  370. * @param string $dirname directory
  371. * @return string bit B
  372. */
  373. function getDirSize($dirname) {
  374. if (! file_exists ( $dirname ) or ! is_dir ( $dirname ))
  375. return false;
  376. if (! $handle = opendir ( $dirname ))
  377. return false;
  378. $size = 0;
  379. while ( false !== ($file = readdir ( $handle )) ) {
  380. if ($file == "." or $file == "..")
  381. continue;
  382. $file = $dirname . "/" . $file;
  383. if (is_dir ( $file )) {
  384. $size += $this->getDirSize ( $file );
  385. } else {
  386. $size += filesize ( $file );
  387. }
  388. }
  389. closedir ( $handle );
  390. return $size;
  391. }
  392. /**
  393. * Convert bytes to Kb or Mb...
  394. * Parameter $size is the byte size
  395. */
  396. function bitSize($size) {
  397. if (! preg_match ( "/^[0-9]+$/", $num ))
  398. return 0;
  399. $type = array ("B", "KB", "MB", "GB", "TB", "PB" );
  400. $j = 0;
  401. while ( $num >= 1024 ) {
  402. if ($j >= 5)
  403. return $num . $type [$j];
  404. $num = $num / 1024;
  405. $j ++;
  406. }
  407. return $num . $type [$j];
  408. }
  409. /**
  410. * Get the file name suffix
  411. *
  412. * @param string $filename
  413. * @return string
  414. */
  415. function fileext($filename) {
  416. return addslashes ( trim ( substr ( strrchr ( $filename, '.' ), 1, 10 ) ) );
  417. }
  418. }
  419. ?>
复制代码


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.