Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

8
  • 2
    Please note that openssl_random_pseudo_bytes() did not use a cryptographically strong algorithm until php 5.6. Related bug: bugs.php.net/bug.php?id=70014 Commented Aug 8, 2016 at 15:30
  • Also note that the smallest string this can make is of length 2. If you pass a byte length of 1 or less to openssl_random_pseudo_bytes() you will get nothing back. Also, note that when using bin2hex(openssl_random_pseudo_bytes($length / 2)) since you are working with integers, it will automatically remove the modulo and will use the next lowest multiple of 2. So, $length = 19 will produce a string of length 18. Commented Oct 26, 2016 at 21:56
  • Proposal to use it as file content that can be opened through fgets($fp, 1024) and every file editor that has problems with very long lines: function string_rand($len, $split="\n") { return substr(chunk_split(bin2hex(openssl_random_pseudo_bytes(ceil($len / 2))), 1023, $split), 0, $len); } Set $split to null if it should return a one-liner. By that you can use it for both cases. Commented Mar 27, 2017 at 13:01
  • I really like the random_bytes solution for PHP 7, but if you need the string to be a certain number of characters would something like this work? $string = substr(base64_encode(random_bytes($size)), 0, $size); Commented Nov 27, 2017 at 11:04
  • This is absolutely without a doubt the best solution. Takes up very little space and is super easy to understand. Commented May 10, 2018 at 17:37