How PHP deletes all files and folders under a path

Source: Internet
Author: User
This article mainly share with you how PHP deletes all files and folders under a path, PHP iterates through all the files and folders within a folder, and removes all the files from all folders and subfolders, recursively realizing the effect of emptying a directory, and the code is simple and practical.

It is also suitable to clean up the cache in thinkphp, in thinkphp can write the following code to the./application/admin/common/function.php file, and then call this function in the controller to clean up the operation.

The function to use:

Scandir ($path)    iterates through all the files in a folder and returns an array.    unlink ($filename) to    delete the file.    rmdir ($path)    Delete only empty folders
<?php//Set the folder to be deleted  $path = "./application/runtime/";  After emptying the folder function and emptying the folder, delete the empty folder function  Deldir ($path) {   //If the directory continues if   (Is_dir ($path)) {    // Scans all folders and files within a folder and returns an array   $p = Scandir ($path);   foreach ($p as $val) {    //exclude directories in. and.    if ($val! = "." && $val! = "...") {     //If directory is recursive subdirectory, continue operation     if (Is_dir ($path. $val)) {      //subdirectory Operation Delete folder and file      Deldir ($path. $val. '/');      Delete empty folder @rmdir after directory emptying      ($path. $val. '/');     } else{      //If the file is deleted directly      unlink ($path. $val);}}}}  //Call function, incoming path Deldir ($path);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.