SHA-256 Hashing in PHP: hash() Function Guide
Use PHP's hash() function to compute SHA-256 hashes. Includes file hashing, HMAC signing, and timing-safe comparison examples for PHP developers.
PHP includes the hash() function natively, making SHA-256 hashing a one-liner with no extensions or libraries required. SHA-256 is available in all PHP versions from 5.1.2 onward, which means it works everywhere PHP runs. It is the standard choice for signing API requests, generating content identifiers, and verifying data integrity in PHP applications.
How to Use the SHA-256 Generator Tool
- Enter your input text — Type or paste the string you want to hash.
- Click Generate — The tool computes the SHA-256 hash and displays the 64-character result.
- Use it in your PHP code — Copy the expected hash and compare it with your PHP
hash()output to verify correctness. - Reference the examples below — Drop them directly into your application.
Basic SHA-256 in PHP
<?php
// Simple string hashing
$hash = hash('sha256', 'hello world');
echo $hash;
// b94d27b9934d3e08a52e52d7da7dabfac484efe04294e576b94...
// Uppercase output (some APIs require uppercase)
$hash_upper = strtoupper(hash('sha256', 'hello world'));
// Raw binary output (for binary protocols)
$raw = hash('sha256', 'hello world', true);
Hashing a File with SHA-256 in PHP
<?php
// Hash a file directly — reads in chunks automatically
$file_hash = hash_file('sha256', '/path/to/file.zip');
echo $file_hash;
// Verify file integrity against a known hash
$expected = 'b94d27b9934d3e08a52e52d7da7dabfac484efe04294e576b94...';
if (hash_equals($expected, $file_hash)) {
echo \"File integrity verified.\";
} else {
echo \"File has been modified or corrupted.\";
}
Why Use SHA-256 in PHP?
- Native support —
hash('sha256', ...)requires no extension. Thehashextension is enabled by default in all PHP builds. - Timing-safe comparison — Always use
hash_equals()instead of==when comparing hashes to prevent timing attacks. - File hashing built-in —
hash_file()handles large files in chunks without loading them entirely into memory. - HMAC support —
hash_hmac('sha256', $data, $secret)generates signed hashes for API authentication.
SHA-256 HMAC for API Signing in PHP
<?php
function sign_request(string $payload, string $secret): string {
return hash_hmac('sha256', $payload, $secret);
}
$signature = sign_request(json_encode($request_body), $api_secret);
// Add as Authorization header or query parameter
SHA-256 vs. password_hash() in PHP
For password storage, never use hash('sha256', $password) directly — use PHP's password_hash($password, PASSWORD_BCRYPT) or PASSWORD_ARGON2ID instead. These functions are specifically designed to be slow and include a built-in salt. SHA-256 without a salt is fast and vulnerable to rainbow table attacks when used for passwords.
Test your PHP SHA-256 hashes with the SHA-256 Generator — verify output before deploying to production.