Php generate unique string

Generate 6,8,10 digit random, unique, alphanumeric string and Number in PHP

If you are searching for such as generate php random string fixed length, generate random string in php without duplication, php, generate unique 6 digit unique number in php alphanumeric string, how to generate a unique string in php , generate php random md5 string, php random password, and php random alphanumeric string etc. So this tutorial will help you a lot.

In this tutorial, we will show you how you can easily generate 6,8,10 digit random, unique, alphanumeric string and number in PHP.

When you are working with PHP. So many times you need to generate random, unique, alphanumeric type string in your PHP projects. This tutorial will simply help you.

Generate 6,8,10 digit random, unique, alphanumeric string and Number in PHP

  • Method 1:- Using str_shuffle() Function
  • Method 2:- Using md5() Function
  • Method 3:- To generate random, unique, alphanumeric numbers in PHP
    • 6-digit alphanumeric number
    • 8-digit alphanumeric number

    Method 1:- Using str_shuffle() Function

    The PHP str_shuffle() function is an built-in function in PHP. Basically which is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it. This function does not make any change in the original string or the number passed to it as a parameter. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter.

    Ex 1 :- php generate alphanumeric random string

    Result of the above code is:

    Method 2:- Using md5() Function

    The md5() function is used to calculate the MD5 hash of a string. Pass timestamp as a argument and md5 function will convert them into 32 bit characters

    "; echo substr(md5(microtime()), 0, 8); ?>

    Result of the above code is:

    Method 3:- To generate random, unique, alphanumeric numbers in PHP

    6-digit alphanumeric number:

    Using the below given function, you can generate 6 digits random unique alphanumeric numbers in PHP:

    function generateRandomString($length = 6) < $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $result = ''; for ($i = 0; $i < $length; $i++) < $result .= $characters[rand(0, strlen($characters) - 1)]; >return $result; > // Usage example: echo generateRandomString();

    8-digit alphanumeric number:

    Using the below given function, you can generate 8 digits random unique alphanumeric numbers in PHP:

    function generateRandomString($length = 8) < $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $result = ''; for ($i = 0; $i < $length; $i++) < $result .= $characters[rand(0, strlen($characters) - 1)]; >return $result; > // Usage example: echo generateRandomString();

    Источник

    uniqid

    Получает уникальный идентификатор с префиксом, основанный на текущем времени в микросекундах.

    Эта функция не создает ни случайную ни трудно подбираемую строку. Нельзя использовать эту функцию в целях повышения безопасности. Используйте криптографически безопасные функции/генераторы случайных данных, и криптографически защищенные хэш-функции для создания непредсказуемых безопасных ID.

    Список параметров

    Может быть полезно, к примеру, если идентификаторы генерируются одновременно на нескольких хостах и генерация идентификаторы производится в одну и ту же микросекунду.

    С пустым параметром prefix , возвращаемая строка будет длиной в 13 символов. Если параметр more_entropy равен TRUE , то строка буде длиной в 23 символа.

    Если равен TRUE , то функция uniqid() добавит дополнительную энтропию (используя комбинированный линейный конгруэнтный генератор) в конце возвращаемого значения, что увеличивает вероятность уникальности результата.

    Возвращаемые значения

    Возвращает уникальный идентификатор в виде строки (string).

    Примеры

    Пример #1 Пример использования uniqid()

    /* Уникальный id, например: 4b3403665fea6 */
    printf ( «uniqid(): %s\r\n» , uniqid ());

    /* Префикс к уникальному id можно добавить одним
    * из следующих способов:
    *
    * $uniqid = $prefix . uniqid();
    * $uniqid = uniqid($prefix);
    */
    printf ( «uniqid(‘php_’): %s\r\n» , uniqid ( ‘php_’ ));

    /* Также можно активировать параметр большей энтропии, который
    * требуется на некоторых системах, таких как Cygwin. Таким образом
    * функция uniqid() сгенерирует значение: 4b340550242239.64159797
    */
    printf ( «uniqid(», true): %s\r\n» , uniqid ( » , true ));
    ?>

    Примечания

    Эта функция не генерирует защищенные криптографически токены, по сути, не передается каких-либо дополнительных параметров и возвращаемое значение мало чем отличается от возвращаемого функцией microtime() . Если необходимо сгенерировать криптографически защищенные токены, то нужно использовать функцию openssl_random_pseudo_bytes() .

    Замечание:

    В Cygwin, параметр more_entropy должен быть задан как TRUE для работы этой функции.

    Источник

    PHP: How to generate a Unique id in PHP (Alphanumeric String)

    In php, there are many ways to generate unique alphanumeric id. First of all, we will understand why we might need unique alphanumeric id in first place.

    In applications, normally we use unique integer ids which is generally generated by database itself ~ Auto-increment, unique integers. But sometimes we need unique alphanumeric string as ids instead of simple integers.

    Few Reasons:

    • Unique ID is needed if you have multiple-server app architecture i.e — Your database is stored in multiple servers
    • If you want to merge different branches of data without clashes
    • Unique ID is helpful and must if you want to prevent sequence discovery of data in application or API endpoints.

    Generate Unique Alphanumeric String using uniqid() function in PHP

    In PHP, there is a very helpful function uniqid() which generates unique alphanumeric string for you. The function has two parameters ~ though both are optional —

    1) $prefix — you can prefix the generated id with any string 2) $more _ entropy — By default, it sets to FALSE but if set to TRUE, it will add additional entropy ~ basically it means that it will increase the uniqueness of the returned string

    //generates 13 character random unique alphanumeric id echo uniqid(); //output - 5e6d873a4f597 //generates 13 character random unique id with prefix - db echo uniqid("db"); //output - db5e6d875de7ba5 //generates 23 character random unique id with prefix - db but with more randomness echo uniqid("db",true); //output - db5e6d8782d90365.80737996 //generates random unique id with random prefix - higher randomness than fixed prefix echo uniqid (rand (),true); //output - 5e6d88383c9abdb5e6d88383c9b118314536965e6d88383c9b75.70966391

    As you can see above, we can use uniqid() function in different ways to generate unique id.

    Generate Unique Alphanumeric String using random _ bytes() function in PHP

    In PHP 7.x, there is another powerful and more secure function to generate random alphanumeric string — random _ bytes(). It requires only one parameter — length, and it generates cryptographically secure pseudo-random bytes. Further, passing its output to another function bin2hex(), will give you unique random string.

    $bytes = random_bytes(16); echo bin2hex($bytes); //output - 68309ba352806f9a943e16e74e5a9da3

    Thus, using any of the above methods, you can create unique random strings and use it instead of basic integers and thus secure your application. Hope this helped you out.

    Источник

    PHP uniqid() Function

    The uniqid() function generates a unique ID based on the microtime (the current time in microseconds).

    Syntax

    Parameter Values

    Parameter Description
    prefix Optional. Specifies a prefix to the unique ID (useful if two scripts generate ids at exactly the same microsecond)
    more_entropy Optional. Specifies more entropy at the end of the return value. This will make the result more unique. When set to TRUE, the return string will be 23 characters. Default is FALSE, and the return string will be 13 characters long

    Technical Details

    Return Value: Returns the unique identifier, as a string
    PHP Version: 4+
    Changelog: The prefix parameter became optional in PHP 5.0.
    The limit of 114 characters long for prefix was raised in PHP 4.3.1.

    ❮ PHP Misc Reference

    Unlock Full Access 50% off

    COLOR PICKER

    colorpicker

    Join our Bootcamp!

    Report Error

    If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

    Thank You For Helping Us!

    Your message has been sent to W3Schools.

    Top Tutorials
    Top References
    Top Examples
    Get Certified

    W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

    Источник

    Читайте также:  Php style align center
Оцените статью