Home > Backend Development > PHP Problem > How to delete files in a folder in php

How to delete files in a folder in php

藏色散人
Release: 2023-03-08 08:34:01
Original
4026 people have browsed it

How to delete files in a folder in php: 1. Delete the specified file directly through the unlink() function, the syntax is "unlink($filename)". 2. Use the while statement and the readdir() function to read the contents of the folder in a loop, use is_dir() to determine whether the file exists in the folder, and if it exists, use the unlink() method to delete it until all files in the folder are deleted.

How to delete files in a folder in php

#The operating environment of this article: Windows 7 system, PHP8, Dell G3 computer.

php file deletion uses the unlink() function

First create a file named testFile.txt.

Example

Delete the specified file

$filename = 'file.txt';
fopen($filename,'a+');
if(!unlink($filename))
{
echo "文件{$filename}删除失败"; 
}
else
{
echo "文件{$filename}删除成功";
}
?>
Copy after login

Delete all files in the directory

function delFileUnderDir( $dirName="../Smarty/templates/templates_c" )
{

if ( $handle = opendir( "$dirName" ) ) {
   while ( false !== ( $item = readdir( $handle ) ) ) {
   if ( $item != "." && $item != ".." ) {
   if ( is_dir( "$dirName/$item" ) ) {
         delFileUnderDir( "$dirName/$item" );
   } else {
   if( unlink( "$dirName/$item" ) )echo "成功删除文件: $dirName/$item<br />n";
   }
   }
   }
   closedir( $handle );
}
}
Copy after login

php unlink() function description

Function: Delete files.

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.

Return value: true if successful, false if failed.

【Recommended: PHP Video Tutorial

The above is the detailed content of How to delete files in a folder in php. 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