Simple File Upload Using PHP, AJAX With jQuery

Following is one the simplest versions of file upload example using PHP, AJAX with jQuery:

So, first thing first, the front-end part, consisting of HTML interface and JavaScript, upload.html:

    <title>Ajax jQuery Image Upload</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        function submitForm() {
            jQuery('#loading').show();
            var fd = new FormData(document.getElementById("fileform"));
            jQuery.ajax({
              url: "upload.php",
              type: "POST",
              data: fd,
              processData: false,  
              contentType: false 
            }).done(function( data ) {
                if(data != 'Invalid File/Size') {
                    jQuery('#output').html('<img src="'+data+'" />');
                    var tmp_arr = jQuery('#fileinput').val().split('\\');
                    jQuery('#filename').val(tmp_arr[2]);
                    jQuery('#filename').show();
                    jQuery('#success').fadeTo( "slow" , 0.5, function() { });
                }
                else {
                    alert(data);
                }
                jQuery('#loading').hide();
            });
            return false;
        }
    </script>

    <h4>Ajax jQuery Image Upload</h4>
    <form method="post" id="fileform" name="fileinfo" >
        <label for="fileinput">
            <span style="cursor: pointer; padding: 2px; border: 1px solid #dddddd; width: auto;">Click to Upload Image</span>
            <input type="file" name="file" id="fileinput" onchange="submitForm();" style="display: none;" />
        </label>
        <span id="loading" style="display: none;">Loading...</span>
        <span id="success" style="display: none;">File Uploaded</span>
        <input id="filename" type="text" style="display: none;" />
    </form><br />
    <div id="output"></div>

The back-end part, consisting of file upload logic in PHP, upload.php:


<?php

$fn = $_FILES["file"]["name"];

if(file_exists('uploads/' . $fn)) {
    unlink('uploads/' . $fn);
}

$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $fn));

if (
    (
           ($_FILES["file"]["type"] == "image/gif")
        || ($_FILES["file"]["type"] == "image/jpeg")
        || ($_FILES["file"]["type"] == "image/jpg")
        || ($_FILES["file"]["type"] == "image/pjpeg")
        || ($_FILES["file"]["type"] == "image/x-png")
        || ($_FILES["file"]["type"] == "image/png")
    )
    && ($_FILES["file"]["size"] < 50000000)
    && in_array($extension, $allowedExts)
    && (!$_FILES["file"]["error"] > 0)
) {
    if(move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $fn)) {
        echo "uploads/" . $fn;
    }
} 
else {
    echo "Invalid File/Size";
}
?>

That’s it!

To download the above code click on the following link:

Download

Notes:

The code allows a maximum upload file size of about 50 mega-bytes. Based on your requirement you may change the number in the back-end code. Also, you may change the validation of file type to be uploaded.

By default the back-end code is uploading the files to the directory named “uploads”. Please make sure that there is a directory named “uploads” with sufficient privileges. Also you may use your preferred versions of icons for upload, loading and success.