Current Location: Home> Latest Articles> How to Use the ceil() Function to Calculate the Number of Chunks in File Chunked Uploads

How to Use the ceil() Function to Calculate the Number of Chunks in File Chunked Uploads

M66 2025-06-23

When implementing large file uploads, file chunking is a very common technique. It allows splitting a massive file into smaller segments for sequential uploading, improving upload efficiency and success rates, and enabling resume functionality after network interruptions.

In PHP, the ceil() function plays a crucial role in the calculation of chunked uploads. This article will provide a detailed guide on how to use ceil() to calculate the number of chunks required for uploading a file.

1. What is the ceil() Function?

ceil() is a built-in PHP mathematical function that rounds a number up to the nearest integer. In other words, no matter how many decimal places there are, it will round the number to the smallest integer greater than the original number.

echo ceil(2.1); // Outputs 3
echo ceil(5.9); // Outputs 6

2. How to Calculate the Number of Chunks?

Suppose we need to upload a file of size $fileSize bytes, splitting it into chunks of size $chunkSize bytes each. The total number of chunks can be calculated using the following formula:

Number of Chunks = ceil ( File Size / Chunk Size )

This is exactly the scenario where the ceil() function is used.

3. Practical Code Example

Here is a simple PHP code snippet that calculates how many chunks are needed to upload a file:

<?php
$fileSize = 10485760; // File size is 10MB (in bytes)
$chunkSize = 1048576; // Each chunk is 1MB
<p>$totalChunks = ceil($fileSize / $chunkSize);</p>
<p>echo "Total number of chunks to upload: $totalChunks";<br>
?><br>

The output will be:

Total number of chunks to upload: 10

In this case, a 10MB file with 1MB per chunk requires exactly 10 chunks.

4. Chunked Upload Using Frontend and Backend

The frontend, typically using JavaScript, splits the file into chunks of the specified size, uploading one chunk at a time, usually with the following parameters:

  • Index of the current chunk (e.g., chunk 1, chunk 2...)

  • Size of each chunk

  • Unique file identifier (e.g., using md5 or uuid)

The backend (using PHP) receives each chunk and temporarily stores it until all chunks have been uploaded, at which point the chunks are merged to form the complete file.

<?php
$index = $_POST['chunkIndex']; // Current chunk index
$total = $_POST['totalChunks']; // Total number of chunks
$fileId = $_POST['fileId']; // Unique file identifier
$chunk = $_FILES['file']['tmp_name'];
<p>$chunkDir = <strong>DIR</strong> . "/chunks/$fileId";<br>
if (!is_dir($chunkDir)) {<br>
mkdir($chunkDir, 0777, true);<br>
}</p>
<p>move_uploaded_file($chunk, "$chunkDir/chunk_$index");</p>
<p>if ($index == $total - 1) {<br>
// All chunks have been uploaded, start merging<br>
$finalFile = fopen(<strong>DIR</strong> . "/uploads/$fileId", 'ab');<br>
for ($i = 0; $i < $total; $i++) {<br>
$chunkPath = "$chunkDir/chunk_$i";<br>
fwrite($finalFile, file_get_contents($chunkPath));<br>
}<br>
fclose($finalFile);</p>
array_map('unlink', glob("$chunkDir/*"));
rmdir($chunkDir);

echo "File upload and merge successful!";

}
?>

5. Practical Application Suggestions

In actual deployment, you may deploy the upload interface on a separate service domain, such as https://upload.m66.net, to enhance upload speed and prevent heavy resource consumption on the main site.

Example frontend upload request:

fetch('https://upload.m66.net/upload.php', {
    method: 'POST',
    body: formData
});

The backend PHP interface can use the ceil() function to verify if the upload is complete, based on the chunk information. For example:

$expectedChunks = ceil($fileSize / $chunkSize);
if ($uploadedChunks == $expectedChunks) {
    // Merge the file
}

6. Conclusion

Using the ceil() function is an easy and effective way to calculate the number of chunks needed for chunked uploads. By leveraging PHP's built-in functions and file handling capabilities, you can efficiently and robustly manage large file chunked uploads and merging. Whether you're building a file storage system or offering a better upload experience for users, mastering this technique is essential.