Current Location: Home> Latest Articles> How to check the integrity of uploaded files through md5_file()

How to check the integrity of uploaded files through md5_file()

M66 2025-05-31

File upload is a very common feature in website development, but the question that comes with it is how to ensure the integrity and security of uploaded files. The file may be tampered with during the transfer, or a malicious file has been uploaded. PHP provides a convenient function md5_file() , which can help developers quickly calculate the MD5 verification code of a file, thereby verifying whether the file has been tampered with or corrupted.

What is md5_file()?

md5_file() is a PHP built-in function that directly calculates the MD5 hash value of the specified file and returns a 32-bit string. The MD5 hash value can be used to detect whether the file content is consistent. If there are any changes to the file content, the corresponding MD5 value will be different.

Function prototype:

 string md5_file ( string $filename [, bool $raw_output = false ] )
  • $filename : file path.

  • $raw_output : Whether to return the original binary format, default to false , returns a 32-bit hexadecimal string.

Use scenarios

  1. Verify the integrity of uploaded files <br> When the user uploads the file, the server calculates the MD5 value of the uploaded file and compares it with the MD5 value calculated by the client before uploading to ensure that the file has not been tampered with.

  2. Prevent duplicate uploads <br> Use the MD5 value to determine whether files with the same content already exist in the server to avoid redundant storage.

  3. Safety Testing <br> You can compare the MD5 value of a file with the MD5 value library of known malicious files to filter dangerous files.

Example: Use md5_file() to verify uploading files

Below is a simple file upload example, using md5_file() to verify file integrity.

 <?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload_file'])) {
    $uploadDir = '/var/www/uploads/';
    $uploadedFile = $_FILES['upload_file']['tmp_name'];
    $originalName = $_FILES['upload_file']['name'];

    // Calculate the uploaded file md5 value
    $md5Hash = md5_file($uploadedFile);

    // Here you can send it to the clientmd5value比对,Suppose the client is comingmd5value
    $clientMd5 = $_POST['client_md5'] ?? '';

    if ($clientMd5 && $md5Hash !== $clientMd5) {
        echo "The integrity verification of uploaded file failed,The file may have been tampered with。";
        exit;
    }

    // Prevent duplicate uploads(Simple use in the examplemd5As file name)
    $destination = $uploadDir . $md5Hash;

    if (file_exists($destination)) {
        echo "The file already exists,No need to upload repeatedly。";
    } else {
        if (move_uploaded_file($uploadedFile, $destination)) {
            echo "File upload successfully,MD5value为:$md5Hash";
        } else {
            echo "File upload failed。";
        }
    }
} else {
?>
<form method="post" enctype="multipart/form-data" action="http://m66.net/upload.php">
    Please select a file:<input type="file" name="upload_file" required><br>
    documentMD5Verification code(Optional):<input type="text" name="client_md5"><br>
    <button type="submit">Upload</button>
</form>
<?php
}
?>

illustrate:

  • Front-end users can first use tools to calculate the MD5 of the file and fill in the client_md5 field of the form. The server side will compare the MD5 of the uploaded file with this value.

  • The server side uses the MD5 value of the file as the save name to prevent repeated uploads of files.

  • The move_uploaded_file() function ensures that files are safely moved from temporary directories to target directories.

Further safety advice

  • Restrict file types : Verify file extensions and MIME types before uploading.

  • Limit file size : Prevent excessive server pressure from uploading excessive files.

  • Use HTTPS : Ensure that the file transfer process is not attacked by man-in-the-middle.

  • Regularly update malicious file library : Use file MD5 to compare with known virus databases to filter dangerous files.

  • Avoid direct access to the upload directory : Use secure storage paths and permission controls.