Site icon FahmidasClassroom

How to upload folder using HTML and PHP

Upload

File or list of files can be uploaded easily to the server by using HTML form and PHP. But uploading any folder that contains list of files or other folders is a little complicated task. This tutorial will help you to learn the way to upload any folder to the server by using HTML form and PHP.

Steps:

1. Open a new HTML document from any code editor.

2. Create a HTML form with a text files to enter the uploading folder’s name, file field to upload the folder and a submit button to complete the upload task. Add the following HTML code create the form. Here, text field is used to enter the name of the folder that will be used to store the uploading folder content. File field is used to to upload the folder from the client computer. A folder can contain multiple files and folders. So, files[] array is used here as field name for the file field. “multiple” atrribute is used here for uploading multiple content. The uploading task will be worked for Chrome and Mozilla browser only. “webkitdirectory” attribute is used for chrome browser and “mozdirectory” attribute is used for Mozilla browser.

  <html>
  <head>
  <title>Upload Folder using PHP </title>
  </head>
  <body>
  <form action="#" method="post" enctype="multipart/form-data"> 
  Type Folder Name:<input type="text" name="foldername" /><br/><br/>
  Select Folder to Upload: <input type="file" name="files[]" id="files" multiple directory="" webkitdirectory="" moxdirectory="" /><br/><br/> 
  <input type="Submit" value="Upload" name="upload" />
  </form>
  </body>
  </html>

3. Write PHP code to complete the upload task

  <?php
  if(isset($_POST['upload']))
  {
  	if($_POST['foldername'] != "")
  	{
  		$foldername=$_POST['foldername'];
  		if(!is_dir($foldername)) mkdir($foldername);
  		foreach($_FILES['files']['name'] as $i => $name)
		{
  		    if(strlen($_FILES['files']['name'][$i]) > 1)
  		    {  move_uploaded_file($_FILES['files']['tmp_name'][$i],$foldername."/".$name);
  		    }
  		}
  		echo "Folder is successfully uploaded";
  	}
  	else
  	    echo "Upload folder name is empty";
  }
  ?>

4. Before executing the code, open the configuration file, php.ini and change the following configuration.

  max_file_uploads = 100
  post_max_size = 500M
  upload_max_filesize = 500M

5. Save the file and run the file from Chrome or Mozilla browser.

***Note: The above script will upload all the files under the uploading folder and all subfolders. So, if the uploading folder contain any subfolder then subfolder will not be created under the main folder but all files will be uploaded. The issue will be solved in the next tutorial.

You can see the steps of this tutorial from the following video link.

Exit mobile version