Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created April 29, 2015 10:56
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save umidjons/42d378dc7d649c659a07 to your computer and use it in GitHub Desktop.
Generate random hash string in PHP

Generate random hash string in PHP

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

Examples:

<?php
echo randHash()  .'<br>'; // c700f7b818a7e9e41e7d04cdf5ec8245
echo randHash(20).'<br>'; // 9bfae7b4cd0f1a3fa571
echo randHash(50).'<br>'; // f359dd85479999ea7632210e8c07158a NOTE: max length = 32
@mrabro
Copy link

mrabro commented Sep 23, 2021

👍🏻

@webnatrix
Copy link

private function randHash($len=64)
{
    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