Make Destination Directory on File upload with PHP

You normally store the user selected files in the specific directory but the same directory is also used by all other users.

If you are allowing to upload multiple types of files like – image, videos, doc, etc then it becomes a mess.

To avoid this you can create separate directories for the store in an organized way.

But for storing it in a more organized way you can dynamically create directories for each user for storing their files. This makes traversing to file easier.

Make destination directory on file upload with PHP


  1. Table structure
  2. Configuration
  3. HTML & PHP
  4. Conclusion


1. Table structure

Create users table.

CREATE TABLE `users` (
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL

2. Configuration

Create a config.php for database connection.

Completed Code

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());


Create a new upload directory for storing files.

List records from the users table and add a <form action='multipart/form-data' > following with the username which contains the file element and a submit button.

Create directory and upload

I am using the username for the directory name. For this, I created a hidden element with username value in <form >.

On the form submit select the POST username and with mkdir() method create a directory if it does not exist in the upload directory.

Completed Code

include "config.php";


  # Username
  $username = $_POST['username'];

  # Get file name
  $filename = $_FILES['file']['name'];

  # Get File size
  $filesize = $_FILES['file']['size'];

  # Location
  $location = "upload/".$username;

  # create directory if not exists in upload/ directory
    mkdir($location, 0755);

  $location .= "/".$filename;

  # Upload file



<!doctype html>
 <body >
 <!-- User list -->
 <table border='1'>

   $fetch_user = mysqli_query($con,"select * from users");
   $count = 1;
   while($row = mysqli_fetch_assoc($fetch_user)){
     $username = $row['username'];

    <td><?= $count ?></td>
    <td><?= $username ?></td>
     <!-- Form -->
     <form method='post' action='' enctype='multipart/form-data'>
      <input type='hidden' value='<?= $username ?>' name='username' >
      <input type="file" name="file" id="file" >
      <input type='submit' name='submit' value='Upload'>

4. Conclusion

Using the above script you can create a new directory dynamically while upload file does not exist.

Specify your directory location in mkdir() function for creation.

If you found this tutorial helpful then don't forget to share.
Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *