Home > Backend Development > PHP Problem > How to delete directory in php unlink

How to delete directory in php unlink

藏色散人
Release: 2023-03-08 18:00:01
Original
2685 people have browsed it

php unlink method to delete a directory: first create a PHP sample file; then delete the directory and files through loop traversal and unlink function.

How to delete directory in php unlink

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

The unlink() function deletes files.

If successful, return true, otherwise return false.

Syntax

unlink(filename,context)
Copy after login

Parameters

filename required. Specifies the files to be deleted.

context Optional. Specifies the environment for a file handle. Context is a set of options that modify the behavior of the stream.

PHP deletes the directory and all files in the directory

The code is as follows:

<?php 
//循环删除目录和文件函数 
function delDirAndFile( $dirName ) 
{ 
if ( $handle = opendir( “$dirName” ) ) { 
while ( false !== ( $item = readdir( $handle ) ) ) { 
if ( $item != “.” && $item != “..” ) { 
if ( is_dir( “$dirName/$item” ) ) { 
delDirAndFile( “$dirName/$item” ); 
} else { 
if( unlink( “$dirName/$item” ) )echo “成功删除文件: $dirName/$item<br />n”; 
} 
} 
} 
closedir( $handle ); 
if( rmdir( $dirName ) )echo “成功删除目录: $dirName<br />n”; 
} 
} 
//假设需要删除一个名叫”upload”的同级目录即此目录下的所有文件,你可以通过以下代码完成: 
delDirAndFile( ‘upload&#39;); 
?>
Copy after login

[Recommended learning: "PHP Video Tutorial 》】

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template