Skip to content

Instantly share code, notes, and snippets.

@HodoJi
Forked from umidjons/random-hash-string-php.md
Last active February 27, 2024 14:20
Show Gist options
  • Save HodoJi/a66c3721ae98442903cc30d699f0cc90 to your computer and use it in GitHub Desktop.
Save HodoJi/a66c3721ae98442903cc30d699f0cc90 to your computer and use it in GitHub Desktop.
Generate random hash string in PHP

Generate random hash string in PHP

<?php
function randHash(int $len = 32): string
{
	return substr(md5(openssl_random_pseudo_bytes(20)), -$len);
}

Examples:

<?php
echo randHash();   // c700f7b818a7e9e41e7d04cdf5ec8245
echo randHash(20); // 9bfae7b4cd0f1a3fa571
echo randHash(50); // f359dd85479999ea7632210e8c07158a -- NOTE: max length = 32
private function randHash(int $len = 64): string // -- for longer hashes
{
    return substr(hash('sha256', openssl_random_pseudo_bytes(20)), -$len);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment