Skip to content

Instantly share code, notes, and snippets.

@robertdrakedennis
Last active October 27, 2019 05:01
Show Gist options
  • Save robertdrakedennis/d58153716e1dedb920d91f935307818c to your computer and use it in GitHub Desktop.
Save robertdrakedennis/d58153716e1dedb920d91f935307818c to your computer and use it in GitHub Desktop.
Helper for generating a truly random string
<?php
if (! function_exists('randomize')) {
/**
* Generates a random string used for various simple randomness.
*
* @param int $min
* @param int $max
* @param int $limit
* @return string
* @throws Exception
*/
function randomize(int $min = 10, int $max = 16, int $limit = null)
{
$randomized = \hash('sha256', \random_bytes(\rand($min, $max)));
if ($limit !== null)
{
return (string) \Illuminate\Support\Str::limit($randomized, $limit, '');
}
return (string) $randomized;
}
}
@robertdrakedennis
Copy link
Author

robertdrakedennis commented Oct 27, 2019

You can limit the string if you want it for things like unique slugs.

Example:

// returns aa3792b5760c98985ff3-some-slug-here
 $slug = randomize(8, 16, 20) . '-' . $slug;

Doing this will allow you for users to have the same title / slug without having any real conflicts or downsides, users should be allowed to have the same thread title especially when it's in a board like general etc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment