Delete file using PHP code : unlink()


Posted on : Thu, 24th Sep 15 03:43 pm UTC
100+ votes

To delete a file or files using PHP code you can use the unlink() method.

Syntax : bool unlink ( string $fileName [, resource $context ] )

It returns a boolean TRUE if the file is deleted successfully and FALSE if it failed to delete it. The resource part is option, it was added in PHP version 5.



Advertisements





Lets see some examples :

1. Delete a single file using unlink()

File : php_unlink_example_1.php Language : PHP
<?php 

    $fileName = "some-file.txt";

    $filePath = "file/path/if/any/";

     //delete the file
    unlink($fileName.$filePath);


?>


2. Delete all text files in a directory using unlink()

File : php_unlink_example_2.php Language : PHP
<?php 

    $filePath = "file/path/if/any/";

   foreach (glob($filePath."*.*")) as $fileName) {
     //*.txt is a wild card will delete all text files contained in the directory location specified.
     unlink($fileName");
     echo $fileName." was deleted!";
 }


?>


3. Delete all files in a directory using unlink()

File : php_unlink_example_3.php Language : PHP
<?php 

    $filePath = "file/path/if/any/";
    
    foreach (glob($filePath."*.*")) as $fileName) {
     //*.* is a wildcard that will delete all files contained in the directory location specified.
    unlink($fileName);
    echo $fileName." was deleted!";
 }


?>


4. Delete all text files in a directory using easy way!

File : php_unlink_example_2.php Language : PHP
<?php 

   $filePath = "file/path/if/any/";
   $wildcard = "*.png"

   //will delete all png files
   array_map( "unlink", glob( $filePath.$wildcard ));
?>


Note :

  1. unlink was added to PHP in version 4, hence it will not work with previous versions.
  2. If you get an warning like Warning: unlink(uploaded_images/pdf.png): Permission denied in /Applications/XAMPP/xamppfiles/c2c/temp.php on line 7 , then its because you do not have permissions to either access this file or the directory.
  3. Its always good to get the boolean value returned by unlink method to check success or failure in deleting the files.

Code2care's mission is to share varied knowledge in technical and non-technical areas gathered during day-to-day learnings and development activities so that our visitors can leverage this portal to find solutions to their queries without re-inventing the wheel. Technical posts include Learnings, Tutorials, Video Tutorials, Code Snippets, Tips-n-tricks.

Follow us : Facebook - Twitter - Google +