PHP MySQL Tutorial
Learn PHP and MySQL

Remove a File Using PHP

100% of people found this useful
Remove a File Using PHP

To remove a file from php use the unlink() function. You can enter either the full path or the relative path to the file. You can see the examples below. All of them are valid.

unlink('deleteme.txt');
unlink('/home/arman/public_html/deleteme.txt');
unlink('./deleteme.txt');
unlink('../deleteme.txt');


PHP will give you a warning if the file you want to remove doesn't exist so you may want to force php to be quiet using the '@' character like this :

@unlink('./deleteme.txt');

Or you can first test if the file exist or not like thigs

$fileToRemove = '/home/arman/public_html/deleteme.txt';
if (file_exists($fileToRemove))) {
   // yes the file does exist
   unlink($fileToRemove);
} else {
   // the file is not found, do something about it???
}


PHP will also give you a warning if you don't have enough permission to delete the file. It would be better if your code check if the file is removed successfully or not like show below

$fileToRemove = '/home/arman/public_html/deleteme.txt';
if (file_exists($fileToRemove)) {
   // yes the file does exist

   if (@unlink($fileToRemove) === true) {
      // the file successfully removed
   } else {
      // something is wrong, we may not have enough permission
      // to delete this file
   }
} else {
   // the file is not found, do something about it???
}

Recent Comments

By: wishofweb Posted on 02-09-2013 8:49 AM

Good Help

By: wishofweb Posted on 02-09-2013 8:49 AM

Good Help

Powered by Community Server (Non-Commercial Edition), by Telligent Systems