Tuesday 25 July 2017

PHP Filesystem with Ajax JQuery

1. List Folder from Directory


2. Create Folder or Directory



3. Change or Rename Folder or Directory Name



4. Upload File in Folder or Directory


5. List Files from Folder or Directory



6. Remove or Delete Files From Folder or Directory



7. Remove or Delete Folder or Directory



8. Change File Name Inside Folder



9. How to Get Folder or Directory Size



There are received many request on made tutorial on PHP Filesystem, so in this post we have discuss PHP Filesystem with Ajax JQuery. In this post we will discuss different function of PHP Filesystem function how can we used particular function as per our requirement. PHP Filesystem mainly deal with files or folder or directory. If you are looking for web tutorial on PHP filesystem then you have to follow this post in which we have used this function with Ajax Jquery. So we can perform all operation without refresh of web page.

For discuss this tutorial we will first list all folder from directory by using PHP glob() function. By using this function we can get all list of files or folder now we want to get only directory then we have used array_filter(). So by using both function we can filter only folder from directory and display on web page. After this we want to create new folder dynamically, so we have use mkdir() PHP Filesystem function. By using this function we can create new folder in directory. After create new folder now we want to change folder name so we have use rename() function for change particular folder or directory name dynamically. Then after we want to upload file in particular folder, so we have use move_uploaded_file() function for upload files in particular folder. After uploading files in particular folder, now we want to list files from particular folder, show we have use scandir() function, by using this function we have list files from particular folder. After list files from particular folder now we want to remove files from folder or directory so we have use unlink() function. This function will remove files from particular folder. And lastly we want to remove folder or directory dynamically so we have use rmdir() function. By using this function we can remove folder or directory but this function will remove only blank folder or directory, so first we want to remove all files from folder, then we can use this folder or directory.

Here we have not only use PHP script but also we have use Ajax JQuery and Bootstrap modal. We can do this all operation without refresh of web page. For front end we have use Ajax JQuery and Bootstrap modal, we have send request to server by using Ajax and it will send particular operation request to server and at server side we have use different PHP Filesystem function for do different operation like list folder or directory, create new folder or directory, rename particular folder or directory, upload files in folder or directory, list files from folder or directory, remove files from folder and delete or remove folder or directory. This all operation we can do without refresh of web page because we have use Ajax Jquery with PHP script. Below you can find complete source code and above you can get all video of this PHP filesystem video series.




Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Filesystem with Ajax JQuery</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br /><br />
  <div class="container">
   <h2 align="center">PHP Filesystem with Ajax JQuery</a></h2>
   <br />
   <div align="right">
    <button type="button" name="create_folder" id="create_folder" class="btn btn-success">Create</button>
   </div>
   <br />
   <div class="table-responsive" id="folder_table">
    
   </div>
  </div>
 </body>
</html>

<div id="folderModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title"><span id="change_title">Create Folder</span></h4>
   </div>
   <div class="modal-body">
    <p>Enter Folder Name
    <input type="text" name="folder_name" id="folder_name" class="form-control" /></p>
    <br />
    <input type="hidden" name="action" id="action" />
    <input type="hidden" name="old_name" id="old_name" />
    <input type="button" name="folder_button" id="folder_button" class="btn btn-info" value="Create" />
    
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>
<div id="uploadModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Upload File</h4>
   </div>
   <div class="modal-body">
    <form method="post" id="upload_form" enctype='multipart/form-data'>
     <p>Select Image
     <input type="file" name="upload_file" /></p>
     <br />
     <input type="hidden" name="hidden_folder_name" id="hidden_folder_name" />
     <input type="submit" name="upload_button" class="btn btn-info" value="Upload" />
    </form>
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>

<div id="filelistModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">File List</h4>
   </div>
   <div class="modal-body" id="file_list">
    
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>

