Cara menggunakan delete files php

19/03/2015    Fachrul Ahaddin    24934    Website

Cara menggunakan delete files php

Halo teman-teman,  pada kesempatan kali ini saya akan mencoba membuat baris program php untuk menghapus sebuah file dalam folder kita. Sebelumnya kita buat dulu sebuah folder di dalam xampp/htdocs dengan nama delete-file. Kemudian saya masukkan beberapa file gambar ke dalam folder tersebut.

Cara menggunakan delete files php

Terlihat gambar di atas ada 3 gambar yang saya masukkan. Saya menempatkan gambar tersebut dalam folder data di dalam folder delete-file.  Kita akan mulai melakukan koding phpnya. Coba teman-teman ketikkan baris program di bawah ini.

Cara menggunakan delete files php

Kemudian save dan jalankan pada browser localhost/delete-file. Dan lihat yang terjadi di dalam folder data yang tadi saya buat. File dengan nama logo-3.png sudah terhapus ketika kita mengakses file tersebut

Cara menggunakan delete files php

No data.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    To delete a file by using PHP is very easy. Deleting a file means completely erase a file from a directory so that the file is no longer exist. PHP has an unlink() function that allows to delete a file. The PHP unlink() function takes two parameters $filename and $context. Syntax:

    unlink( $filename, $context );

    Below programs illustrate the above approach: Program 1: This program uses unlink() function to remove file from directory. Suppose there is a file named as “gfg.txt” 

    php

    <?php

    $file_pointer = "gfg.txt";

    if (!unlink($file_pointer)) {

        echo ("$file_pointer cannot be deleted due to an error");

    }

    else {

        echo ("$file_pointer has been deleted");

    }

    ?>

    Output:

    gfg.txt has been deleted

    Program 2: This program uses unlink() function to delete a file from folder after using some operation. 

    php

    <?php

    $file_pointer = fopen('gfg.txt', 'w+');

    fwrite($file_pointer, 'A computer science portal for geeks!');

    fclose($file_pointer);  

    if (!unlink($file_pointer)) {

        echo ("$file_pointer cannot be deleted due to an error");

    }

    else {

        echo ("$file_pointer has been deleted");

    }

    ?>

    Output:

    Warning: unlink() expects parameter 1 to be a valid path, resource
    given in C:\xampp\htdocs\server.php on line 12
    Resource id #3 cannot be deleted due to an error

    Note: If the file does not exist then it will display an error.

    PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


    ❮ PHP Filesystem Reference

    Table of Contents

    • Definition and Usage
    • Parameter Values
    • Technical Details
    • To Read And Delete File From Folder It Takes Only Two Steps:-
    • Step 1. Make a PHP file to read file from folder
    • Step 2. Make a PHP file to delete file from folder
    • How can you delete file from PHP?
    • How do I empty a directory in PHP?
    • Which function is used in PHP to delete a file?
    • How do I delete a file in HTML?

    Example

    Delete a file:

    <?php
    $file = fopen("test.txt","w");
    echo fwrite($file,"Hello World. Testing!");
    fclose($file);

    unlink("test.txt");
    ?>



    Definition and Usage

    The unlink() function deletes a file.

    Syntax

    unlink(filename, context)

    Parameter Values

    ParameterDescription
    filename Required. Specifies the path to the file to delete
    context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream


    Technical Details

    Return Value:TRUE on success, FALSE on failure
    PHP Version:4.0+
    PHP Changelog:PHP 5.0 - Added the context parameter

    ❮ PHP Filesystem Reference

    Last Updated : Apr 15, 2022

    IN - PHP

    In this tutorial we will show you how to read and delete file from folder using PHP. Using this method you can display all the files present in folder and delete any type of file using PHP.

    You may also like create, edit and delete file using PHP.

    Join With 27,000+ Members In Our Google Group & Get Latest Tutorials

    Get our latest tutorials, How-To guides on web development every day right into your inbox.

    To Read And Delete File From Folder It Takes Only Two Steps:-

    1. Make a PHP file to read file from folder
    2. Make a PHP file to delete file from folder

    Step 1. Make a PHP file to read file from folder

    We make a PHP file and save it with a name read.php

    <html>
    <body>
    <div id="wrapper">
    
    <div id="file_div">
    <?php
    $folder = "images/";
    if ($dir = opendir($folder))
    {
     while (($file = readdir($dir)) !== false)
     {
      echo "<p>".$file."</p>";
      echo "<form method='post' action='delete_file.php'>";
      echo "<input type='hidden' name='file_name' value='".$file."'>";
      echo "<input type='submit' name='delete_file' value='Delete File'>";
      echo "</form>";
     }
     closedir($dir);
    }
    ?>
    </div>
    
    </div>
    </body>
    </html>
    

    In this step we read all the files from images folder and create a delete button for each file to delete that file from folder.

    We use opendir() function to open the folder for file reading and then use while() loop and readdir() function to read all the files and then we use closedir() function to close the directory.

    You may also like remove file extension using htaccess.

    Step 2. Make a PHP file to delete file from folder

    We make a PHP file and save it with a name delete_file.php

    <?php
    if(isset($_POST['delete_file']))
    {
     $filename = $_POST['file_name'];
     unlink('images/'.$filename);
    }
    ?>
    

    In this step we get the file name and use php unlink() function to delete that file from folder.

    That's all, this is how to read and delete file from folder using PHP. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

    Let’s see what steps are necessary to be taken to delete files with this method. First of all, you should create a files list with the glob() method. The second step is the iteration over that list. Then, you should inspect whether its a file or not. And, finally, it’s time to delete the given file with the unlink() method.

    Here is an example:

    <?php
    // PHP program for deleting all
    // file from a folder
       
    // Folder path to be flushed
    $folder_path = "myw3docs";
       
    // List of name of files inside
    // specified folder
    $files = glob($folder_path.'/*'); 
       
    // Delete all the files of the list
    foreach($files as $file) {
       
        if(is_file($file)) 
        
            // Deleting the given file
            unlink($file); 
    }
    ?>

    Or you can choose to apply a short code for the glob() method. First, it is necessary to create a files’ list with the glob() method. The next step is implementing the array_filter() method. Then, it comes to mapping the list to unlink() method with array_map.

    Here is how to do that:

    <?php
    // PHP program for deleting all files from a folder
      
    // Delete all the files inside the given folder
    array_map('unlink', array_filter(glob("myw3Docs/*"), 'is_file'));  
    ?>

    In the framework of this approach, it is required to create a list of files with DirectoryIterator. Then, iterate over it. Afterwards, you should validate the files during the process of testing whether the directory includes a dot. Finally, apply the getPathName method reference, deleting the file with unlink().

    Here is an example:

    <?php
    // PHP program for deleting all the files
    // from a folder
      
    // Folder path to be flushed
    $folder_path = 'myw3docs/';
      
    // Assign files inside the directory
    $dir = new DirectoryIterator(dirname($folder_path));
      
    // Delete all the files in the list
    foreach ($dir as $fileinfo) {
          
        if (!$fileinfo->isDot() && $fileinfo->isFile()) {
      
            // Deleting the given file
            unlink($fileinfo->getPathname());
        }
    }
    ?>

    In this snippet, we showed you the most common and efficient ways to delete files from the folder with PHP.

    How can you delete file from PHP?

    To delete a file in PHP, use the unlink function. Let's go through an example to see how it works. The first argument of the unlink function is a filename which you want to delete. The unlink function returns either TRUE or FALSE , depending on whether the delete operation was successful.

    How do I empty a directory in PHP?

    The rmdir() function in PHP is an inbuilt function which is used to remove an empty directory. It is mandatory for the directory to be empty, and it must have the relevant permissions which are required to delete the directory.

    Which function is used in PHP to delete a file?

    PHP | unlink() Function The unlink() function is an inbuilt function in PHP which is used to delete files.

    How do I delete a file in HTML?

    Deleting pages and files from the server.

    Browse to the page you want to delete. OR. ... .

    If you are trying the delete a web page file (. html), make sure you are not editing the page. ... .

    Select File > Actions > Delete Page from the Contribute menu bar..

    Click Yes in the confirmation dialog box to delete the file permanently..