PHP - Remove File From Directory

In this tutorial we will create a Remove File From Directory Using PHP. PHP is a server-side scripting language designed primarily for web development. Using PHP, you can let your user directly interact with the script and easily to learned its syntax. It is mostly used by a newly coders for its user friendly environment. So Let's do the coding...

Getting Started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">PHP - Remove File From Directory</h3>
  16. <hr style="border-top:1px dotted #ccc;"/>
  17. <table class="table table-bordered">
  18. <thead class="alert-info">
  19. <tr>
  20. <th>Filename</th>
  21. <th>Action</th>
  22. </tr>
  23. </thead>
  24. <tbody style="background-color:#fff;">
  25. <?php
  26. $files = scandir('files/');
  27. foreach ($files as $file){
  28. if($file != '.' && $file !='..'){
  29. $path = "files/".$file;
  30. ?>
  31. <tr>
  32. <td><?php echo $file?></td>
  33. <td><a class="text-danger" href="remove.php?file_name=<?php echo $path?>">Remove</a></td>
  34. </tr>
  35. <?php
  36. }
  37. }
  38. ?>
  39.  
  40. </tbody>
  41. </table>
  42. </div>
  43. </body>
  44. </html>

Creating the Main Function

This code contains the main function of the application. This code will remove the file inside the directory when the button is clicked. To make this just simple copy and write the this block of codes inside the text editor, then save it as remove.php.
  1. <?php
  2. if(ISSET($_REQUEST['file_name'])){
  3. if(unlink($_REQUEST['file_name'])){
  4. header('location: index.php');
  5. }
  6. }
  7. ?>
There you have it we successfully created Remove File From Directory using PHP. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

Add new comment