Introduction

PHP is widely used in developing server-side applications. On a dynamic website, uploading files to keep it updated is a routine. And PHP efficiently handles this process. You can use PHP to handle the uploading of multiple files to the server and display them on a dynamic website. 

PHP is used with almost all popular database software. MySQL is one of the most popular databases used in PHP applications. There are many other databases such as PostgreSQL, SYBASE, Oracle Database, and so on that can easily connect with your PHP applications. 

An image can be uploaded and displayed on your PHP website in multiple ways. The most common method of achieving this is by uploading the image into the server’s directory and updating its name in the database. This method is efficient because in this case, the image won’t take any space inside the database, and this will also make your webpage load faster. Another way is by inserting the image into the database directly, instead of uploading it into the server. This method is not recommended because the images take up a lot of space in the database, thereby increasing its size. This will also slow down the loading of your web pages. 

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

In this article, you will look into an efficient method to achieve image upload in PHP, by uploading the image file into a server directory and simply inserting the file name in a database. The file name is used to retrieve the desired file later on, and display it on your website. You will use a MySQL database to demonstrate image upload in PHP.

The following steps need to be followed to upload an image and display it on a website using PHP:

  1. Create a form using HTML for uploading the image files.
  2. Connect with the database to insert the image file.

Program to Achieve the Task

Step 1: Create a Form Using HTML for Uploading the Image Files.

The following HTML code will create a simple form on your website, with a “choose file” option and a button to upload the chosen file.

<!DOCTYPE html>

<html>

<head>

    <title>Image Upload in PHP</title>

    <! link the css file to style the form >

    <link rel="stylesheet" type="text/css" href="style.css" />

</head>

<body>

    <div id="wrapper">

        <! specify the encoding type of the form using the 

                enctype attribute >

        <form method="POST" action="" enctype="multipart/form-data">        

            <input type="file" name="choosefile" value="" />

            <div>

                <button type="submit" name="uploadfile">

                UPLOAD

                </button>

            </div>

        </form>

    </div>

</body>

</html>

The following CSS code is for giving a basic styling to the HTML form.

#wrapper{

    width: 50%;

    margin: 20px auto;

    border: 2px solid #dad7d7;

}

form{

    width: 50%;

    margin: 20px auto;

}

form div{

    margin-top: 5px;

}

img{

    float: left;

    margin: 5px;

    width: 280px;

    height: 120px;

}

#img_div{

    width: 70%;

    padding: 5px;

    margin: 15px auto;

    border: 1px solid #dad7d7;

}

#img_div:after{

    content: "";

    display: block;

    clear: both;

}

Step 2: Connect With the Database to Insert the Image File.

The following PHP code will connect the database to insert the submitted data into the database.

<?php

error_reporting(0);

?>

<?php

$msg = ""; 

// check if the user has clicked the button "UPLOAD" 

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

    $filename = $_FILES["choosefile"]["name"];

    $tempname = $_FILES["choosefile"]["tmp_name"];  

        $folder = "image/".$filename;   

    // connect with the database

    $db = mysqli_connect("localhost", "root", "", "Image_Upload"); 

        // query to insert the submitted data

        $sql = "INSERT INTO image (filename) VALUES ('$filename')";

        // function to execute above query

        mysqli_query($db, $sql);       

        // Add the image to the "image" folder"

        if (move_uploaded_file($tempname, $folder)) {

            $msg = "Image uploaded successfully";

        }else{

            $msg = "Failed to upload image";

    }

}

$result = mysqli_query($db, "SELECT * FROM image");

?>

Program Explanation

HTML Program

The above HTML program creates a simple HTML form having an option to choose a file from your system to upload, and an “UPLOAD” button. It will upload the image file using the POST method.

enctype attribute: This attribute is used to specify the encoding format, in which the data submitted in the form has to be encoded before sending it to the server. This attribute is very important and without specifying this, the image will not be uploaded to the server.

Syntax

enctype="multipart/form-data"

PHP Program

First, you need to create a database using the XAMPP/WAMP server. Here, you have to create a database and name it “Image_Upload”. Next, you need to create a new table in the database. You have created a new table named “Image”. Create two fields in the table:

  • Id – int(11)
  • Filename – varchar(100)

The PHP program discussed earlier will first connect to the database using the mysqli_connect() method. The data submitted using the POST method in the HTML form is stored in a variable $filename. To insert the data into the database, you have to apply an SQL query. The mysqli_query() method executes the SQL query and finally stores the submitted data into the database.

PHP Methods Used in the Program

  • isset 

The isset method is an essential built-in PHP method. This method is used to find if it set a variable or not. A variable is said to be a set variable if it holds a value other than NULL. In other words, the isset method is used to determine if a variable has been declared and has a non-null value or not. It has a boolean return type. If it finds the variable to be set, this method will return true, otherwise, it will return false.

This method proves to be more useful in longer codes. In small pieces of code, you can easily track what and how many variables have been declared. But in the case of longer programs, you might face the problem of losing the track of variables. In such cases, the isset method is very helpful.  You can pass the name of the variable that you want to check.

The syntax for checking the status of a variable using the isset method:

isset ( mixed $var1 , mixed $var2,  ...$vars )

This method accepts mixed parameters. Mixed variables mean that you can pass one or more variables of different data types to isset in PHP as parameters.

  • $_POST

$_POST is a global method in PHP that is used to send user data submitted into an HTML form from the browser to the webserver. The data is first encoded and then transferred to the server via the QUERY_STRING HTTP header. Being a superglobal method, you can use anywhere it in the entire program. The isset method can also be used with the $_POST method to check whether the user has submitted a value or not. 

The data sent using the $_POST method can be of any size. Also, this method is secure since, unlike the $_GET method, the data is invisible and cannot be accessed by anyone from the URL. This method accepts an array as its parameter and supports multiple data types like string, integer, and binary. 

  • mysqli_connect

This method is used to connect a PHP application to the web server by establishing a secure connection between them. Another method called mysql_connect also does the same task, but mysqli_connect is more secure and the “i” here represents an improved version. 

The syntax to establish a new connection using the mysqli_connect method:

mysqli_connect ( "host","username","password","database_name" )

This method accepts 4 parameters:

host: This is an optional parameter. If you are on a local server, then pass NULL or the keyword “localhost” to specify that the connection has to be made with the local webserver.

username: This parameter is used to specify the username of MySQL. This is also an optional parameter. If you are on a local server, then the username will be “root”.

password: This parameter is used to specify the password of the user in MySQL. You can skip this parameter as it is an optional parameter.

name_of_database: This parameter is the name of the database you want to establish the connection with. It will perform all the queries on this specified database. This parameter is also optional.

  • mysqli_query

This method is used to execute the query that is passed as a parameter to it. The queries insert, select, update, and delete can be executed using the mysqli_query method. If the queries are successfully executed, then this method will return an object or a boolean value TRUE, depending upon the type of query executed.

The syntax to execute a MySQL query using the mysqli_query method in PHP:

mysqli_query($connection, query, mode)

This method accepts 3 parameters:

connection: This is a mandatory parameter, and it represents the object of the server with which the connection is established.

query: This parameter is also mandatory, and it represents the SQL query string that needs to be executed.

mode: This is an optional parameter. It represents the mode of the result. It is a constant and is used to store the return value of the method.

  • move_uploaded_file

This method is used to move a specified file (that has already been uploaded) to a new location. This method first validates the specified file, and if it is valid, then moves it to the destination location. If there is already a file in the destination location, then it is overwritten by the new file.

The syntax to move a file to a specific location using the move_uploaded_file method:

move_uploaded_file(file_name, destination_path)

This method accepts 2 parameters:

  • file_name: This parameter is a string that represents the name of the file to be moved to a new location.
  • destination_path: This is a string specifying the destination location where the file needs to be moved.

Add Another Star to Your Performance Evaluation

Learn from industry experts for FREEStart Learning
Add Another Star to Your Performance Evaluation

Final Code Combining the PHP, CSS, and HTML

Following is the combined program that illustrates how to achieve image upload in PHP. 

<?php

error_reporting(0);

?>

<?php

$msg = "";

// check if the user has clicked the button "UPLOAD" 

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

    $filename = $_FILES["choosefile"]["name"];

    $tempname = $_FILES["choosefile"]["tmp_name"];  

        $folder = "image/".$filename;

      // connect with the database

    $db = mysqli_connect("localhost", "root", "", "Image_upload");

        // query to insert the submitted data

        $sql = "INSERT INTO image (filename) VALUES ('$filename')";

     // function to execute above query

        mysqli_query($db, $sql);       

        // Add the image to the "image" folder"

        if (move_uploaded_file($tempname, $folder)) {

            $msg = "Image uploaded successfully";

        }else{

            $msg = "Failed to upload image";

    }

}

$result = mysqli_query($db, "SELECT * FROM image");

?> 

<!DOCTYPE html>

<html> 

<!DOCTYPE html>

<html>

 <head>

    <title>Image Upload in PHP</title>

    <! link the css file to style the form >

    <link rel="stylesheet" type="text/css" href="style.css" />

  <style type="text/css">

        #wrapper{

            width: 50%;

            margin: 20px auto;

            border: 2px solid #dad7d7;

        }

        form{

            width: 50%;

            margin: 20px auto;

        }

        form div{

            margin-top: 5px;

        }

        img{

            float: left;

            margin: 5px;

            width: 280px;

            height: 120px;

        }

        #img_div{

            width: 70%;

            padding: 5px;

            margin: 15px auto;

            border: 1px solid #dad7d7;

        }

        #img_div:after{

            content: "";

            display: block;

            clear: both;

        }

    </style>

</head>

 <body>

    <div id="wrapper">

         <! specify the encoding type of the form using the 

                enctype attribute >

         <form method="POST" action="" enctype="multipart/form-data">

                  <input type="file" name="choosefile" value="" />

            <div>

                <button type="submit" name="uploadfile">WAMP or XAMPP server

                UPLOAD

                </button>

            </div>

        </form>

    </div>

</body>

</html>

Output

  • New Database Using phpMyAdmin.

Database name: Image_Upload

Table name: Image

Image_Upload_PHP_1 

  • HTML Form.

Image_Upload_PHP_2.

Steps to Exceed the Size of Image Upload

The program depicted above can upload a file of up to 2MB in size. This is the default file size in PHP. This size limit can be updated and exceeded according to your choice. To increase the size limit for file upload, follow the steps discussed below:

  • Go to the C drive and open the folder named WAMP or XAMPP server.
  • Click on “bin” to open this folder.
  • Open the folder named as the PHP version (the version which you are using).
  • In this folder, search and go to “php.ini”.
  • Now search for the variables:
    •  upload_max_size = 100M
    • post_max_filesize = 100M
  • Update the new values of these variables and save them.
  • Now go to this path: “C:\wamp64\bin\apache\apache2.4.27\bin”.
  • Search and go to “php.ini” and make the same changes.
  • Save the changes.
  • Finally, restart your WAMP or XAMPP server.
  • Run your code on the server.
Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Wrapping Up!

In this article, you learned how to upload an image in PHP. This article also explored the different ways to upload a file using PHP. You saw the methods used for image upload in PHP in-depth. You then looked at the steps to increase the limit of the file size to be uploaded in PHP. Additionally, you also explored in detail the required codes and combined them to get the desired result.

To get started with PHP, you can refer to this video. You can also learn how to build dynamic applications using PHP with the help of an all-inclusive PHP training course. This course will allow you to get a strong grip on PHP, MySQL, Laravel 4, and other trending topics.

Don’t just stop here. To learn Full-stack Development and to give yourself a chance to work for top tech giants, check out our course on Full Stack Web Development. In this course, you will learn the complete end-to-end technologies/skills that will help you to set your foot into professional web development. These include Java, DevOps, Agility, HTML, AWS, etc.

Check out the complete list of free online courses by Simplilearn.

If you have any questions for us, please mention them in the comments section and our experts will answer them for you.

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.