Home  >  Article  >  Backend Development  >  How to delete all file contents in a directory with PHP?

How to delete all file contents in a directory with PHP?

Guanhui
GuanhuiOriginal
2020-07-22 10:36:442520browse

How to delete all file contents in a directory with PHP?

#How to delete all file contents in a directory with PHP?

First create a function and accept a parameter; then use the "opendir" function in the function to open the passed in parameters; finally iterate through the returned results and determine whether it is a folder. If Yes, recursion is required, otherwise the file can be deleted.

Sample code

<?php
$dirName = &#39;/www/tmp&#39;;
echo "current :".get_current_user()."  ".$dirName;
deleteDir($dirName);
function deleteDir($dirName){
    if(file_exists($dirName)){//判断目录是否存在
        //如果是目录,那么我们就遍历下面的文件或者目录
        //打开目录句柄
        $dir = opendir($dirName);
        while($fileName = readdir($dir)){
            //不运行像上级目录运行
            if($fileName!="." && $fileName!=".."){
                $file = $dirName."/".$fileName;
                echo "||".$file."||";
                if(is_dir($file)){
                    deleteDir($file);//使用递归删除目录
                }else{
                    echo "--delete-".$file."++";
                    unlink($file);
                }
            }
        }
        closedir($dir);//关闭dir

        if( rmdir( $dirName ) )echo "成功删除目录: $dirName"; 

        
    }else{
        echo "对不起,目录不存在";
    }
}

Recommended tutorial: "PHP"

The above is the detailed content of How to delete all file contents in a directory with 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