<script>
$(document).ready(function(){
 
 load_folder_list();
 
 function load_folder_list()
 {
  var action = "fetch";
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:action},
   success:function(data)
   {
    $('#folder_table').html(data);
   }
  });
 }
 
 $(document).on('click', '#create_folder', function(){
  $('#action').val("create");
  $('#folder_name').val('');
  $('#folder_button').val('Create');
  $('#folderModal').modal('show');
  $('#old_name').val('');
  $('#change_title').text("Create Folder");
 });
 
 $(document).on('click', '#folder_button', function(){
  var folder_name = $('#folder_name').val();
  var old_name = $('#old_name').val();
  var action = $('#action').val();
  if(folder_name != '')
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{folder_name:folder_name, old_name:old_name, action:action},
    success:function(data)
    {
     $('#folderModal').modal('hide');
     load_folder_list();
     alert(data);
    }
   });
  }
  else
  {
   alert("Enter Folder Name");
  }
 });
 
 $(document).on("click", ".update", function(){
  var folder_name = $(this).data("name");
  $('#old_name').val(folder_name);
  $('#folder_name').val(folder_name);
  $('#action').val("change");
  $('#folderModal').modal("show");
  $('#folder_button').val('Update');
  $('#change_title').text("Change Folder Name");
 });
 
 $(document).on("click", ".delete", function(){
  var folder_name = $(this).data("name");
  var action = "delete";
  if(confirm("Are you sure you want to remove it?"))
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{folder_name:folder_name, action:action},
    success:function(data)
    {
     load_folder_list();
     alert(data);
    }
   });
  }
 });
 
 $(document).on('click', '.upload', function(){
  var folder_name = $(this).data("name");
  $('#hidden_folder_name').val(folder_name);
  $('#uploadModal').modal('show');
 });
 
 $('#upload_form').on('submit', function(){
  $.ajax({
   url:"upload.php",
   method:"POST",
   data: new FormData(this),
   contentType: false,
   cache: false,
   processData:false,
   success: function(data)
   { 
    load_folder_list();
    alert(data);
   }
  });
 });
 
 $(document).on('click', '.view_files', function(){
  var folder_name = $(this).data("name");
  var action = "fetch_files";
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:action, folder_name:folder_name},
   success:function(data)
   {
    $('#file_list').html(data);
    $('#filelistModal').modal('show');
   }
  });
 });
 
 $(document).on('click', '.remove_file', function(){
  var path = $(this).attr("id");
  var action = "remove_file";
  if(confirm("Are you sure you want to remove this file?"))
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{path:path, action:action},
    success:function(data)
    {
     alert(data);
     $('#filelistModal').modal('hide');
     load_folder_list();
    }
   });
  }
 });

$(document).on('blur', '.change_file_name', function(){
  var folder_name = $(this).data("folder_name");
  var old_file_name = $(this).data("file_name");
  var new_file_name = $(this).text();
  var action = "change_file_name";
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{folder_name:folder_name, old_file_name:old_file_name, new_file_name:new_file_name, action:action},
   success:function(data)
   {
    alert(data);
   }
  });
 });
 
});
</script>


action.php



<?php

function format_folder_size($size)
{
 if ($size >= 1073741824)
 {
  $size = number_format($size / 1073741824, 2) . ' GB';
 }
    elseif ($size >= 1048576)
    {
        $size = number_format($size / 1048576, 2) . ' MB';
    }
    elseif ($size >= 1024)
    {
        $size = number_format($size / 1024, 2) . ' KB';
    }
    elseif ($size > 1)
    {
        $size = $size . ' bytes';
    }
    elseif ($size == 1)
    {
        $size = $size . ' byte';
    }
    else
    {
        $size = '0 bytes';
    }
 return $size;
}

function get_folder_size($folder_name)
{
 $total_size = 0;
 $file_data = scandir($folder_name);
 foreach($file_data as $file)
 {
  if($file === '.' or $file === '..')
  {
   continue;
  }
  else
  {
   $path = $folder_name . '/' . $file;
   $total_size = $total_size + filesize($path);
  }
 }
 return format_folder_size($total_size);
}

