©
This document uses PHP Chinese website manual Release
(PHP 4, PHP 5, PHP 7)
unlink — 删除文件
$filename
[, resource $context
] )
删除 filename
。和 Unix C 的
unlink() 函数相似。
发生错误时会产生一个 E_WARNING
级别的错误。
filename
文件的路径。
context
Note: 在 PHP 5.0.0 中增加了对上下文(Context)的支持。有关上下文(Context)的说明参见 Streams。
成功时返回 TRUE
, 或者在失败时返回 FALSE
。
版本 | 说明 |
---|---|
5.0.0 | 自 PHP 5.0.0 起 unlink() 也可以用于某些 URL 封装协议。参考支持的协议和封装协议 中的列表看哪些封装协议支持 unlink() 。 |
Example #1 基本的 unlink() 用法
<?php
$fh = fopen ( 'test.html' , 'a' );
fwrite ( $fh , '<h1>Hello world!</h1>' );
fclose ( $fh );
unlink ( 'test.html' );
?>
[#1] llmll at gmx dot de [2015-04-11 09:53:00]
On OSX, when fighting against a "Permission Denied" error, make sure, the directory has WRITE permissions for the executing php-user.
Furthermore, if you rely on ACLs, and want to delete a file or symlink, the containing directory needs to have "delete_child" permission in order to unlink things inside. If you only grant "delete" to the folder that will allow you to delete the container folder itself, but not the objects inside.
[#2] softontherocks at gmail dot com [2014-10-29 18:13:46]
Here you have a function to delete a directory and subdirectories recursively:
function deleteDirectory($dir){
$result = false;
if ($handle = opendir("$dir")){
$result = true;
while ((($file=readdir($handle))!==false) && ($result)){
if ($file!='.' && $file!='..'){
if (is_dir("$dir/$file")){
$result = deleteDirectory("$dir/$file");
} else {
$result = unlink("$dir/$fich");
}
}
}
closedir($handle);
if ($result){
$result = rmdir($dir);
}
}
return $result;
}
The source is found in http://softontherocks.blogspot.com/2014/09/eliminar-un-directorio-completo-con-php.html
[#3] Eric [2014-08-11 14:17:56]
This might seem obvious, but I was tearing my hair out with this problem - make sure the file you're trying to delete isn't currently being used. I had a script that was parsing a text file and was supposed to delete it after completing, but kept getting a permission denied error because I hadn't explicitly closed the file, hence it was technically still being "used" even though the parsing was complete.
[#4] Set [2014-04-05 03:57:41]
<?php
// for deleting in other directory
unlink("dir/" .$file ); //or
unlink("http://www.localhost/dir/" . $file );
?>
[#5] deen804 at gmail dot com [2013-12-10 06:14:40]
unlink($fileName); failed for me .
Then i tried using the realpath($fileName) function as
unlink(realpath($fileName)); it worked
just posting it , in case if any one finds it useful .
[#6] james at dunmore dot me dot uk [2013-10-24 14:52:16]
I know it is obvious, but.... if you have nested symlinks (for example, we archive into yyyy-mm for backups, and symbolic link to make our directory structure look flat - don't ask), unlink will only delete the top level symlink (as expected).
If you want to delete the actual file, you'll need to use readlink. If you want to delete all of the files and the symlinks, you'll need to recurse up and down to achieve that.
[#7] Alex, the Marrch Ca'at [2013-06-26 16:22:33]
The best way to delete files by mask is as follows:
<?php
array_walk(glob('/etc
function recursiveDelete($str){
if(is_file($str)){
return @unlink($str);
}
elseif(is_dir($str)){
$scan = glob(rtrim($str,'/').'
function unlinkRecursive($dir, $deleteRootToo)
{
if(!$dh = @opendir($dir))
{
return;
}
while (false !== ($obj = readdir($dh)))
{
if($obj == '.' || $obj == '..')
{
continue;
}
if (!@unlink($dir . '/' . $obj))
{
unlinkRecursive($dir.'/'.$obj, true);
}
}
closedir($dh);
if ($deleteRootToo)
{
@rmdir($dir);
}
return;
}
?>
[#17] Anonymous [2008-11-01 06:13:09]
To unlink, the web server user must have write permissions to the directory.
Conversely, if a user has write permissions to a directory, it may delete files from that directory regardless of who owns them...
[#18] hi at hi dot hi [2008-10-11 20:19:34]
using this function with windows will generate an error, make sure to use is_file
[#19] http://www.paladinux.net [2008-10-01 08:59:17]
Under Windows System and Apache, denied access to file is an usual error to unlink file.
To delete file you must to change file's owern.
An example:
<?php
chown($TempDirectory."/".$FileName,666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($TempDirectory."/".$FileName);
?>
[#20] gotdalife at gmail dot com [2008-09-25 07:04:46]
To anyone who's had a problem with the permissions denied error, it's sometimes caused when you try to delete a file that's in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with "../").
So to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located.
<?php
$old = getcwd(); // Save the current directory
chdir($path_to_file);
unlink($filename);
chdir($old); // Restore the old working directory
?>
[#21] southsentry at yahoo dot com [2008-08-31 10:23:06]
This is in response to alvaro at demogracia dot com
Yes, I found that out and have had to wrap it with is_file:
<?php
if(is_file("$file")) {
unlink("$file");
}
?>
[#22] PD [2008-08-06 05:07:11]
I have been working on some little tryout where a backup file was created before modifying the main textfile. Then when an error is thrown, the main file will be deleted (unlinked) and the backup file is returned instead.
Though, I have been breaking my head for about an hour on why I couldn't get my persmissions right to unlink the main file.
Finally I knew what was wrong: because I was working on the file and hadn't yet closed the file, it was still in use and ofcourse couldn't be deleted :)
So I thought of mentoining this here, to avoid others of making the same mistake:
<?php
// First close the file
fclose($fp);
// Then unlink :)
unlink($somefile);
?>
[#23] ayor ATTTTT ayor.biz [2007-12-20 06:02:21]
ggarciaa's post above has already one small error, closedir has to be used even if $DeleteMe is false
<?php
// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone
function SureRemoveDir($dir, $DeleteMe) {
if(!$dh = @opendir($dir)) return;
while (false !== ($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
}
closedir($dh);
if ($DeleteMe){
@rmdir($dir);
}
}
//SureRemoveDir('EmptyMe', false);
//SureRemoveDir('RemoveMe', true);
?>
[#24] rahulnvaidya at gmail dot com [2007-08-03 02:36:41]
ggarciaa's post above has one small error, it will ignore file and directory strings that are evaluated as false (ie. "0")
Fixed code is below (false !==)
<?php
// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone
function SureRemoveDir($dir, $DeleteMe) {
if(!$dh = @opendir($dir)) return;
while (false !== ($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
}
if ($DeleteMe){
closedir($dh);
@rmdir($dir);
}
}
//SureRemoveDir('EmptyMe', false);
//SureRemoveDir('RemoveMe', true);
?>
[#25] ggarciaa at gmail dot com [2007-07-03 23:00:46]
<?php
// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone
function SureRemoveDir($dir, $DeleteMe) {
if(!$dh = @opendir($dir)) return;
while (($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
}
if ($DeleteMe){
closedir($dh);
@rmdir($dir);
}
}
//SureRemoveDir('EmptyMe', false);
//SureRemoveDir('RemoveMe', true);
?>
[#26] torch at torchsdomain dot com [2006-11-22 12:27:36]
Here is simple function that will find and remove all files (except "." ones) that match the expression ($match, "*" as wildcard) under starting directory ($path) and all other directories under it.
function rfr($path,$match){
static $deld = 0, $dsize = 0;
$dirs = glob($path."*");
$files = glob($path.$match);
foreach($files as $file){
if(is_file($file)){
$dsize += filesize($file);
unlink($file);
$deld++;
}
}
foreach($dirs as $dir){
if(is_dir($dir)){
$dir = basename($dir) . "/";
rfr($path.$dir,$match);
}
}
return "$deld files deleted with a total size of $dsize bytes";
}
[#27] bmcouto at hotmail dot com [2006-09-30 13:30:37]
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
?>
Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the file to start working its destructive magic.
<?php
$myFile = "testFile.txt";
unlink($myFile);
?>
The testFile.txt should now be removed.
[#28] bishop [2005-06-05 12:30:53]
<?php
function rm($fileglob)
{
if (is_string($fileglob)) {
if (is_file($fileglob)) {
return unlink($fileglob);
} else if (is_dir($fileglob)) {
$ok = rm("$fileglob
function tail($file,&$pos) {
// get the size of the file
if(!$pos) $pos = filesize($file);
// Open an inotify instance
$fd = inotify_init();
// Watch $file for changes.
$watch_descriptor = inotify_add_watch($fd, $file, IN_ALL_EVENTS);
// Loop forever (breaks are below)
while (true) {
// Read events (inotify_read is blocking!)
$events = inotify_read($fd);
// Loop though the events which occured
foreach ($events as $event=>$evdetails) {
// React on the event type
switch (true) {
// File was modified
case ($evdetails['mask'] & IN_MODIFY):
// Stop watching $file for changes
inotify_rm_watch($fd, $watch_descriptor);
// Close the inotify instance
fclose($fd);
// open the file
$fp = fopen($file,'r');
if (!$fp) return false;
// seek to the last EOF position
fseek($fp,$pos);
// read until EOF
while (!feof($fp)) {
$buf .= fread($fp,8192);
}
// save the new EOF to $pos
$pos = ftell($fp); // (remember: $pos is called by reference)
// close the file pointer
fclose($fp);
// return the new data and leave the function
return $buf;
// be a nice guy and program good code ;-)
break;
// File was moved or deleted
case ($evdetails['mask'] & IN_MOVE):
case ($evdetails['mask'] & IN_MOVE_SELF):
case ($evdetails['mask'] & IN_DELETE):
case ($evdetails['mask'] & IN_DELETE_SELF):
// Stop watching $file for changes
inotify_rm_watch($fd, $watch_descriptor);
// Close the inotify instance
fclose($fd);
// Return a failure
return false;
break;
}
}
}
}
// Use it like that:
$lastpos = 0;
while (true) {
echo tail($file,$lastpos);
}
?>