When developing with PHP, deleting specified files is a very common operation. This article will introduce how to delete specified files using PHP.
1. How to delete files using PHP
PHP deletes files by calling the unlink()
function. The syntax of this function is as follows:
bool unlink ( string $filename [, resource $context ] )
The filename
parameter is the file name to be deleted, and the context
parameter is the optional file context.
If the deletion is successful, the function returns true
; if the deletion fails, the function returns false
.
2. Sample program
The following is a simple sample program that demonstrates how to use PHP to delete specified files:
<?php $file = 'example.txt'; if (file_exists($file)) { if (unlink($file)) { echo "文件删除成功:$file"; } else { echo "文件删除失败:$file"; } } else { echo "文件不存在:$file"; } ?>
3. Code analysis
$file
. file_exists()
function to detect whether the file exists. If the file exists, delete it, otherwise it will prompt that the file does not exist. unlink()
function to delete the file. If the deletion is successful, file deletion success will be output: $file
, otherwise file deletion failure will be output: $file
. 4. Notes
# The unlink()
function can only delete files, not directories. 5. Summary
This article introduces how to use PHP to delete specified files. Specified files can be easily deleted by calling the unlink()
function. When deleting files, you need to pay attention to whether the files are in use and perform permission verification to ensure system security.
The above is the detailed content of php delete specified files. For more information, please follow other related articles on the PHP Chinese website!