It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

How to upload images and files using php

By zooboole

Hi, welcome to this new tutorial on how to upload images and files using php. For very long time, this topic has been treated by many and up to now it remains a big mystery for beginners. I intend in this tutorial to give you some clear steps and keys that can help you in understanding how that can be done in the simplest way.

For better understanding, I suggest you read deeply about Global variables and PHP arrays. This two elements are key for such systems.

Now, if you feel this tutorial as outdated, I believe you may be a guru in PHP. Please I invite you to help others to understand it better by contributing with your comments.

How does it work?

Sometimes, while developing a website you may face a situation whereby you have to allow your users to upload images (like their profile avatar, email attachment) or document files (like pdf, docs, etc).

Since we are dealing with PHP, the first option one could think of is using HTML forms to allow the user input that information. Unlikely, PHP doesn't process files the same way it does with text fields. So, getting pictures and files from our users' computer require some special work.

Basically, we'll create an HTML form, with that form we'll ask the user to choose a file from his local disk. Our application will then analyze it and save/display it if everything went as expected.

How to do it?

Create a folder that will host our project and name it upload. Create in the folder a file and name it index.html with the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Files upload</title>

    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class="container">
        <div class="form">

            <form name="uploader" action="process.php" method="POST" enctype="multipart/form-data">

                <input type="file" name="file">

                <button type="submit">Upload</button>
            </form>

        </div>
    </div>
</body>
</html>

This code has a basic HTML page structure. I've included a simple css file in it, and the file is named style.css. This is just to give a bit of beauty to the page.

Important thing to keep in mind

The opening <form> tag has an attribute enctype with a value of multipart/form-data. This must be there otherwise the form will not consider the upload of files.

Next, let's create our PHP processing file. This file will be in charge of checking weither the user uploaded a correct file, the size, type, etc of the file.

So, go ahead and create the file process.php in the same folder and put the following code in it:

<?php

var_dump($_FILES);

After that go to the index page and try to upload a file with your form and click upload. If everything goes fine you should see something similar to this:

array (size=1)
  'file' => 
    array (size=5)
      'name' => string 'watch-dm.jpg' (length=12)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string 'C:\wamp\tmp\phpC979.tmp' (length=23)
      'error' => int 0
      'size' => int 87541

This is an array that gives all information PHP can see on the image. So this information will help us process the image. For example you can see the size of the image (int 87541).

Now, let's go back in our process.php and try to handle the file. Here I am going to move the file from the user's computer to a folder named downloads located at the root folder of our project (upload/uploads).

Remove the var_dump() function from process.php and put in the following code:

<?php

$file_max_weight = 20000; //limit the maximum size of file allowed (20Mb)

$ok_ext = array('jpg','png','gif','jpeg'); // allow only these types of files

$destination = 'uploads/'; // where our files will be stored

// PHP sets a global variable $_FILES['file'] which containes all information on the file
// The $_FILES['file'] is also an array, so to have the file name we're supposed to write $_FILES['file']['name']
// To shorten that I added the following line. With that I could just do $file['name']
$file = $_FILES['file'];

$filename = explode(".", $file["name"]); 

$file_name = $file['name']; // file original name

$file_name_no_ext = isset($filename[0]) ? $filename[0] : null; // File name without the extension

$file_extension = $filename[count($filename)-1];

$file_weight = $file['size'];

$file_type = $file['type'];

// If there is no error
if( $file['error'] == 0 )
{
    // check if the extension is accepted
    if( in_array($file_extension, $ok_ext)):

        // check if the size is not beyond expected size
        if( $file_weight <= $file_max_weight ):

                // rename the file
                $fileNewName = md5( $file_name_no_ext[0].microtime() ).'.'.$file_extension ;

                // and move it to the destination folder
                if( move_uploaded_file($file['tmp_name'], $destination.$fileNewName) ):

                    echo" File uploaded !";

                else:

                    echo "can't upload file.";

                endif;

        else:

           echo "File too heavy.";

        endif;

    else:

        echo "File type is not supported.";

    endif;
}

don't forget to create the folder uploads in your root folder.

So that's it. If you have any question or you need more options let me know. You can download my source code here to compare it with yours

Last updated 2021-05-14 UTC