In PHP, hash_final() is a function used with hash_init() and hash_update() to generate hash values in step. This set of functions provides a more flexible way than using the hash() function directly, especially for processing large data streams or segmented data.
This article will explain how to use hash_final() to generate SHA-256 hash values.
hash_final() is used to complete the hash context and return the final hash value. It is used in conjunction with hash_init() (initializes a hash context) and hash_update() (adds data to the context).
This approach is especially suitable when you can't put all your data into memory at once, such as processing large files or streaming data.
Here are the basic steps to generate a SHA-256 hash:
1?? Initialize the hash context
2?? Pass data into segments
3?? Get the final hash value
The following code demonstrates how to process string data in segments and generates a SHA-256 hash.
<?php
// first step:Initialize hash context,Specify the algorithm as sha256
$context = hash_init('sha256');
// Step 2:Update data in segments(Can be called multiple times hash_update)
$dataPart1 = 'Hello, ';
$dataPart2 = 'this is a test ';
$dataPart3 = 'using hash_final().';
hash_update($context, $dataPart1);
hash_update($context, $dataPart2);
hash_update($context, $dataPart3);
// Step 3:Get the final hash value(Hexadecimal string)
$hash = hash_final($context);
echo "The final SHA-256 The hash value is: $hash";
?>
Output example:
The final SHA-256 The hash value is: 6e4b18e9f8f2de9d4d70f43b8f6b1c7e6812b826ad3b1c5eaf2df62e245b3f94
If you want to generate a SHA-256 hash on a large file, you can do this:
<?php
$context = hash_init('sha256');
// Open the file stream
$handle = fopen('https://gitbox.net/path/to/largefile.zip', 'rb');
if ($handle === false) {
die('Unable to open the file。');
}
// Each read 8KB
while (!feof($handle)) {
$data = fread($handle, 8192);
hash_update($context, $data);
}
fclose($handle);
$hash = hash_final($context);
echo "Filed SHA-256 The hash value is: $hash";
?>
In this example, we use fopen() to directly read the remote file https://gitbox.net/path/to/largefile.zip , and update the hash context block by block, and finally get the SHA-256 hash value of the file.
? If you only need to generate hashings for small data (such as a string), it is actually easier to use hash() directly:
$hash = hash('sha256', 'Hello, this is a test.');
? After hash_final() is used up, the hash context will be destroyed. If you want to reuse it, you need to call hash_init() again.