Labels

php (34) javascript (30) phpjavascript (29) jquery (23) html (19) 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)

Wednesday, February 28, 2018

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.


5 comments:

  1. Thanks you sharing how to file or img upload in php code. your post is very informative
    https://www.radiustheme.com/downloads/eikra-education-wordpress-theme/

    ReplyDelete
  2. Hi! your blog is very nice. I read it completely with the deep eye. you have really done a great work. please keep it up.You have given such a great information that will be very useful for me.I want to know more information deeply about it. If possible you can share your more blog for us. Thank you for your such a great blog. great content I am also a content writer in best digital marketing company in udaipur which provide all services related to Digital Marketing in last five year we are recommended as a best digital marketing agency in udaipur by our client to other at last i want to express my thought really your blog is knowledge gaining. I really appreciate your blog.

    ReplyDelete
  3. Buy perfect money in India @Rs.70/- per pm Sell @Rs.58/- per pm,CALL 08054019105, Chandigarh, 160017

    --------------------------------------------------------------------------------------------------------------

    Buy/Sell Perfect Money At Reasonable Rates. We Provide Perfect Money At best Rates.
    We also sell buy Perfect Money, neteller and Bitcoin.

    Call us : +91 9517544444

    Gtalk : garrysingh1598

    Web.: www.sellperfectmoney64.com

    ReplyDelete
  4. All Assignment Help review
    A superior all assignment Help reviews offered by this website with the advantage of online support with high proficiency level based on its latest research and information by professional reviews writers. Wide ranges of subjects are covered with separate writers for each subject.

    ReplyDelete
  5. Glance complicated in order to much added in pleasant from you!Lighting Warehouse Sydney

    ReplyDelete

More Posts

FOLLOW