Home  >  Article  >  Backend Development  >  How to delete all file contents in php

How to delete all file contents in php

藏色散人
藏色散人Original
2021-06-10 09:27:012234browse

php method to delete all file contents: first create a PHP sample file; then delete the folder and all files under the folder through the "public function deldir($dir) {...}" method .

How to delete all file contents in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to delete all file contents with php?

PHP deletes the folder and all files under the folder

  • Only deletes the files contained in the folder, not the folder

public function deldir($dir) {
//先删除目录下的文件:
$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 folder and all files under the folder

public function deldir($dir) {
//先删除目录下的文件:
$dh = opendir($dir);
while ($file = readdir($dh)) {
if($file != "." && $file!="..") {
$fullpath = $dir."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
} else {
deldir($fullpath);
}
}
}
closedir($dh);
//删除当前文件夹:
if(rmdir($dir)) {
return true;
} else {
return false;
}
}
  • Create the folder and specify permissions and encoding

if (!is_dir($dir)){                                 //如果目录不存在
mkdir(iconv("UTF-8", "GBK", $dir),0777,true);   //创建目录,777权限,GBK编码格式
}

【Recommended learning: PHP video tutorial

The above is the detailed content of How to delete all file contents in php. For more information, please follow other related articles on the PHP Chinese website!

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