How to delete files or folders in PHP

Source: Internet
Author: User

Sometimes we need to use PHP to delete files and folders. PHP also has functions to implement. Below is a simple record of the Code to facilitate future persistence. First look at the code

<? Function deldir ($ dir) {// delete the files in the directory first: $ dh = opendir ($ dir); while ($ file = readdir ($ dh )) {if ($ file! = "." & $ File! = "..") {$ Fullpath = $ dir. "/". $ file; if (! Is_dir ($ fullpath) {unlink ($ fullpath) ;}else {deldir ($ fullpath) ;}} closedir ($ dh); // Delete the current folder: if (rmdir ($ dir) {return true;} else {return false ;}}?>

The unlink () function is used to delete objects. If the call succeeds, true is returned. If the call fails, false is returned. The rmdir () function is used to delete an empty directory. It tries to delete the directory specified by the dir. The directory must be empty and have the corresponding permissions.

One instance: delete all the ". svn" folders under a folder (including the content to be deleted ).

<? Phpfunction delsvn ($ dir) {$ dh = opendir ($ dir); // find all ". svn "folder: while ($ file = readdir ($ dh) {if ($ file! = "." & $ File! = ".. ") {$ Fullpath = $ dir. "/". $ file; if (is_dir ($ fullpath) {if ($ file = ". svn ") {delsvndir ($ fullpath);} else {delsvn ($ fullpath) ;}}} closedir ($ dh);} function delsvndir ($ svndir) {// delete the files in the directory first: $ dh = opendir ($ svndir); while ($ file = readdir ($ dh) {if ($ file! = "." & $ File! = ".. ") {$ Fullpath = $ svndir. "/". $ file; if (is_dir ($ fullpath) {delsvndir ($ fullpath);} else {unlink ($ fullpath) ;}} closedir ($ dh ); // Delete the directory folder if (rmdir ($ svndir) {return true;} else {return false; }}$ dir = dirname (_ FILE __); // echo $ dir; delsvn ($ dir);?>

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.