Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Filesystem Functions : unlink

unlink

Deletes a file (PHP 4, PHP 5)
bool unlink ( string filename [, resource context] )


Related Examples ( Source code ) » unlink





Code Examples / Notes » unlink

jchase

[Editor's note: A suggestion for a work-around was submitted by argistof at gmail dot com: You can use the recursive option (see man chmod) when chmodding, for instance 'chmod 777 directory/ -R'. Be aware though, this will change the permissions of all files and folders in the diectory.]
Just a note which you probably all know, but I didn't, and it might save another poor sap some unnecessary time:
I was doing unlink() and fopen() on a file and got a permission denied error, even after chmoding the file to 0777.  
The folder that contains the file must ALSO have write permission.  Took a headache to find this out.  
Hope this helps someone :)


pc

To delete files using wildcards:
<?
function delfile($str)
{
   foreach(glob($str) as $fn) {
       unlink($fn);
   }
}
?>


chris

To delete all files of a particular extension, or infact, delete all with wildcard, a much simplar way is to use the glob function.  Say I wanted to delete all jpgs .........
<?php
foreach (glob("*.jpg") as $filename) {
  echo "$filename size " . filesize($filename) . "\n";
  unlink($filename);
}
?>


anarcho

Just to be a bit more accurate to the post of "jchase at solidmark dot com":
On unixoide systems you only need write permission for the directory to delete a file. The permissions of the file are nonrelevant.
You need file permissions if you want to change the file data or to read the data.


khalidz83

If you get an error while deleting a file from the system, check who is the owner of the file. For example if you move to another system and the owner is 'nobody' then the owner should be nobody for that file on the new system.If you delete as another user, you will get an error.

torch

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";
}


rahulnvaidya

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);
?>


james

Cheap and dirty example for cleaning a directory of files so many seconds old.
       function cleantmp() {
               $seconds_old = 3600;
               $directory = "/var/tmp";
               if( !$dirhandle = @opendir($directory) )
                       return;
               while( false !== ($filename = readdir($dirhandle)) ) {
                       if( $filename != "." && $filename != ".." ) {
                               $filename = $directory. "/". $filename;
                               if( @filemtime($filename) < (time()-$seconds_old) )
                                       @unlink($filename);
                       }
               }
       }


dagski_at_gmail_dot_com

before you could unlink a file created which uses a handle e.g.,
$handle = sqlite('temp.db');
unset($handle); first befofe
unlink($handle);
to avoide permission denied error.


ashley

Actually you should use "@unlink" rather than testing with file_exists. The former is atomic, whereas the latter can break if you can't guarantee only one process will try to delete a given file at a time.

paul

A work around for the Permission Denied problem.
I used ftp_connect() then ftp_delete() to erase files which unlink could not erase due to permision problems


ggarciaa

<?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);
?>


bishop

<?php
/**
* rm() -- Vigorously erase files and directories.
*
* @param $fileglob mixed If string, must be a file name (foo.txt), glob pattern (*.txt), or directory name.
*                        If array, must be an array of file names, glob patterns, or directories.
*/
function rm($fileglob)
{
   if (is_string($fileglob)) {
       if (is_file($fileglob)) {
           return unlink($fileglob);
       } else if (is_dir($fileglob)) {
           $ok = rm("$fileglob/*");
           if (! $ok) {
               return false;
           }
           return rmdir($fileglob);
       } else {
           $matching = glob($fileglob);
           if ($matching === false) {
               trigger_error(sprintf('No files match supplied glob %s', $fileglob), E_USER_WARNING);
               return false;
           }      
           $rcs = array_map('rm', $matching);
           if (in_array(false, $rcs)) {
               return false;
           }
       }      
   } else if (is_array($fileglob)) {
       $rcs = array_map('rm', $fileglob);
       if (in_array(false, $rcs)) {
           return false;
       }
   } else {
       trigger_error('Param #1 must be filename or glob pattern, or array of filenames or glob patterns', E_USER_ERROR);
       return false;
   }
   return true;
}
?>


Change Language


Follow Navioo On Twitter
basename
chgrp
chmod
chown
clearstatcache
copy
delete
dirname
disk_free_space
disk_total_space
diskfreespace
fclose
feof
fflush
fgetc
fgetcsv
fgets
fgetss
file_exists
file_get_contents
file_put_contents
file
fileatime
filectime
filegroup
fileinode
filemtime
fileowner
fileperms
filesize
filetype
flock
fnmatch
fopen
fpassthru
fputcsv
fputs
fread
fscanf
fseek
fstat
ftell
ftruncate
fwrite
glob
is_dir
is_executable
is_file
is_link
is_readable
is_uploaded_file
is_writable
is_writeable
lchgrp
lchown
link
linkinfo
lstat
mkdir
move_uploaded_file
parse_ini_file
pathinfo
pclose
popen
readfile
readlink
realpath
rename
rewind
rmdir
set_file_buffer
stat
symlink
tempnam
tmpfile
touch
umask
unlink
eXTReMe Tracker