Three ways to delete directory files in PHP

Source: Internet
Author: User
Keywords Network programming PHP tutorial
Tags content delete delete directory directory file files function is_dir

1, pass the law: the use of recursive layers of delete.

The following is quoted content:
deleteDir ($ dir)
{
if (rmdir ($ dir) == false && is_dir ($ dir)) {
if ($ dp = opendir ($ dir)) {
while (($ file = readdir ($ dp))! = false) {
if (is_dir ($ file) && $ file! = '.' && $ file! = '..') {
deleteDir ($ file);
} else {
unlink ($ file);
}
}
closedir ($ dp);
} else {
exit ('Not permission');
}
}
}


2, the system call method

The following is quoted content:
function del_dir ($ dir)
{
if (strtoupper (substr (PHP_OS, 0, 3)) == 'WIN') {
$ str = "rmdir / s / q". $ dir;
} else {
$ str = "rm -Rf". $ dir;
}
}


3, circulation method

The following is quoted content:
function deltree ($ pathdir)
{
Echo $ pathdir; / ​​/ debug time
if (is_empty_dir ($ pathdir)) // if empty
{
rmdir ($ pathdir); / / delete directly
}
else
{// Otherwise read this directory, except .. and .. outside
$ d = dir ($ pathdir);
while ($ a = $ d-> read ())
{
if (is_file ($ pathdir. '/'. $ a) && ($ a! = '.') && ($ a! = '..')) {unlink ($ pathdir. '/'. $ a); }
// If the file is deleted directly
if (is_dir ($ pathdir. '/'. $ a) && ($ a! = '.') && ($ a! = '..'))
{// if it is a directory
if (! is_empty_dir ($ pathdir. '/'. $ a)) // is empty
{// If not, call itself, but the original path + his subordinate directory name
deltree ($ pathdir. '/'. $ a);
}
if (is_empty_dir ($ pathdir. '/'. $ a))
{// If it is empty, delete it
rmdir ($ pathdir. '/'. $ a);
}
}
}
$ d-> close ();
Echo "must first delete all the files in the directory"; / / I used when debugging
}
}
function is_empty_dir ($ pathdir)
{
// to determine whether the directory is empty
$ d = opendir ($ pathdir);
$ i = 0;
while ($ a = readdir ($ d))
{
$ i ++;
}
closedir ($ d);
if ($ i> 2) {return false;}
else return true;
}

Related Article

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.