7.2 Removing a File


You want to delete a file.

Technique

Use the unlink() function:

 <?php unlink ($somefile)   or die ("Cannot delete $somefile"); ?> 

Comments

unlink() returns 1 on success and on failure. Therefore, you can test the return value with either an or (or) operator or an if - else block.

If you want to delete a list of files, you can use a foreach loop to loop through the array items and unlink each subsequent file:

 <?php foreach ($files as $file) {      unlink($file)       or die("Cannot delete $file"); } ?> 

If you are having trouble deleting a file, keep in mind that to delete a file under the UNIX operating system, you do not need write access to a file, but rather to the directory in which the file is held. The reason is that on a systems level, when you delete a file you are not modifying the file, but rather you are modifying the directory. This causes funny quirks when it comes to file permissions. Sometimes you can have write access to a file, but you won't be able to delete it because of directory permissions and vice versa.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net