Generar cadenas alfanuméricas aleatorias (pseudo)


¿Cómo puedo generar una cadena alfanumérica (pseudo)aleatoria, algo así como: 'd79jd8c' en PHP?

 78
Author: MrValdez, 2008-09-07

14 answers

Primero haga una cadena con todos sus caracteres posibles:

 $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';

También puedes usar range() para hacer esto más rápidamente.

Luego, en un bucle, elige un número aleatorio y úsalo como índice de la cadena $characters para obtener un carácter aleatorio, y añádelo a tu cadena:

 $string = '';
 $max = strlen($characters) - 1;
 for ($i = 0; $i < $random_string_length; $i++) {
      $string .= $characters[mt_rand(0, $max)];
 }

$random_string_length es la longitud de la cadena aleatoria.

 154
Author: Jeremy Ruten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-01 11:30:50

Me gusta esta función para el trabajo

function randomKey($length) {
    $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));

    for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
    }
    return $key;
}

echo randomKey(20);
 18
Author: azerafati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-28 13:37:14

Genere una cadena de caracteres criptográficamente fuerte, aleatoria (potencialmente) de 8 caracteres usando la función openssl_random_pseudo_bytes:

echo bin2hex(openssl_random_pseudo_bytes(4));

Procedimiento:

function randomString(int $length): string
{
    return bin2hex(openssl_random_pseudo_bytes($length));
}

Actualización:

PHP7 introdujo las funciones random_x() que deberían ser aún mejores. Si viene de PHP 5.X, use la biblioteca excellent paragonie/random_compat que es un polyfill para random_bytes() y random_int() de PHP 7.

function randomString($length)
{
    return bin2hex(random_bytes($length));
}
 9
Author: emix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-09 12:17:56

Solución de una línea:

echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );

Puede cambiar el parámetro substr para establecer una longitud diferente para su cadena.

 6
Author: Marco Panichi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 19:55:36

Utilizar la tabla ASCII escoger un rango de letras, donde el: $range_start , $range_end es un valor de la columna decimal en la tabla ASCII.

Encuentro que este método es mejor comparado con el método descrito donde el rango de caracteres se define específicamente dentro de otra cadena.

// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end   = 122;
$random_string = "";
$random_string_length = 10;

for ($i = 0; $i < $random_string_length; $i++) {
  $ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
  // finds the character represented by $ascii_no and adds it to the random string
  // study **chr** function for a better understanding
  $random_string .= chr( $ascii_no );
}

echo $random_string;

Ver más:

 4
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:24

Sé que es un post antiguo pero me gustaría contribuir con una clase que he creado basada en la respuesta de Jeremy Ruten y mejorado con sugerencias en comentarios:

    class RandomString
    {
      private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
      private static $string;
      private static $length = 8; //default random string length

      public static function generate($length = null)
      {

        if($length){
          self::$length = $length;
        }

        $characters_length = strlen(self::$characters) - 1;

        for ($i = 0; $i < self::$length; $i++) {
          self::$string .= self::$characters[mt_rand(0, $characters_length)];
        }

        return self::$string;

      }

    }
 4
Author: diegoiglesias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-13 10:38:09

Tal vez me perdí algo aquí, pero aquí hay una manera de usar la función uniqid () .

 2
Author: Edward Fuller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-26 23:40:03

He hecho la siguiente función rápida solo para jugar con la función range(). Podría ayudar a alguien en algún momento.

Function pseudostring($length = 50) {

    // Generate arrays with characters and numbers
    $lowerAlpha = range('a', 'z');
    $upperAlpha = range('A', 'Z');
    $numeric = range('0', '9');

    // Merge the arrays
    $workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));
    $returnString = "";

    // Add random characters from the created array to a string
    for ($i = 0; $i < $length; $i++) {
        $character = $workArray[rand(0, 61)];
        $returnString .= $character;
    }

    return $returnString;
}
 2
Author: Peter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-29 07:52:12
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo generateRandomString();
 1
Author: Molla Rasel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-08 10:48:58

Puede utilizar el siguiente código, copiado de este artículo. Es similar a las funciones existentes, excepto que puede forzar el conteo de caracteres especiales:

function random_string()
{
    // 8 characters: 7 lower-case alphabets and 1 digit
    $character_set_array = array();
    $character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
    $character_set_array[] = array('count' => 1, 'characters' => '0123456789');
    $temp_array = array();
    foreach ($character_set_array as $character_set) {
        for ($i = 0; $i < $character_set['count']; $i++) {
            $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
        }
    }
    shuffle($temp_array);
    return implode('', $temp_array);
}
 1
Author: Salman A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-09 06:47:03

Esto es algo que uso:

$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);

Puede ver los documentos para openssl_random_pseudo_bytes aquí , y los documentos para bin2hex aquí

 0
Author: Zeeshan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-28 13:57:31

La respuesta de Jeremy es genial. Si, como yo, no estás seguro de cómo implementar range(), puedes ver mi versión usando range().

<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
    for($i = 0; $i < 6; $i++) {
        $string .= $character_array[rand(0, (count($character_array) - 1))];
    }
echo $string;
?>

Esto hace exactamente lo mismo que Jeremy pero usa matrices combinadas donde usa una cadena, y usa count() donde usa strlen().

 0
Author: Josh Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-19 17:22:08

1 línea:

$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;
 0
Author: HausO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-11 15:19:54

Si desea una manera muy fácil de hacer esto, puede apoyarse en las funciones PHP existentes. Este es el código que uso:

substr( sha1( time() ), 0, 15 )

time() le da la hora actual en segundos desde epoch, sha1() la cifra a una cadena de 0-9a-f, y substr() le permite elegir una longitud. No tienes que comenzar en el carácter 0, y cualquiera que sea la diferencia entre los dos números será la longitud de la cadena.

 0
Author: DiMono,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-16 14:51:02