ENGINEERING JOURNAL

Verifying File Uploads with SHA-256 Checksums in Laravel

Verify file uploads with SHA-256 checksums in Laravel: hash on the client, hash again on the server, and reject truncated uploads before they are stored.

THE ARTICLE 01 — 03

A file upload can fail in a way nobody notices. The request returns 200, the file lands on disk, and the record is created. Weeks later someone opens the file and finds a truncated PDF or a corrupted image. The upload did not fail loudly. It failed halfway through and nobody checked.

A SHA-256 checksum fixes that. The client hashes the file before sending it, the server hashes the file after receiving it, and the two values must match. If they do not, the upload is rejected before anything is stored. This is a small amount of code for a real guarantee: what you stored is byte for byte what the user sent.

Why a checksum check is worth adding

Uploads break in quiet ways. A mobile connection drops mid-transfer and the client retries with a partial body. A proxy truncates a large file. A disk write is interrupted. In each case the framework happily stores whatever bytes arrived, because it has no way to know the file is incomplete.

Size checks do not catch this. A truncated file is still a file, just a shorter one. Extension and MIME checks do not catch it either; a truncated PDF still looks like a PDF until a reader tries to parse it. A checksum is the only check that compares the content itself against what was sent.

The flow: hash on both ends, compare in the middle

The flow has three steps. First, the client computes the SHA-256 hash of the file before uploading. Second, it sends the file and the hash together, usually as a form field alongside the file. Third, the server hashes the received file and compares the two values with a timing-safe comparison. A mismatch means the upload is rejected and the stored file is deleted.

On the client side, the browser can hash a file with the Web Crypto API before it is sent:

async function sha256(file) {
    const buffer = await file.arrayBuffer();
    const digest = await crypto.subtle.digest('SHA-256', buffer);
    return [...new Uint8Array(digest)]
        .map((b) => b.toString(16).padStart(2, '0'))
        .join('');
}

const checksum = await sha256(fileInput.files[0]);

const form = new FormData();
form.append('document', fileInput.files[0]);
form.append('checksum', checksum);
await fetch('/api/documents', { method: 'POST', body: form });

Nothing here depends on a framework. Any client that can hash a file can take part, and the server does not care which one it is.

Verifying the checksum in Laravel

On the server, the validation step should require the checksum field and constrain its shape. A SHA-256 hex digest is exactly 64 lowercase hex characters, so the rule can enforce that:

$validated = $request->validate([
    'document' => ['required', 'file', 'max:10240', 'mimes:pdf,jpg,jpeg,png'],
    'checksum' => ['required', 'string', 'size:64', 'regex:/^[a-f0-9]{64}$/i'],
]);

Then hash the uploaded file and compare. PHP has a built-in function for this, hash_file, which hashes a file on disk without loading it fully into memory:

$file = $request->file('document');
$actual = hash_file('sha256', $file->getRealPath());

if (! hash_equals(strtolower($validated['checksum']), $actual)) {
    return response()->json([
        'message' => 'Upload failed checksum verification.',
    ], 422);
}

Use hash_equals instead of ==. It compares the two strings in constant time, which is the correct habit for comparing anything secret or integrity related. Compare case-insensitively by lowercasing the client value first, since some clients send uppercase hex.

Only after the check passes should the file be stored and the record created. If the check fails, do not store the file at all. Returning a 422 tells the client the upload was rejected for a reason it can fix by retrying, rather than a server error it cannot act on.

Storing the checksum with the file record

The checksum is worth keeping, not just checking once. Store it on the same record as the file path so the file can be re-verified later, long after the upload request is gone:

Schema::table('documents', function (Blueprint $table) {
    $table->string('sha256', 64)->nullable()->after('path');
});
$path = $file->store('documents', 'private');

$document = Document::create([
    'organization_id' => $request->user()->organization_id,
    'original_name' => $file->getClientOriginalName(),
    'path' => $path,
    'size' => $file->getSize(),
    'sha256' => $actual,
]);

Storing the original name, size, and checksum together gives you a complete record of what was received. When a user later reports that a file will not open, the first thing to check is whether the file on disk still hashes to the stored value. That one check separates "the upload was bad" from "something changed the file after upload".

Re-verifying files later with a scheduled check

A checksum stored at upload time is also useful as an ongoing integrity check. A small scheduled command can re-hash stored files and report any that no longer match:

foreach (Document::cursor() as $document) {
    $diskPath = Storage::disk('private')->path($document->path);

    if (! file_exists($diskPath)) {
        $this->warn("Missing file: {$document->id}");
        continue;
    }

    $current = hash_file('sha256', $diskPath);

    if (! hash_equals($document->sha256, $current)) {
        $this->error("Checksum mismatch: {$document->id}");
    }
}

Run this daily or weekly depending on how much the files matter. For evidence files, invoices, or signed documents, a mismatch is an incident worth investigating, not a warning to ignore. This is the same instinct as triaging a production incident: the first question is always what changed, and a checksum gives you a definite answer.

What a checksum does not protect against

A checksum proves the bytes arrived intact. It does not prove the bytes are safe. A file can hash perfectly and still be malware, a script disguised as an image, or a document with a spoofed extension. Keep the other checks in place: validate the MIME type from the file contents, not the extension; store uploads outside the public web root; serve them through a controller that checks authorization; and run a malware scan if the files come from untrusted users.

It also does not prove the file came from the person who claims to have sent it. That is an authentication question, answered by the auth layer, not by a hash. Treat the checksum as one layer: it guarantees integrity in transit and at rest, and the other layers handle identity and safety.

Takeaway

Checksum verification is a small addition with a clear payoff. Hash the file on the client, hash it again on the server, compare with hash_equals, store the value, and re-check it on a schedule. The next time an upload is silently truncated, the request fails loudly at the door instead of becoming a corrupted file someone discovers weeks later.

Muhammad Aqib ← ALL ARTICLES
KEEP EXPLORING

More ideas.
Better engineering.

Explore the journal ↗