declare(strict_types=1);
/**
* Computes a SHA-256 hash for a string.
*
* Why SHA-256?
* - Built into PHP.
* - Produces a fixed-length hexadecimal string.
* - Commonly used for checksums and data verification.
* - More appropriate than rolling your own hash function.
*
* Important:
* - Hashing is not encryption.
* - A hash is intended to identify data, not recover it.
* - Different inputs can theoretically produce the same hash
* (called a collision), although collisions are extremely
* unlikely with SHA-256.
*
* @param string $text The input string to hash.
*
* @return string The SHA-256 hash as a hexadecimal string.
*/
function hashString(string $text): string
{
return hash('sha256', $text);
}
/*
* Example input string.
*
* In a real application, this value might come from:
* - User input
* - A file
* - A database
* - An API request
*/
$text = 'Hello, World!';
/*
* Compute the hash value.
*/
$hashValue = hashString($text);
echo "Original string: {$text}" . PHP_EOL;
echo "SHA-256 hash : {$hashValue}" . PHP_EOL;
/*
* Demonstrate hash comparison.
*
* Identical strings should produce identical hashes.
*/
$anotherText = 'Hello, World!';
$hash1 = hashString($text);
$hash2 = hashString($anotherText);
if ($hash1 === $hash2) {
echo PHP_EOL;
echo "Hashes match." . PHP_EOL;
/*
* IMPORTANT:
*
* A matching hash does not mathematically guarantee
* that two inputs are identical because all hash
* functions have the possibility of collisions.
*
* For SHA-256, collisions are extraordinarily unlikely,
* but when exact equality matters, compare the original
* values as well.
*/
if ($text === $anotherText) {
echo "Strings are identical." . PHP_EOL;
}
}
/*
* Professional guidance:
*
* Good uses for hashing:
* - Data integrity verification
* - File checksums
* - Cache keys
* - Digital fingerprints
* - Detecting changes in data
*
* Password storage:
* - Do NOT use hash() directly.
* - Use password_hash() and password_verify().
*
* Example:
*
* $passwordHash = password_hash($password, PASSWORD_DEFAULT);
*
* if (password_verify($password, $passwordHash)) {
* // Password is correct.
* }
*
* Password hashing requires specialized algorithms such as
* bcrypt or Argon2, which are provided by PHP's password API.
*/
/*
run:
Original string: Hello, World!
SHA-256 hash : dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
Hashes match.
Strings are identical.
*/