php method to delete files based on path: 1. Delete folders and files under a path through the "function deleteDir($dir){...}" method; 2. Through the "function deldir($path) ){...}"delete.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How does php delete files based on the path? PHP deletes a path Methods for all folders and files under
Function used:
scandir($path) Traverses all files in a folder and returns an array.
unlink($filename) Delete the file.
rmdir($path) Delete only empty folders
Code:
Delete a single file
$file = "./aa/aas.txt"; if (!unlink($file)) { echo ("Error deleting $file"); } else { echo ("Deleted $file"); }
Delete all folders and files under a path Method 1
$path = "./aa"; function deleteDir($dir) { if (!$handle = @opendir($dir)) { return false; } while (false !== ($file = readdir($handle))) { if ($file !== "." && $file !== "..") { //排除当前目录与父级目录 $file = $dir . '/' . $file; if (is_dir($file)) { deleteDir($file); } else { @unlink($file); } } } @rmdir($dir); } deleteDir($path);
Method 2 to delete all folders and files under a path
//设置需要删除的文件夹 $path = "./aa"; //清空文件夹函数和清空文件夹后删除空文件夹函数的处理 function deldir($path){ //如果是目录则继续 if(is_dir($path)){ //扫描一个文件夹内的所有文件夹和文件并返回数组 $p = scandir($path); foreach($p as $val){ //排除目录中的.和.. if($val !="." && $val !=".."){ //如果是目录则递归子目录,继续操作 if(is_dir($path.'/'.$val)){ //子目录中操作删除文件夹和文件 deldir($path.'/'.$val); //目录清空后删除空文件夹 @rmdir($path.'/'.$val); }else{ //如果是文件直接删除 unlink($path.'/'.$val); } } } } } //调用函数,传入路径 deldir($path);
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete files based on path in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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),

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
