hash_file vs read-then-hash for file integrity
A same-file comparison of PHP’s streaming hash_file path and an explicit whole-file read followed by hash.
What the application is trying to do
Does hashing through hash_file differ materially from loading the full file and hashing the resulting string?
Artifact verification and upload pipelines often need a digest but not the full file contents in memory.
Memory behavior can be more important than a small timing delta, especially under concurrent uploads.
Observed host behavior
What this run shows: hash_file SHA-256 reduced local integrity-check time by avoiding part of the competing path; storage latency and memory pressure can change the balance. The slowest-to-fastest median spread was 30.62% on the measured host.
| Variant | Median | Middle 50% | Operations/s | Additional measure |
|---|---|---|---|---|
| hash_file SHA-256Fastest | 1.75 ms | 1.73 ms–1.77 ms | 572 | — |
| Read then hash SHA-256 | 2.29 ms | 2.28 ms–2.36 ms | 438 | — |
What changes outside the fixture
Even if a whole-file path appears fast in a warm-cache test, it adds memory proportional to file size. hash_file communicates the actual intent and avoids retaining a second full copy in userland.
Choose based on whether the application already needs the file bytes. If not, streaming integrity functions are generally the clearer resource boundary.
Read path and controls
hash_file should provide a memory-bounded path and may avoid an unnecessary application-level buffer, even when timing is close on a small cached file.
- Both variants compute SHA-256 over the same 2 MiB fixture.
- The read-then-hash variant allocates a complete PHP string before hashing.
- The digest prefix is consumed as a checksum; file-open and read work remain in the timed operation.
Open measured environment
- Measurement run
- 2026-07-22T15:23:56+00:00
- PHP
- 8.4.23 (cli)
- Operating system
- Linux 4.18.0-553.85.1.el8_10.x86_64
- Architecture
- x86_64
- Processor
- AMD EPYC-Rome Processor
- Reported host memory
- 15.02 GiB host total
- CLI OPcache
- 0
- PHP memory limit
- 1024M
- Loaded study extensions
- json, openssl, zlib, mbstring, pdo_sqlite
- Timing clock
- hrtime(true)
- Measured rounds
- 7
Before changing a production path
- Prefer hash_file when only a digest is required.
- Avoid reading large uploads fully into memory just to verify integrity.
- Use constant-time comparison functions where digest comparison has security significance.
Storage variables not simulated here
- The test uses a small local cached file.
- Peak resident memory and concurrent requests are not measured.
Primary documentation
These references document the PHP filesystem and hashing operations. Local storage behavior remains specific to the measured host.