All those functions will be used, but only in a different sequence.Īs a last option, I will provide you with two of my functions that can generate a string of the length that we want.įirst function. The next three options are very similar to the previous option for getting a string. As a final step, we pass this hash of the string to the substr function, which will truncate the string to the length we want by passing in the second parameter, length. In the next step, we pass this set of numbers to the md5 function, which forms the hash of the string. We first get a set of digits by calling the time function which returns the number of seconds since the Unix epoch. The next option to generate a unique string, we will use already three functions, substr, md5 and time. The bin2hex function is designed to convert binary data to a hexadecimal representation, that is, to a regular string. After generating a string in bytes by a further action, this string must be passed to the bin2hex function. In the following example, we will use two functions, random_bytes and bin2hex, to generate a unique string.įirst, the random_bytes function generates cryptographically pseudo-random bytes, the function takes a mandatory length parameter, that is, the length of the generated string in bytes. We've called the uniqid function twice, resulting in two unique strings. This function has two optional parameters that can be passed, but in order for us to generate a unique string, we can additionally not pass anything. Write a PHP script to generate random 11 characters string of letters and numbers. The uniqid function generates a unique string based on getting the current time in microseconds. In the very first option, we will use the uniqid function. There are a lot of options in PHP for how to generate a unique string, and I will show you the most common options that developers use. One example where you will need to generate a unique string is a cookie for users who register on your site, and this cookie will be used by the user each time they log in. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter.In today's article, we'll talk about how to generate a unique string in PHP.Īlmost always in your developments you will encounter the fact that you need to generate a unique string of a certain length, and there are a lot of examples of this. This function does not make any change in the original string or the number passed to it as a parameter. When a number is passed, it treats the number as the string and shuffles it. Basically which is used to randomly shuffle all the characters of a string passed to the function as a parameter. The PHP str_shuffle() function is an built-in function in PHP.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |