php之unlink的使用:
unlink filename 只会删除 filename,但不会影响 filename 所在的目录结构。
只适用于文件,不适用于目录(尝试 unlink 目录会报错)。
只是解除目录对该文件的引用,如果该文件仍然被其他进程打开,它的内容不会立即被删除,直到最后一个引用关闭。
例子:
$ mkdir -p testdir/subdir
$ touch testdir/subdir/file.txt
$ unlink testdir/subdir/file.txt # 仅删除 file.txt,不影响 testdir/subdir
$ ls testdir/subdir
# 输出为空,表示文件删除了,但 subdir 仍然存在
实际项目使用:
public function removeFile(string $filePath): void
{
$filePath = $this->dmsDir . $filePath;
if (file_exists($filePath)) {
if (!unlink($filePath)) {
throw new \Exception("Failed to delete file '$filePath'.");
}
}
}
上面代码优化:
public function removeFile(string $filePath): void
{
$filePath = $this->dmsDir . $filePath;
if (is_file($filePath)) { // 确保它是一个文件, file_exists 对于目录也会返回true, 可以避免误删目录, 虽然这里unlink删除不了目录,但是减少了异常抛出次数
if (!@unlink($filePath)) { //unlink 只能对文件生效
throw new \RuntimeException("Failed to delete file '$filePath'.");
}
}
}
关于
file_exists:
https://www.php.net/manual/en/function.file-exists.php
is_file:
https://www.php.net/manual/en/function.is-file.php
