Hash update file: примеры (PHP)
hash_update_file(HashContext $context, string $filename, ?resource $stream_context = null): boolОписание функции hash_update_file
Функция hash_update_file добавляет данные из файла в активный контекст хеширования. Она применяется для инкрементального вычисления хеш-суммы больших файлов без необходимости загрузки всего содержимого в память.
Синтаксис: hash_update_file(HashContext $context, string $filename, ?resource $stream_context = null): bool
- $context - контекст хеширования, созданный функцией hash_init.
- $filename - путь к файлу, данные которого добавляются в хеш.
- $stream_context - необязательный ресурс контекста потока, создаваемый функцией stream_context_create.
Функция возвращает true при успешном выполнении или false в случае ошибки.
Базовые примеры использования
<?php
$context = hash_init('sha256');
hash_update_file($context, 'document.pdf');
$hash = hash_final($context);
echo $hash;
?>a7f3c8e1d9b54f2a6e5d8c7b0a9f1e2d3c4b5a6e7f8d9c0b1a2f3e4d5c6b7a8e9
<?php
$context = hash_init('md5');
hash_update_file($context, 'file1.txt');
hash_update_file($context, 'file2.txt');
$combinedHash = hash_final($context);
echo "Хеш двух файлов: $combinedHash";
?>Хеш двух файлов: 5d41402abc4b2a76b9719d911017c592
<?php
$context = hash_init('sha1');
$streamContext = stream_context_create(['http' => ['timeout' => 30]]);
hash_update_file($context, 'https://example.com/largefile.zip', $streamContext);
$result = hash_final($context);
echo $result;
?>da39a3ee5e6b4b0d3255bfef95601890afd80709
Альтернативные функции в PHP
Вычисляет хеш файла напрямую без инкрементального подхода. Используется для простых случаев, когда не требуется добавлять данные из нескольких источников.
<?php
$hash = hash_file('sha256', 'largefile.iso');
?>Специализированные функции для конкретных алгоритмов. Устарели в пользу hash_file с указанием алгоритма.
Добавляет строковые данные в контекст хеширования. Подходит для данных, уже находящихся в памяти.
<?php
$context = hash_init('sha256');
hash_update($context, 'данные для хеширования');
?>Альтернативы в других языках программирования
Hash update file в Python
Используется модуль hashlib с инкрементальным обновлением через update().
import hashlib
sha256 = hashlib.sha256()
with open('file.txt', 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
print(sha256.hexdigest())e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Модуль crypto создает хеш-объекты с методом update.
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
const input = fs.createReadStream('file.txt');
input.on('data', chunk => hash.update(chunk));
input.on('end', () => console.log(hash.digest('hex')));Использование утилит командной строки.
sha256sum file.txte3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Типичные ошибки при использовании
<?php
$context = hash_init('sha256');
$result = @hash_update_file($context, 'nonexistent.txt');
if ($result === false) {
echo "Ошибка при чтении файла";
}
?>Ошибка при чтении файла
<?php
$context = hash_init('md5');
hash_final($context);
$result = hash_update_file($context, 'file.txt');
var_dump($result);
?>bool(false)
<?php
$notContext = 'string';
hash_update_file($notContext, 'file.txt');
?>TypeError: hash_update_file(): Argument #1 ($context) must be of type HashContext, string given
Изменения в последних версиях PHP
Тип параметра $context изменен на HashContext (ранее был resource). Добавлена строгая типизация.
Добавлена поддержка хеш-контекстов как объектов. Функция продолжает принимать ресурсы для обратной совместимости.
В PHP 5.1 функция была введена как часть модуля Hash.
Расширенные примеры применения
<?php
function verifyFileHash($filePath, $expectedHash, $algorithm = 'sha256') {
$context = hash_init($algorithm);
if (hash_update_file($context, $filePath)) {
$actualHash = hash_final($context);
return hash_equals($expectedHash, $actualHash);
}
return false;
}
$isValid = verifyFileHash('setup.exe', 'abc123...');
echo $isValid ? 'Файл корректен' : 'Файл поврежден';
?><?php
function hashDirectory($dir, $algorithm = 'sha256') {
$context = hash_init($algorithm);
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($files as $file) {
if ($file->isFile()) {
hash_update_file($context, $file->getRealPath());
}
}
return hash_final($context);
}
echo hashDirectory('/path/to/project');
?><?php
function hashLargeFileWithProgress($filename, $algorithm = 'sha256') {
$context = hash_init($algorithm);
$fileSize = filesize($filename);
$handle = fopen($filename, 'rb');
$processed = 0;
while (!feof($handle)) {
$chunk = fread($handle, 65536);
hash_update($context, $chunk);
$processed += strlen($chunk);
$progress = ($processed / $fileSize) * 100;
echo "Прогресс: " . round($progress, 2) . "%\r";
}
fclose($handle);
echo "\n";
return hash_final($context);
}
?><?php
function areFilesIdentical($file1, $file2, $algorithm = 'md5') {
$context1 = hash_init($algorithm);
$context2 = hash_init($algorithm);
hash_update_file($context1, $file1);
hash_update_file($context2, $file2);
return hash_final($context1) === hash_final($context2);
}
?><?php
function createFileSetHash($fileList, $algorithm = 'sha1') {
$context = hash_init($algorithm);
sort($fileList);
foreach ($fileList as $file) {
hash_update_file($context, $file);
hash_update($context, filemtime($file));
}
return hash_final($context);
}
$files = ['script.js', 'styles.css', 'index.php'];
echo "ID набора файлов: " . createFileSetHash($files);
?>