How to upload Image with PHP

In this post, we are going to learn how to upload image with PHP. It completely from scratch, no framework or library. Just an HTML form that enables users to submit an image to the server and a PHP script that handle the image upload.

Read: 3 Useful Tips Running PHP from the Command Line

For the sake of this tutorial, you should create a folder which will serve as a root directory, for me I created a folder called image-uploader.

At the end of this tutorial, our folder will have the following contents:

PHP-image-upload-folder

The first thing we need is to build up a form.

HTML Upload Form

To upload an image with PHP we first need to create an HTML Form that will contain the input file field that the users will interact with.

Create a new index.html file in the root directory and add the below code into it.

<!doctype html>
<head><title>PHP IMAGE UPLOAD</title></head>

<form action="imageUpload.php" method="post" enctype="multipart/form-data">
    <label>Upload an Image:</label>
    <input type="file" name="myImage" 
           id="imageToUpload" 
           accept="image/png, image/jpeg, image/jpg image/gif">
    <button type="submit" name="submit">Upload Image Now</button> 
</form>

In the above code, the user will be presented a form with a single input field and an upload button.

The form tag has three attributes: action, method, and enctype. The action attribute point to the PHP script (imageUpload.php) that will handle the real upload process. Also, the method attribute defines clearly the kind of operation the form will perform, which is a POST action. Lastly, the enctype attribute, which is very important, particularize the kind of contents ( an encoding type) the form submits.

If you’re using terminal, fire up your code like so:

php -a localhost:3001

Locate on the browser and you’ll see a web page similar to this:

PHP-Image-Upload

Note: Your browsers might display the form field and the button in a different way.

PHP Upload Image Script

When the user selects an image and submit, the selected image is sent to the server. The imageUpload.php that we specify in the form action attribute will handle the real upload process.

Before we dive into actual coding, there are a lot of things to consider when handling image file upload. We will consider only a few in the form of questions:

  • In which directory should the image be stored?
  • Can we put files into the directory?
  • What type of image should the user be allowed to upload?
  • Can the user upload more than one image?
  • What is the maximum image size should the server allow?
  • Should the user upload more than one image?
  • What type of browser should the upload support?

The above questions will give us a better understanding of the upload process.

Now, create a file imageUpload.php, in the root directory and add this code:

<?php

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

    // upload an image
    $currentDir = getcwd();
    $uploadDir = "/images/";

    $errors = []; // Store all errors

    $imageExtensions = ["jpg", "jpeg", "png", "gif"];

    $imageName = $_FILES['myImage']['name']; // image name
    $imageSize = $_FILES['myImage']['size']; // image size in bytes
    $imageTmpName = $_FILES['myImage']['tmp_name']; // image temp name on the server
    $imageType = $_FILES['myImage']['type']; // image type
    $imageExtension = strtolower(end(explode( '.' , $imageName))); // get the extension

    $uploadPath = $currentDir . $uploadDir . basename($imageName);

    // check the image extension
    if ( !in_array( $imageExtension, $imageExtensions)) {
        $errors[] = "The image extension is not allowed. Please upload a JPEG, PNG, GIF file";
    }
    // check the image size
    if ( $imageSize > 5000000) {
        $errors[] = "The image is more than 5MB. Please upload an image that is equal or less than 5MB";
    }
    if ( empty($errors)) {
        // if no errors was found
        $uploaded = move_uploaded_file( $imageTmpName, $uploadPath); // upload the file
        
        if ( $uploaded) {
            echo "The image " . basename($imageName) . "has been uploaded";
        }
        else {
            echo "Fail to upload image. Try again or contact the webmaster";
        }
    }
    else {
        foreach( $errors as $error) {
            echo "Something not right: <br>" . $error;
        }
    }
}

?>

Let’s talk about the PHP code above.

  • $currentDir = getcwd(); : This get the current working directory using the getcwd() built-in PHP function.
  • $uploadDir = “/uploads/”; This specify the directory where the image is uploaded.
  • $imageExtensions = [“jpg”, “jpeg”, “png”, “gif”]; This specifies types of images the user is allow to upload.
  • $imageName = $_FILES[‘myImage’][‘name’]; This refers to the actual name of the uploaded image.
  • $imageSize = $_FILES[‘myImage’][‘size’]; This refers to the size of the image.
  • $imageTmpName = $_FILES[‘myImage’][‘tmp_name’]; Get the temporary image that resides in the tmp/ directory of the web server.
  • $imageType = $_FILES[‘myImage’][‘type’];  This refers to the type of image.
  • $imageExtension = strtolower(end(explode( ‘.’ , $imageName))); This grabs the extension of the image and change to lowercase.
  • $uploadPath = $currentDir . $uploadDir . basename($imageName); This is the path where the image will be saved on the server.

Also, in the code above, we set some conditions:

First, we checked to see that the image been uploaded is either JPEG, PNG, or GIF.

// check the image extension
if ( !in_array( $imageExtension, $imageExtensions)) {
    $errors[] = "The image extension is not allowed. Please upload a JPEG, PNG, GIF file";
}

We also checked to see that the image that can be uploaded is not more than 5MB.

// check the image size
if ( $imageSize > 5000000) {
    $errors[] = "The image is more than 5MB. Please upload an image that is equal or less than 5MB";
}

We then checked if the first and second conditions where satisfied,  and if it does, we upload the image to the server, which is $uploaded = move_uploaded_file( $imageTmpName, $uploadPath);

if ( empty($errors)) {
    // if no errors was found
    $uploaded = move_uploaded_file( $imageTmpName, $uploadPath); // upload the file
        
    if ( $uploaded) {
        echo "The image " . basename($imageName) . "has been uploaded";
    }
    else {
        echo "Fail to upload image. Try again or contact the webmaster";
    }
}

Finally, we make sure we print out the errors peradventure our set conditions were not meet e.g the user tries to upload an image more than 2MB.

else {
    foreach( $errors as $error) {
        echo "Something not right: <br>" . $error;
    }
}

You can run your code to see if it working correctly.

PHP Upload Settings

Before closing this post, here are a few things to note:

First, make sure the upload directory uploads/ is writable. You can run the command below on the terminal to make it writable.

chmod 0755 uploads/ 

Your PHP.ini file needs to have the following constants with appropriate values like:

  • max_file_uploads = 20
  • upload_max_size = 5M
  • post_max_size = 8M

Note: You can simply increase those values in case you want users to upload larger files.

Run the code again and your image should upload to the uploads/ directory.

Congratulation, you just successfully know how to upload image with PHP.

Come with me to the next post on how to upload multiple images with PHP.

Leave a Comment

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