php 如何从php中的文件夹中删除文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13507721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to delete a file from folder in php
提问by xing
I have a folder 'items'in which there are 3 files item1.txt, item2.txt and item3.txt.I want to delete item2.txtfile from folder. I am using the below code but it not deleting a file from folder. Can any body help me in that.
我有一个文件夹'items',其中有 3 个文件item1.txt, item2.txt and item3.txt.我想delete item2.txt从文件夹中归档。我正在使用下面的代码,但它没有从文件夹中删除文件。任何机构都可以帮助我。
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($file);
}
}
closedir($dirHandle);
?>
回答by Vamsi
Initially folder should have 777 permissions
$data="item2.txt"; $dir = "items"; while ($file = readdir($dirHandle)) { if($file==$data) { unlink($dir.'/'.$file); } }
最初文件夹应该有 777 权限
$data="item2.txt"; $dir = "items"; while ($file = readdir($dirHandle)) { if($file==$data) { unlink($dir.'/'.$file); } }
or try
或尝试
$path = $_SERVER['DOCUMENT_ROOT'].'items/item2.txt';
unlink($path);
回答by Tahir Yasin
No need of while loop here for just deleting a file, you have to pass path of that file to unlink() function, as shown below.
这里不需要while循环来删除一个文件,你必须将该文件的路径传递给unlink()函数,如下所示。
$file_to_delete = 'items/item2.txt';
unlink($file_to_delete);
Please read details of unlink() function
请阅读 unlink() 函数的详细信息
回答by Sibu
回答by som
if($file==$data) {
unlink( $dir .'/'. $file);
}
回答by prabhu programmer
It's very simple:
这很简单:
$file='a.txt';
if(unlink($file))
{
echo "file named $file has been deleted successfully";
}
else
{
echo "file is not deleted";
}
//if file is in other folder then do as follows
unlink("foldername/".$file);
回答by Louis Loudog Trottier
try renaming it to the trash or a temp folder that the server have access **UNLESS IT'S sensitive data.
尝试将其重命名为服务器有权访问的垃圾箱或临时文件夹**除非它是敏感数据。
rename($old, $new) or die("Unable to rename $old to $new.");

