PHP Large File Upload In Chunks

Files that have to be uploaded can be small or huge – about several gigabytes in size. In such cases standard upload may fail, since browsers still cannot handle it properly. We slice the files in chunks and send them out one by one. You can then safely collect them on the server and combine into original file.

Controller : Upload.php

<?php if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);

class Upload extends CI_Controller {

public function index()

public function uploadtoserver()
// 5 minutes execution time
@set_time_limit(5 * 60);
// Uncomment this one to fake upload time
// usleep(5000);

// Settings

$targetDir = FCPATH . “uploads”;
//$targetDir = ‘uploads’;
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds

// Create target dir
if (!file_exists($targetDir)) {

// Get a file name
if (isset($_REQUEST[“name”])) {
$fileName = $_REQUEST[“name”];
} elseif (!empty($_FILES)) {
$fileName = $_FILES[“file”][“name”];
} else {
$fileName = uniqid(“file_”);

$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

// Chunking might be enabled
$chunk = isset($_REQUEST[“chunk”]) ? intval($_REQUEST[“chunk”]) : 0;
$chunks = isset($_REQUEST[“chunks”]) ? intval($_REQUEST[“chunks”]) : 0;

// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die(‘{“jsonrpc” : “2.0”, “error” : {“code”: 100, “message”: “Failed to open temp directory.”}, “id” : “id”}’);

while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

// If temp file is current file proceed to the next
if ($tmpfilePath == “{$filePath}.part”) {

// Remove temp file if it is older than the max age and is not the current file
if (preg_match(‘/\.part$/’, $file) && (filemtime($tmpfilePath) < time() – $maxFileAge)) {

// Open temp file
if (!$out = @fopen(“{$filePath}.part”, $chunks ? “ab” : “wb”)) {
die(‘{“jsonrpc” : “2.0”, “error” : {“code”: 102, “message”: “Failed to open output stream.”}, “id” : “id”}’);

if (!empty($_FILES)) {
if ($_FILES[“file”][“error”] || !is_uploaded_file($_FILES[“file”][“tmp_name”])) {
die(‘{“jsonrpc” : “2.0”, “error” : {“code”: 103, “message”: “Failed to move uploaded file.”}, “id” : “id”}’);

// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES[“file”][“tmp_name”], “rb”)) {
die(‘{“jsonrpc” : “2.0”, “error” : {“code”: 101, “message”: “Failed to open input stream.”}, “id” : “id”}’);
} else {
if (!$in = @fopen(“php://input”, “rb”)) {
die(‘{“jsonrpc” : “2.0”, “error” : {“code”: 101, “message”: “Failed to open input stream.”}, “id” : “id”}’);

while ($buff = fread($in, 4096)) {
fwrite($out, $buff);


// Check if file has been uploaded
if (!$chunks || $chunk == $chunks – 1) {
// Strip the temp .part suffix off
rename(“{$filePath}.part”, $filePath);

// Return Success JSON-RPC response
die(‘{“jsonrpc” : “2.0”, “result” : null, “id” : “id”}’);


/* End of file upload.php */
/* Location: ./application/controllers/upload.php */

View : Welcome.php


<div id=”container”>
<h1>CodeIgniter Plupload Chunk Uploading</h1>

<div id=”body”>
<p>Upload Big file chunk by chunk using Plupload.</p>

<div id=”filelist”>Your browser doesn’t have Flashs, Silverlight or HTML5 support.</div>
<div id=”container”>
<div class=”form-group”>
<a id=”uploadFile” name=”uploadFile” href=”javascript:;”>Select file</a>

<div class=”form-group”>
<a id=”upload” href=”javascript:;” class=”btn btn-danger”>Upload files</a>
<input type=”hidden” id=”file_ext” name=”file_ext” value=”<?=substr( md5( rand(10,100) ) , 0 ,10 )?>”>
<div id=”console”></div>

<p class=”footer”>Page rendered in <strong>{elapsed_time}</strong> seconds</p>
<script type=”text/javascript”>
BASE_URL = “<?php echo base_url();?>”

<script src=”<?=base_url();?>public/js/plupload/plupload.full.min.js”></script>
<script type=”text/javascript” src=”<?=base_url();?>public/js/application.js”></script>


NOTE : Comment Your Email ID, I Will Send YOU Source Code..

2321total visits,13visits today

One Comment on “PHP Large File Upload In Chunks”

  1. Hello ,

    I saw your tweets and thought I will check your website. Have to say it looks very good!
    I’m also interested in this topic and have recently started my journey as young entrepreneur.

    I’m also looking for the ways on how to promote my website. I have tried AdSense and Facebok Ads, however it is getting very expensive.
    Can you recommend something what works best for you?

    Would appreciate, if you can have a quick look at my website and give me an advice what I should improve:
    (Recently I have added a new page about FutureNet and the way how users can make money on this social networking portal.)

    I wanted to subscribe to your newsletter, but I couldn’t find it. Do you have it?

    Hope to hear from you soon.

    Maybe I will add link to your website on my website and you will add link to my website on your website? It will improve SEO of our websites, right? What do you think?

    Jan Zac

Leave a Reply

Your email address will not be published. Required fields are marked *