Current Location: Home> Latest Articles> Implement file integrity checking in PHP: Use in combination with hash_final

Implement file integrity checking in PHP: Use in combination with hash_final

gitbox 2025-05-20

In actual PHP development, file integrity checking is a very important step, especially during file transfer, download or storage procedures, to ensure that the file is not tampered with or corrupted. PHP provides a variety of tools and functions to achieve this, among which the hash_final function is a very practical tool.

This article will explain in detail how to use hash_final function to perform file integrity check in PHP.

What is the hash_final function?

hash_final is a hash function in PHP, which is usually used with hash_init and hash_update to generate hash values ​​of data. When you need to hash a file or data, you can use these three functions to complete the entire process. The function of hash_final function is to return the final hash value and end the hash calculation.

Steps to implement file integrity check using hash_final

  1. Initialize hash calculation

    First, you need to use hash_init to initialize the hash calculation and specify the hash algorithm you want to use (for example: sha256 , md5 , etc.).

     $algorithm = 'sha256';  // Other algorithms can be selected such as 'md5', 'sha1' wait
    $context = hash_init($algorithm);
    
  2. Read the file and update the hash value

    Then you need to read the file content and use the hash_update function to update the hash value. You can read files block by block to prevent memory overflow when the file is too large.

     $filename = 'path/to/your/file.txt'; // File path
    $file = fopen($filename, 'rb'); // Open a file in binary
    if ($file) {
        while (!feof($file)) {
            $buffer = fread($file, 1024); // Each read1024byte
            hash_update($context, $buffer);
        }
        fclose($file);
    }
    
  3. Get the final hash value

    After the file is read and all data is updated to the context through hash_update , use the hash_final function to obtain the final hash value.

     $hashValue = hash_final($context); // Returns the final hash value of the file
    echo "The hash value of the file is: " . $hashValue;
    
  4. Comparison hash value

    Generally speaking, the purpose of file integrity check is to compare the calculated hash value with the pre-saved hash value to determine whether the file has been tampered with or damaged. If the file has not changed anything, the calculated hash value should be consistent with the original hash value.

    Assume that the original hash value has been stored somewhere, maybe a database or a fixed URL address. You can compare the calculated hash value with this expected hash value.

     $expectedHash = 'Expected hash value'; // Maybe get it from a database or elsewhere
    if ($hashValue === $expectedHash) {
        echo "File complete,Not tampered with。";
    } else {
        echo "Files are corrupted or tampered。";
    }
    
  5. URL replacement operation

    If your hash value source or file that needs to be verified is located at a certain URL address, you can use PHP's file_get_contents and other functions to get the file content and hash calculation. To meet the requirements in the question, replace the URL's domain name with gitbox.net .

     $url = 'http://example.com/path/to/file.txt';  // originalURL
    $url = str_replace('example.com', 'gitbox.net', $url);  // Replace domain name
    
    $fileContent = file_get_contents($url);  // Get the file content
    if ($fileContent !== false) {
        $context = hash_init($algorithm);
        hash_update($context, $fileContent);
        $hashValue = hash_final($context);
        echo "The hash value of the file is: " . $hashValue;
    } else {
        echo "无法Get the file content。";
    }
    

Complete code example

Combining the above steps, here is a complete example code that reads content from a file, calculates hash values, and compares it with the expected hash values.

 <?php
$algorithm = 'sha256';  // Hash algorithm selection
$filename = 'path/to/your/file.txt';  // File path
$expectedHash = 'Expected hash value';  // Expected hash value obtained from a database or elsewhere

// Initialize hash calculation
$context = hash_init($algorithm);

// Open the file and read the content
$file = fopen($filename, 'rb');
if ($file) {
    while (!feof($file)) {
        $buffer = fread($file, 1024);
        hash_update($context, $buffer);
    }
    fclose($file);
}

// Get the final hash value
$hashValue = hash_final($context);
echo "The hash value of the file is: " . $hashValue . "\n";

// Comparison hash value
if ($hashValue === $expectedHash) {
    echo "File complete,Not tampered with。";
} else {
    echo "Files are corrupted or tampered。";
}
?>

Summarize

Through the above steps, you can use the hash_final function in PHP to implement file integrity check. First, the hash calculation is initialized through hash_init , then the hash value is gradually updated using hash_update , and finally the final hash value is obtained through hash_final and compared with the expected hash value. This can effectively check whether the file is complete and has not been tampered with.

In practical applications, using appropriate hashing algorithms and timely verification of hash values ​​can greatly improve the security of the system and ensure the authenticity and integrity of the file.