search
HomeBackend DevelopmentPHP ProblemPHP file operation: remove files or directories with a given path
PHP file operation: remove files or directories with a given pathAug 23, 2021 pm 03:36 PM
phpDelete Filesdelete directoryFile operations

In the previous article "php file operation: extracting the name of the file/directory", we learned about the method of obtaining the name part of the file/directory. This time we continue the PHP file operation series and talk about how to delete specified files or directories. Interested friends can learn about it~

When operating files/directories, not only can You can also operate on the data of the file/directory itself (such as deleting the file/directory). Today we will introduce to you how to delete specified files or directories.

1: Delete specified file operation

To delete a file, you can use the unlink($filename,$context) function, It can delete the specified file $filename, and the optional parameter $context is used to specify the environment of the file handle. Returns TRUE if the execution succeeds and FALSE if it fails.

Let’s take a look at the specific code examples:

Example 1: Delete the "test.txt" file in the same directory

PHP file operation: remove files or directories with a given path

<?php
header("content-type:text/html;charset=utf-8");
$file = &#39;test.txt&#39;;
if(file_exists($file)){
    if(unlink($file)){
        echo $file.&#39; 删除成功!&#39;;
    }else{
        echo $file.&#39; 删除失败!&#39;;
    }
}else{
    echo $file.&#39; 不存在!&#39;;
}
?>

The output result is:

PHP file operation: remove files or directories with a given path

After reopening the directory and looking at the files, you will find that the "test.txt" file no longer exists.

PHP file operation: remove files or directories with a given path

Example 2: Delete the "text.txt" file in the D:\demo directory

PHP file operation: remove files or directories with a given path

<?php
header("content-type:text/html;charset=utf-8");
$file = &#39;D:/demo/text.txt&#39;;
if(file_exists($file)){
    if(unlink($file)){
        echo $file.&#39; 删除成功!&#39;;
    }else{
        echo $file.&#39; 删除失败!&#39;;
    }
}else{
    echo $file.&#39; 不存在!&#39;;
}
?>

Output results For:

PHP file operation: remove files or directories with a given path

# After reopening the directory and looking at the files, you will find that the "text.txt" file no longer exists.

PHP file operation: remove files or directories with a given path

How to delete all files in a directory, you can use loops and readdir() to obtain all files and directories in the D:\demo directory (excluding subdirectories ), and then delete all the files in it:

<?php
header("content-type:text/html;charset=utf-8");
$dir = &#39;D:/demo&#39;;
if (is_dir($dir)) {
	$info = opendir($dir);
	while (($file = readdir($info)) !== false) {//用不全等于是区分如果文件夹名字为0的时候,那么0!==false,仍然可以遍历
		if ($file != "." && $file != ".." ) {
			$path = $dir . &#39;/&#39; . $file;
			if(is_dir($path)){
				continue;
			}
			unlink($path);
		}
	}
	echo &#39;文件删除成功!&#39;;
	closedir($info);
} 
?>

The output result is:

PHP file operation: remove files or directories with a given path

After reopening the directory and looking at the files, you will find that only An "img" folder still exists.

PHP file operation: remove files or directories with a given path

2: Delete the specified directory operation

To delete a directory, you can usermdir($dir ,$context) function, $context is an omitted parameter, used to specify the environment of the file handle. Returns TRUE if the execution succeeds and FALSE if it fails.

It should be noted that when using the rmdir() function to delete the specified directory, the directory must be empty and must have corresponding permissions. Deleting a directory that is not empty will also generate an E_WERNING level error.

Let’s take a look at the specific code examples: Delete the empty directory “img” under the D:\demo directory

<?php
	header("content-type:text/html;charset=utf-8");
    $dir = &#39;D:/demo/img&#39;;
    if(is_dir($dir)){
        if(rmdir($dir)) echo &#39;目录删除成功!&#39;;
    }else{
        echo "目录不存在!";
    }
?>

The output result is:

PHP file operation: remove files or directories with a given path

After reopening the directory and looking at the files, you will find that the empty directory "img" no longer exists.

PHP file operation: remove files or directories with a given path

But in most cases, the directory we need to delete is not empty, and it contains many sub-files and sub-directories. How can we delete it? What about the specified directory and its sub-files and directories?

Specific implementation method: You can traverse all files and folders in this directory and delete all files and folders in this directory one by one recursively

As given below Specific implementation code:

<?php
    function deldir($path){
        //如果是目录则继续
        if(is_dir($path)){
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            //如果 $p 中有两个以上的元素则说明当前 $path 不为空
            if(count($p)>2){
                foreach($p as $val){
                    //排除目录中的.和..
                    if($val !="." && $val !=".."){
                        //如果是目录则递归子目录,继续操作
                        if(is_dir($path.$val)){
                            //子目录中操作删除文件夹和文件
                            deldir($path.$val.&#39;/&#39;);
                        }else{
                            //如果是文件直接删除
                            unlink($path.$val);
                        }
                    }
                }
            }
        }
        //删除目录
        return rmdir($path);
    }
    //设置需要删除的文件夹
    $path = "D:/demo/";
    //调用函数,传入路径
    deldir($path);
?>

Okay, that’s all. If you want to know anything else, you can click this. → →

Basic operation of PHP files

## Recommended:

PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of PHP file operation: remove files or directories with a given path. 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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft