How to upload image using PHP?

Uploading images can be broken down into the three following steps.
  • An HTML form with a browse button to allow the client to choose which file to upload
  • A script to process the upload, validate the file, name it and place it in the file system
  • Lastly, a page to advise the client the upload was a success
Also, we are providing the solution to another most frequently asked question reviewing image before uploading into the folder by javascript.

HTML Code:

<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <style>
            .container{
                position: absolute;
                width: 500px;
                height: 400px;
                top: 30%;
                left: 50%;
                margin: -100px 0 0 -150px;
                background: #80808061;
                color: white;
                border-radius:5px;
            }
            .container-header{
                width: 500px;
                margin-left: -15px;
                height: 40px;
                background: #464646;
                color:white;
                padding:5px;
                font-size:20px;
                text-align:center;
                margin-bottom:40px;
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
            }
            #output{
                width:100px;
                height:auto;
                margin-top:20px;
            }
            .btn{
                margin-top:20px;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <div class="container-header">
                Select image to upload
            </div>
            <form action="upload.php" method="post" enctype="multipart/form-data" id="form1" runat="server">
                <div class="col-md-12">
                    <input type='file' id="imgInp" name="fileToUpload" accept="image/*" onchange="loadFile(event)" class="form-control"/>
                    <img id="output"/>
                </div>
                <div class="col-md-12">
                    <input type="submit" value="Upload Image" name="submit" class="btn">
                </div>
            </form>
        </div>
    </body>
    <script>
        var loadFile = function (event) {
            var reader = new FileReader();
            reader.onload = function () {
                var output = document.getElementById('output');
                output.src = reader.result;
            };
            reader.readAsDataURL(event.target.files[0]);
        };
    </script>
</html>

PHP Code:
upload.php
<?php

$directory = "uploads/";
$target_file = $directory . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image using getimagesize function
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if ($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists by using file name
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
Result:
Note:
To access the file you uploaded, you need to store the path of the file in the database table which is very simple to do with basic knowledge.
$target_file is the path variable, you can store this variable value directly in the database by normal insertion query. 

Also, you need to create uploads folder in the root directory.


Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts