How to Implement Chunk Upload in PHP

Recently one of our readers asked about chunk uploading in PHP. They want to upload large files in a fast and reliable way. By implementing chunk uploading you can upload/move large files on a server easily. In this article, I will write a PHP code for chunk uploading which can be useful for uploading/moving large files.

Sometimes in the web application, you need to deal with large files. It may be video or zip files that need to move to a specific location on the server.

It’s very easy to implement chunk upload in PHP. In the code below we are moving the source file inside the ‘uploads’ directory. We read the file in chunks of 256 bytes and write it to the destination file. This process will continue until the script reads all bytes from the source file and write these bytes to the destination file. For this operation, I am using PHP native functions – fopen, fread, fwrite, and fseek.

Let’s say you have a ‘video.mp4’ file that you want to move under the ‘uploads’ folder. Below is the code which moves a file in chunks to the destination folder.

$source = 'video.mp4';
$orig_file_size = filesize($source);
$destination = 'uploads/video.mp4';
$chunk_size = 256; // chunk in bytes
$upload_start = 0;
$handle = fopen($source, "rb");
$fp = fopen($destination, 'w');
while($upload_start < $orig_file_size) {
    $contents = fread($handle, $chunk_size);
    fwrite($fp, $contents);
    $upload_start += strlen($contents);
    fseek($handle, $upload_start);
echo "File uploaded successfully.";

That’s it! It’s that much simple to implement chunk upload in PHP. I would like to hear your thoughts or suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

2 thoughts on “How to Implement Chunk Upload in PHP

Leave a Reply

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