All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

File Upload In PHP Example Code Demo

Last Updated : Mar 11, 2024

File Upload In PHP Example Code Demo

In this tutorial we will show you the solution of file upload in PHP example code demo, you can upload files with various extensions to the server using PHP's file upload function.

HTML forms can be used to allow users to upload files to the server. Unless they are relocated to a designated location for permanent storage, these files are stored in a temporary directory.

However, in order for the PHP file upload to succeed, we must guarantee that some configuration parameters are correct. Lets check out how to upload file in php.

Step By Step Guide On File Upload In PHP Example Code Demo :-

The HTML Form

<!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>
  1. Lets start by creating an HTML form that the user will see when they try to upload a file. Create a folder for this example project, and place the preceding code in the index.html file.
  2. Then, from the location where you created the file, enter your terminal and start the PHP server.

File upload in PHP

<?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";
        }
      }
    }
?>
  1. We'll start taking care of the file upload's backend. Create a new directory called uploads in the same directory. This is where the files will be saved by our script.
  2. Create a file called fileUploadScript.php in the same directory as index.html. It's worth noting that this is the same name as the form's action attribute. Then paste in the code from above.
  3. Also, we validate the file upload in the code above by checking both the file type and size. (Only png and jpeg files under 4MB will be accepted.)
  4. Before we begin uploading files, there are a few last tasks to complete:
  5. Make your uploads/ directory readable by using the command: chmod 0755 uploads/
  6. Make sure your php.ini file is configured correctly to support file uploads (tip: run php --ini to locate your php.ini file) - max_file_uploads = 20 , upload_max_filesize = 2M and post_max_size = 8M
  7. Finally, if you go to localhost:1234, then upload a file, you will see it saved in the uploads folder

Conclusion :-

With the help of a simple example, you learnt everything there is to know about file upload in PHP.

You've also shown how to use PHP to develop client-side and server-side programmes for file upload.

You can now test uploading various files with different file extensions to see how things go.

Also, purposely cause some errors to watch how the error variable retrieves and displays the appropriate error message. I hope this tutorial on file upload in PHP example code demo helps you.

Author Image About Anjali

Experienced Computer Programmer with a broad range of experience in technology. Strengths in application development and Object Oriented architecture design, front end programming, usability and multimedia technology. Expert in coding languages such as C, C++ Java, JavaScript, PHP and more.

Follow Anjali On Linkedin 🡪