How to Make a File Uploader with PHP

dark mural on a laptop that displays codes on how to make a file uploader with PHP

Most developers use PHP nowadays to specifically create a file uploader for their web or mobile applications. PHP file uploader, for instance, is one of the most effective methods of uploading files. Developers should know how to make a file uploader with PHP in order to have a better file upload feature.

Having this knowledge, as a result, lands you miles ahead of your colleagues. We need to know some basics before learning how to create a PHP file uploader.

What Is PHP?

PHP, otherwise known as Hypertext Preprocessor, is an open-source framework. Most developers use PHP because of its free server scripting language. PHP is a programming language that even newbies can learn because of its superb support and available documentation. Also, WordPress users can use PHP to customize their site.

What Are The Uses Of PHP?

Similarly, PHP, like any other framework, is essential to developers. For example, PHP is flexible and straightforward, allowing beginners to use it easily. Other uses of PHP include:

  • It can do system functions
    • Creating, opening, writing, reading, and opening files
  • It can control forms
    • Gathering and saving data from files
  • PHP can help add, remove, and change elements in your database
  • PHP helps you to specifically limit users to gaining entry to some pages on your website
  • Finally, because of its security, it can encrypt the stored data

Since we know the uses of PHP, we can now proceed with how to create a file uploader PHP.

How To Make A File Uploader With PHP?

Developers can use Filestack to create a better file uploader using PHP. To start with, we will be considering three steps, for example.

  • Creating An HTML Form

Firstly, you will need to create an HTML form for users to view in case they want to upload their files. Similarly, create a folder for the project and an index.html with the codes, for instance:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>PHP File Upload</title>

</head>

<body>

    <form action="fileUploadScript.php" method="post" enctype="multipart/form-data">

        Upload a File:

        <input type="file" name="the_file" id="fileToUpload">

        <input type="submit" name="submit" value="Start Upload">

    </form>

</body>

</html>

The result of the code will surely create the HTML form. Before going to the next step, we need to note a few things about the code functions in particular, and they are:

  1. action=“fileUploadScript.php”

This code tag acknowledges the PHP script responsible for handling file upload on the backend.

  1. method=“post”

This function lets the browser know which form to use while sending the file to the server.

  1. enctype=“multipart/form-data”

Finally, this function decides the type of content the form can submit.

After knowing those code functions, we can go further to the next step for the file uploader. Ensure you open your terminal and start your server from the directory. Write the following codes, for example:

PHP-file-upload

Furthermore, go to your web browser and open to localhost: 1234. In the case it shows the above code, then you have successfully started the server.

  • Give The Form A Better Look

Secondly, style the form to make it more suited for user interaction. Most developers often neglect this path because they feel it is not worth the stress. Doing this styling for your file uploader with PHP and CSS will make your user interface more appealing to users. You can write the following codes, for example:

div.upload-wrapper {

  color: white;

  font-weight: bold;

  display: flex;

}

 

input[type="file"] {

  position: absolute;

  left: -9999px;

}

 

input[type="submit"] {

  border: 3px solid #555;

  color: white;

  background: #666;

  margin: 10px 0;

  border-radius: 5px;

  font-weight: bold;

  padding: 5px 20px;

  cursor: pointer;

}

 

input[type="submit"]:hover {

  background: #555;

}

 

label[for="file-upload"] {

  padding: 0.7rem;

  display: inline-block;

  background: #fa5200;

  cursor: pointer;

  border: 3px solid #ca3103;

  border-radius: 0 5px 5px 0;

  border-left: 0;

}

 

label[for="file-upload"]:hover {

  background: #ca3103;

}

 

span.file-name {

  padding: 0.7rem 3rem 0.7rem 0.7rem;

  white-space: nowrap;

  overflow: hidden;

  background: #ffb543;

  color: black;

  border: 3px solid #f0980f;

  border-radius: 5px 0 0 5px;

  border-right: 0;

}

The result of these codes will surely give your form a better look.

  • File Uploader PHP

This step is for you to handle the file upload backend. Firstly, create a directory with the name uploads so you can save files. Secondly, create another file with the name fileUploadScript.php in the directory index.html. After doing that, write the following codes; for instance:

<?php

    $currentDirectory = getcwd();

    $uploadDirectory = "/uploads/";

 

$errors = []; // Store errors here

 

  $fileExtensionsAllowed = ['jpeg','jpg','png']; // These will be the only file extensions allowed

 

$fileName = $_FILES['the_file']['name'];

    $fileSize = $_FILES['the_file']['size'];

    $fileTmpName  = $_FILES['the_file']['tmp_name'];

    $fileType = $_FILES['the_file']['type'];

    $fileExtension = strtolower(end(explode('.',$fileName)));

 

    $uploadPath = $currentDirectory . $uploadDirectory . basename($fileName);

 

    if (isset($_POST['submit'])) {

 

     if (! in_array($fileExtension,$fileExtensionsAllowed)) {

        $errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";

      }

 

     if ($fileSize > 4000000) {

        $errors[] = "File exceeds maximum size (4MB)";

      }

 

     if (empty($errors)) {

        $didUpload = move_uploaded_file($fileTmpName, $uploadPath);

 

       if ($didUpload) {

          echo "The file " . basename($fileName) . " has been uploaded";

        } else {

          echo "An error occurred. Please contact the administrator.";

        }

      } else {

        foreach ($errors as $error) {

          echo $error . "These are the errors" . "\n";

        }

      }

 

    }

?>

Consequently, before you start uploading files, write the following code, to ensure your uploads directory is writable:

chmod 0755 uploads/

Then thoroughly check your php.ini to see if the file is suitable for handling files by running this command:

PHP -ini

In conclusion, begin the PHP server and open it to localhost:1234 to then upload the file. Once the uploads folder shows the saved file, you have successfully created a file uploader PHP.

How To Make A Multiple File Uploader With PHP?

You should know that you can create multiple file uploaders with PHP while using a single element. Developers can specifically design your single file uploader PHP code and allow the file element to select multiple times. You can take the following steps to create multiple files uploader.

  • Ensure You Create An HTML Form

Firstly, allow multiple files uploads in <form> and write the following codes, for example:

<form method='post' action='' enctype='multipart/form-data'>

 

 <input type="file" name="file[]" id="file" multiple>

 <input type='submit' name='submit' value='Upload'>

 

</form>

As a result of the codes, you will be able to create the HTML form successfully.

  • Select Files On The Basis

Next, count all picked files and twist them over the whole files for the purpose of selecting files on an index basis. Write the following codes, for example, to carry that out:

<?php 

if(isset($_POST['submit'])){

 // Count total files

 $countfiles = count($_FILES['file']['name']);

 // Looping all files

 for($i=0;$i<$countfiles;$i++){

   $filename = $_FILES['file']['name'][$i];

 

 // Upload file

 

move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);

 

 }

} 

?>

Thus, the result of the codes will show that you have successfully created a multiple files uploader for your PHP.

Ready to start with a better way to upload files in PHP?

Are you tired of constantly creating a failed file uploader with PHP? Do you want to make some head-start in a similar vein? You can head on to Filestack to get started and furthermore, create a better file uploader.

 

Read More →

Ready to get started?

Create an account now!