if(isset($_POST["action"]))
{
 if($_POST["action"] == "fetch")
 {
  $folder = array_filter(glob('*'), 'is_dir');
  
  $output = '
  <table class="table table-bordered table-striped">
   <tr>
    <th>Folder Name</th>
    <th>Total File</th>
    <th>Size</th>
    <th>Update</th>
    <th>Delete</th>
    <th>Upload File</th>
    <th>View Uploaded File</th>
   </tr>
   ';
  if(count($folder) > 0)
  {
   foreach($folder as $name)
   {
    $output .= '
     <tr>
      <td>'.$name.'</td>
      <td>'.(count(scandir($name)) - 2).'</td>
      <td>'.get_folder_size($name).'</td>
      <td><button type="button" name="update" data-name="'.$name.'" class="update btn btn-warning btn-xs">Update</button></td>
      <td><button type="button" name="delete" data-name="'.$name.'" class="delete btn btn-danger btn-xs">Delete</button></td>
      <td><button type="button" name="upload" data-name="'.$name.'" class="upload btn btn-info btn-xs">Upload File</button></td>
      <td><button type="button" name="view_files" data-name="'.$name.'" class="view_files btn btn-default btn-xs">View Files</button></td>
     </tr>';
   }
  }
  else
  {
   $output .= '
    <tr>
     <td colspan="6">No Folder Found</td>
    </tr>
   ';
  }
  $output .= '</table>';
  echo $output;
 }
 
 if($_POST["action"] == "create")
 {
  if(!file_exists($_POST["folder_name"])) 
  {
   mkdir($_POST["folder_name"], 0777, true);
   echo 'Folder Created';
  }
  else
  {
   echo 'Folder Already Created';
  }
 }
 if($_POST["action"] == "change")
 {
  if(!file_exists($_POST["folder_name"]))
  {
   rename($_POST["old_name"], $_POST["folder_name"]);
   echo 'Folder Name Change';
  }
  else
  {
   echo 'Folder Already Created';
  }
 }
 
 if($_POST["action"] == "delete")
 {
  $files = scandir($_POST["folder_name"]);
  foreach($files as $file)
  {
   if($file === '.' or $file === '..')
   {
    continue;
   }
   else
   {
    unlink($_POST["folder_name"] . '/' . $file);
   }
  }
  if(rmdir($_POST["folder_name"]))
  {
   echo 'Folder Deleted';
  }
 }
 
 if($_POST["action"] == "fetch_files")
 {
  $file_data = scandir($_POST["folder_name"]);
  $output = '
  <table class="table table-bordered table-striped">
   <tr>
    <th>Image</th>
    <th>File Name</th>
    <th>Delete</th>
   </tr>
  ';
  
  foreach($file_data as $file)
  {
   if($file === '.' or $file === '..')
   {
    continue;
   }
   else
   {
    $path = $_POST["folder_name"] . '/' . $file;
    $output .= '
    <tr>
     <td><img src="'.$path.'" class="img-thumbnail" height="50" width="50" /></td>
     <td contenteditable="true" data-folder_name="'.$_POST["folder_name"].'"  data-file_name = "'.$file.'" class="change_file_name">'.$file.'</td>
     <td><button name="remove_file" class="remove_file btn btn-danger btn-xs" id="'.$path.'">Remove</button></td>
    </tr>
    ';
   }
  }
  $output .='</table>';
  echo $output;
 }
 
 if($_POST["action"] == "remove_file")
 {
  if(file_exists($_POST["path"]))
  {
   unlink($_POST["path"]);
   echo 'File Deleted';
  }
 }
 
 if($_POST["action"] == "change_file_name")
 {
  $old_name = $_POST["folder_name"] . '/' . $_POST["old_file_name"];
  $new_name = $_POST["folder_name"] . '/' . $_POST["new_file_name"];
  if(rename($old_name, $new_name))
  {
   echo 'File name change successfully';
  }
  else
  {
   echo 'There is an error';
  }
 }
}
?>


upload.php



<?php
if($_FILES["upload_file"]["name"] != '')
{
 $data = explode(".", $_FILES["upload_file"]["name"]);
 $extension = $data[1];
 $allowed_extension = array("jpg", "png", "gif");
 if(in_array($extension, $allowed_extension))
 {
  $new_file_name = rand() . '.' . $extension;
  $path = $_POST["hidden_folder_name"] . '/' . $new_file_name;
  if(move_uploaded_file($_FILES["upload_file"]["tmp_name"], $path))
  {
   echo 'Image Uploaded';
  }
  else
  {
   echo 'There is some error';
  }
 }
 else
 {
  echo 'Invalid Image File';
 }
}
else
{
 echo 'Please Select Image';
}
?>

42 comments:

  1. i encounter something wrong with the upload of the files to the specific folders. i dont know if its me or what but i can copies exactly as you and followed your videos but still i receive the same problem...

    ReplyDelete
  2. What if i want to allow all file extensions?

    ReplyDelete
  3. Hey admin, can you please make a tutorial about 'how to post a comment'. Thank you.

    ReplyDelete
  4. can you provide a database for this ?

    ReplyDelete
  5. how can i create the download link??

    ReplyDelete
  6. Hello ... how can I insert this code in one php file ?
    please need help

    ReplyDelete
  7. How to make the files downloadable

    ReplyDelete
  8. How can I upload file type like pdf and docs? And why I also cannot uploa image

    ReplyDelete
  9. How to remove a folder which has the sub-folders and files inside?

    ReplyDelete
  10. Can help us how to insert images details into database

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This Page is Really really good.
    thank you very much whoever did this.
    Information in this page was very helpful.

    ReplyDelete
  13. great tutorial, how about subfolders?

    ReplyDelete
  14. Very Nice tutorial! Can you add button to copy folders and download files?

    ReplyDelete
  15. Very nice tutorial! If you can, add please copy folder and download file buttons!

    ReplyDelete
  16. This tutorial has solved all my problems. Just one questions is where are the folders created and stored on c drive????

    ReplyDelete
  17. http://raf.webprofis.nl/index.php

    ReplyDelete
  18. This code is for those folders that are in the same directory with php code file , isn't it.. But if i want to do same works in a specific folder with a specific path , then what should i do

    ReplyDelete
  19. This code is for those folders that are in the same directory with php code file , isn't it.. But if i want to do same works in a specific folder with a specific path , then what should i do

    ReplyDelete
  20. i can create folders but not upload files inside, where is the problem?
    thankyou

    ReplyDelete
  21. doesn`t support utf-8 file name ?

    ReplyDelete
  22. Would be nice to place a link on image thum to the file URL

    ReplyDelete
  23. Hi, thanks for the tutorial. Can you please help me on how to identify database?
    Can you please provide the database structure for this tut? Thanks.

    ReplyDelete
  24. Thanks for this tutorial. Can you please provide database structure?

    ReplyDelete
  25. Thanks a lot.. very useful information
    can you please suggest how to "list files based on date of uploading"

    ReplyDelete
  26. how do i view the uploaded files please help me out my email- chimmykk@gmail.com

    ReplyDelete
  27. was wondering how to protect the upload,delete,update with a pass code ?

    ReplyDelete
  28. Epic! wondering how to protect the upload,delete,update button with a password ?

    ReplyDelete
  29. Please, can anybody help me i could not upload, despite the fact that i selected image

    ReplyDelete
  30. Please, help me i could not upload, despite the fact that i selected image, other things are working delete and folder update is working but upload is not working

    ReplyDelete
  31. First of all Thanks for your perfect videos and demos and source codes.
    All of them shows way how to do something to me.

    FOr that video how can I talk to mysql datbase as same way of that video?

    ReplyDelete
  32. I wish to add extra files to be uploaded such as rar/zip and 7zip files. Could someone help me please with the revised piece of code if it is possible please.
    Thanks in advance

    ReplyDelete
  33. how to call the folder name base from a value from database?



    ReplyDelete
  34. Hi! How do I accept other files? Like pdf, doc...
    Thank you.

    ReplyDelete
  35. How to show subfolders of a director?

    ReplyDelete
  36. Hi,

    How to download the files from the folder.

    Thanks

    ReplyDelete