PHP Chunk File Upload using JavaScript Example

Mar 24, 2022 . Admin



Hello dev,

I am going to explain you how to PHP chunk file upload using Javascript. You will learn upload files in chunk using PHP and JavaScript. In side this article we will see how to implement chunk upload in PHP.

This article will give you simple example of uploading large files with JavaScript using PHP. We will use get simple how to JavaScript PHP chunk file upload.

I will give you simple Example of how to upload chunks of file via JavaScript and PHP.

So, let's see bellow solution:

index.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PHP Chunk File Upload using Javascript - Mywebtuts.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div id="container" class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card w-75 m-auto">
                    <div class="card-header text-center bg-success text-white">
                        <h4>PHP Chunk File Upload using Javascript - Mywebtuts.com</h4>
                    </div>
                    <div class="card-body">
                        <div id="file-input">
                            <input type="file" class="form-control" id="pickfiles">
                        </div>
                        <div id="file-name"></div>
                        <div class="progress d-none" id="file-progress">
                            <div id="progressBar" class="progress-bar progress-bar-striped" role="progressbar" style="width: 10%" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                    </div>
                </div>
            </div>     
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/plupload/3.1.5/plupload.full.min.js" integrity="sha512-yLlgKhLJjLhTYMuClLJ8GGEzwSCn/uwigfXug5Wf2uU5UdOtA8WRSMJHJcZ+mHgHmNY+lDc/Sfp86IT9hve0Rg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
        window.addEventListener("load", function () {
            var path = "plupload/js/`";
            var uploader = new plupload.Uploader({
                browse_button: 'pickfiles',
                container: document.getElementById('file-input'),
                url: 'upload.php',
                chunk_size: '10kb',
                max_retries: 2,
                filters: {
                    max_file_size: '50mb',
                    mime_types: [{title: "Image", extensions: "jpg,png,jpeg,pneg"}]
                },

                init: {
                    PostInit: function () {
                        document.getElementById('file-name').innerHTML = '';
                    },

                    FilesAdded: function (up, files) {
                        plupload.each(files, function (file) {
                            document.getElementById('file-name').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
                        });
                        uploader.start();
                    },

                    UploadProgress: function (up, file) {
                        $('#file-progress').removeClass('d-none');
                        $('#progressBar').css('width', file.percent+'%');
                        $('#progressBar').html(file.percent+'%');
                        document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                    },

                    FileUploaded: function(up, file, result){
                        setTimeout(function() {
                            $('#file-progress').addClass('d-none');
                        }, 2500);
                    },

                    UploadComplete: function(up, file){
                        console.log("Upload Succefully.");     
                    },

                    Error: function (up, err) {
                        // DO YOUR ERROR HANDLING!
                        console.log(err);
                    }
                }
            });
            uploader.init();
        });
    </script>
</body>
</html>
upload.php
<?php
    // RESPONSE FUNCTION
    function index($ok=1,$info=""){
        // THROW A 400 ERROR ON FAILURE
        if ($ok==0) { http_response_code(400); }
        die(json_encode(["ok"=>$ok, "info"=>$info]));
    }
    
    // INVALID UPLOAD
    if (empty($_FILES) || $_FILES['file']['error']) {
        index(0, "Failed to move uploaded file.");
    }

    // THE UPLOAD DESITINATION - CHANGE THIS TO YOUR OWN
    $filePath = __DIR__ . DIRECTORY_SEPARATOR . "uploads";

    if (!file_exists($filePath)) { 

        if (!mkdir($filePath, 0777, true)) {
            index(0, "Failed to create $filePath");
        }
    }

    $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
    $filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;

    // DEAL WITH CHUNKS
    $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
    $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
    $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");

    if ($out) {
        $in = @fopen($_FILES['file']['tmp_name'], "rb");

        if ($in) {
            while ($buff = fread($in, 4096)) { fwrite($out, $buff); }
        } else {
            index(0, "Failed to open input stream");
        }

        @fclose($in);
        @fclose($out);
        @unlink($_FILES['file']['tmp_name']);

    } else {
        index(0, "Failed to open output stream");
    }

    // CHECK IF FILE HAS BEEN UPLOADED
    if (!$chunks || $chunk == $chunks - 1) {
        rename("{$filePath}.part", $filePath);
    }
    index(1, "Upload OK");
?>
Output:

It will help you...
#PHP