Generador de cadenas aleatorias PHP


Estoy tratando de crear una cadena aleatoria en PHP, y no obtengo absolutamente ninguna salida con esto:

<?php
function RandomString()
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randstring = '';
    for ($i = 0; $i < 10; $i++) {
        $randstring = $characters[rand(0, strlen($characters))];
    }
    return $randstring;
}
RandomString();
echo $randstring;

¿Qué estoy haciendo mal?

Author: Yogesh Suthar, 2010-12-05

30 answers

Para responder a esta pregunta específicamente, dos problemas:

  1. $randstring no está en el alcance cuando se hace eco de él.
  2. Los caracteres no se concatenan juntos en el bucle.

Aquí hay un fragmento de código con las correcciones:

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

Muestra la cadena aleatoria con la siguiente llamada:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

Tenga en cuenta que esto genera cadenas aleatorias predecibles. Si desea crear tokens seguros, consulte esta respuesta.

 1183
Author: Stephen Watkins,
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 12:34:44

Nota: str_shuffle() usos internos rand(), que no sea adecuado para fines de criptografía (por ejemplo, generar contraseñas aleatorias). En su lugar, desea un generador seguro de números aleatorios. Tampoco permite que los caracteres se repitan.

Una manera más.

ACTUALIZADO (ahora esto genera cualquier longitud de cadena):

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)

Eso es todo. :)

 327
Author: Pr07o7yp3,
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 12:10:43

Hay muchas respuestas a esta pregunta, pero ninguna de ellas aprovecha un Generador de Números Pseudoaleatorios Criptográficamente Seguro (CSPRNG).

La respuesta simple, segura y correcta es usar RandomLib y no reinventar la rueda.

Para aquellos de ustedes que insisten en inventar su propia solución, PHP 7.0.0 proporcionará random_int() para este propósito; si todavía está en PHP 5.x, escribimos un PHP 5 polyfill para random_int() para que pueda utilizar la nueva API incluso antes de actualizar a PHP 7.

Generar enteros aleatorios de forma segura en PHP no es una tarea trivial. Siempre debe consultar con sus expertos residentes en criptografía StackExchange antes de implementar un algoritmo local en producción.

Con un generador de enteros seguro en su lugar, generar una cadena aleatoria con un CSPRNG es un paseo por el parque.

Creando un Seguro, Aleatorio String

/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
    $pieces = [];
    $max = mb_strlen($keyspace, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pieces []= $keyspace[random_int(0, $max)];
    }
    return implode('', $pieces);
}

Uso :

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');

Demo: https://3v4l.org/b4PST (Ignore los fallos de PHP 5; necesita random_compat)

 252
Author: Scott Arciszewski,
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-01 20:29:20

Crea una cadena hexdec de 20 caracteres:

$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars

En PHP 7 (random_bytes()):

$string = base64_encode(random_bytes(10)); // ~14 chars
// or
$string = bin2hex(random_bytes(10)); // 20 chars
 110
Author: Rudie,
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-06-30 16:16:49

@tasmaniski: tu respuesta funcionó para mí. Yo tenía el mismo problema, y lo sugeriría para aquellos que siempre están buscando la misma respuesta. Aquí está de @ tasmaniski:

<?php 
    $random = substr(md5(mt_rand()), 0, 7);
    echo $random;
?>
 76
Author: Humphrey,
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-07-26 15:47:51

Dependiendo de tu aplicación (quería generar contraseñas), puedes usar

$string = base64_encode(openssl_random_pseudo_bytes(30));

Siendo base64, pueden contener = o - así como los caracteres solicitados. Puede generar una cadena más larga, luego filtrarla y recortarla para eliminarla.

openssl_random_pseudo_bytes parece ser la forma recomendada de generar un número aleatorio adecuado en php. Por qué rand no usa /dev/random No lo sé.

 43
Author: rjmunro,
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
2013-02-06 17:40:18

Sé que esto puede ser un poco tarde para el juego, pero aquí hay una simple línea que genera una cadena aleatoria verdadera sin ningún bucle de nivel de script o el uso de bibliotecas openssl.

echo substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', mt_rand(1,10))),1,10);

Para descomponerlo para que los parámetros sean claros

// Character List to Pick from
$chrList = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

// Minimum/Maximum times to repeat character List to seed from
$chrRepeatMin = 1; // Minimum times to repeat the seed string
$chrRepeatMax = 10; // Maximum times to repeat the seed string

// Length of Random String returned
$chrRandomLength = 10;

// The ONE LINE random command with the above variables.
echo substr(str_shuffle(str_repeat($chrList, mt_rand($chrRepeatMin,$chrRepeatMax))),1,$chrRandomLength);

Este método funciona repitiendo aleatoriamente la lista de caracteres, luego baraja la cadena combinada y devuelve el número de caracteres especificados.

Puede aleatorizar aún más esto, aleatorizando la longitud de la cadena devuelta, reemplazar $chrRandomLength por mt_rand(8, 15) (para una cadena aleatoria entre 8 y 15 caracteres).

 25
Author: Kraang Prime,
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
2014-04-19 21:18:25

Una mejor manera de implementar esta función es:

function RandomString($length) {
    $keys = array_merge(range(0,9), range('a', 'z'));

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

echo RandomString(20);

mt_rand es más aleatorio según este y este en php7. La función rand es un alias de mt_rand.

 23
Author: Rathienth Baskaran,
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-03-30 15:41:12
function generateRandomString($length = 15)
{
    return substr(sha1(rand()), 0, $length);
}

Tada!

 21
Author: Davor,
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
2012-12-26 16:32:42

$randstring en el ámbito de la función no es el mismo que el ámbito donde se llama. Debe asignar el valor devuelto a una variable.

$randstring = RandomString();
echo $randstring;

O simplemente repite directamente el valor devuelto:

echo RandomString();

Además, en tu función tienes un pequeño error. Dentro del bucle for, debe usar .= para que cada carácter se agregue a la cadena. Al usar = lo sobrescribes con cada carácter nuevo en lugar de añadirlo.

$randstring .= $characters[rand(0, strlen($characters))];
 19
Author: BoltClock,
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-12-04 22:59:23

Primero, define el alfabeto que desea usar:

$alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$special  = '~!@#$%^&*(){}[],./?';
$alphabet = $alphanum . $special;

Entonces, use openssl_random_pseudo_bytes() para generar datos aleatorios adecuados:

$len = 12; // length of password
$random = openssl_random_pseudo_bytes($len);

Finalmente, utiliza estos datos aleatorios para crear la contraseña. Debido a que cada carácter en $random puede ser chr(0) hasta chr(255), el código usa el resto después de la división de su valor ordinal con $alphabet_length para asegurarse de que solo se seleccionen caracteres del alfabeto (tenga en cuenta que hacerlo sesga la aleatoriedad):

$alphabet_length = strlen($alphabet);
$password = '';
for ($i = 0; $i < $len; ++$i) {
    $password .= $alphabet[ord($random[$i]) % $alphabet_length];
}

Alternativamente, y en general mejor, es usar RandomLib y SecurityLib :

use SecurityLib\Strength;

$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new Strength(Strength::MEDIUM));

$password = $generator->generateString(12, $alphabet);
 14
Author: Ja͢ck,
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-06-29 03:52:19

Métodos cortos..

Aquí hay algunos métodos más cortos para generar la cadena aleatoria

<?php
echo $my_rand_strng = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), -15); 

echo substr(md5(rand()), 0, 7);

echo str_shuffle(MD5(microtime()));
?>
 9
Author: Punit Gajjar,
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-12 06:45:34

He probado el rendimiento de las funciones más populares allí, el tiempo que se necesita para generar 1'000'000 cadenas de 32 símbolos en mi caja es:

2.5 $s = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,32);
1.9 $s = base64_encode(openssl_random_pseudo_bytes(24));
1.68 $s = bin2hex(openssl_random_pseudo_bytes(16));
0.63 $s = base64_encode(random_bytes(24));
0.62 $s = bin2hex(random_bytes(16));
0.37 $s = substr(md5(rand()), 0, 32);
0.37 $s = substr(md5(mt_rand()), 0, 32);

Tenga en cuenta que no es importante cuánto tiempo fue realmente, pero cuál es más lento y cuál es más rápido para que pueda seleccionar de acuerdo con sus requisitos, incluida la preparación para criptografía, etc.

Substr() alrededor de MD5 se agregó para mayor precisión si necesita una cadena que sea más corta que 32 símbolos.

En aras de la respuesta: la cadena no fue concatenada sino sobrescrita y el resultado de la función no fue almacenado.

 8
Author: Putnik,
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-10-24 12:09:28
function rndStr($len = 64) {
     $randomData = file_get_contents('/dev/urandom', false, null, 0, $len) . uniqid(mt_rand(), true);
     $str = substr(str_replace(array('/','=','+'),'', base64_encode($randomData)),0,$len);
    return $str;
}
 7
Author: Руслан Ибрагимов,
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
2012-11-13 14:45:01

Este fue tomado de fuentes adminer :

/** Get a random string
* @return string 32 hexadecimal characters
*/
function rand_string() {
    return md5(uniqid(mt_rand(), true));
}

Adminer , herramienta de gestión de bases de datos escrita en PHP.

 7
Author: userlond,
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-02 03:15:53

Una forma muy rápida es hacer algo como:

substr(md5(rand()),0,10);

Esto generará una cadena aleatoria con la longitud de 10 caracteres. Por supuesto, algunos podrían decir que es un poco más pesado en el lado computacional, pero hoy en día los procesadores están optimizados para ejecutar el algoritmo md5 o sha256 muy rápidamente. Y por supuesto, si la función rand() devuelve el mismo valor, el resultado será el mismo, teniendo una probabilidad de 1 / 32767 de ser el mismo. Si la seguridad es el problema, entonces simplemente cambie rand() a mt_rand()

 6
Author: Akatosh,
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
2013-10-24 16:04:02

Función auxiliar de Laravel 5 framework

/**
 * Generate a "random" alpha-numeric string.
 *
 * Should not be considered sufficient for cryptography, etc.
 *
 * @param  int  $length
 * @return string
 */
function str_random($length = 16)
{
    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
 5
Author: artnikpro,
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-02-17 19:03:02

La versión editada de la función funciona bien, solo un problema que encontré: Usó el carácter incorrecto para encerrar los caracteres$, por lo que el carácter ' a veces es parte de la cadena aleatoria que se genera.

Para arreglar esto, cambie:

$characters = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;

A:

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

De esta manera solo se usan los caracteres encerrados, y el carácter ' nunca será parte de la cadena aleatoria que se genera.

 4
Author: bmcswee,
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
2012-08-09 05:56:56

Otro one-liner, que genera una cadena aleatoria de 10 caracteres con letras y números. Creará una matriz con range (ajustará el segundo parámetro para establecer el tamaño), loops sobre esta matriz y asigna un ascii-char aleatorio (rango 0-9 o a-z), luego implosiona la matriz para obtener una cadena.

$str = implode('', array_map(function () { return chr(rand(0, 1) ? rand(48, 57) : rand(97, 122)); }, range(0, 9)));

Nota: solo funciona en PHP 5.3+

 4
Author: kasimir,
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
2014-08-01 19:44:29

Una línea.
rápido para cuerdas enormes con algo de singularidad.

function random_string($length){
    return substr(str_repeat(md5(rand()), ceil($length/32)), 0, $length);
}
 4
Author: Jacob 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
2015-07-10 00:03:36
/**
 * @param int $length
 * @param string $abc
 * @return string
 */
function generateRandomString($length = 10, $abc = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
{
    return substr(str_shuffle($abc), 0, $length);
}

Fuente de http://www.xeweb.net/2011/02/11/generate-a-random-string-a-z-0-9-in-php/

 4
Author: sxn,
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-12-23 11:59:30

Me gustó el último comentario que usaba openssl_random_pseudo_bytes, pero no fue una solución para mí, ya que todavía tenía que eliminar los caracteres que no quería, y no pude obtener una cadena de longitud establecida. Aquí está mi solución...

function rndStr($len = 20) {
    $rnd='';
    for($i=0;$i<$len;$i++) {
        do {
            $byte = openssl_random_pseudo_bytes(1);
            $asc = chr(base_convert(substr(bin2hex($byte),0,2),16,10));
        } while(!ctype_alnum($asc));
        $rnd .= $asc;
    }
    return $rnd;
}
 3
Author: RKaneKnight,
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
2013-02-10 21:02:54
function randomString($length = 5) {
       return substr(str_shuffle(implode(array_merge(range('A','Z'), range('a','z'), range(0,9)))), 0, $length);
}
 3
Author: Anjith K P,
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-20 16:35:24

Otra forma de generar una cadena aleatoria en PHP es:

function RandomString($length) {
    $original_string = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
    $original_string = implode("", $original_string);
    return substr(str_shuffle($original_string), 0, $length);
}
echo RandomString(6);
 2
Author: Akhilraj N S,
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
2014-04-13 17:24:26

Hay un código simple:

echo implode("",array_map(create_function('$s','return substr($s,mt_rand(0,strlen($s)),1);'),array_fill(0,16,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")));

Hay una guía simple:

  • Para cambiar la longitud de la cadena, cambie el 16 a otro valor, solamente.
  • Para seleccionar entre diferentes caracteres, cambie la cadena de caracteres.
 2
Author: 16ctt1x,
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-02 15:27:54

Hay mejores alternativas a esto, muchos ya se publicó, así que solo te devuelvo tus cosas con correcciones

<?php
function RandomString()
{
    global $randstring ;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randstring = '';
    for ($i = 0; $i < 10; $i++) {
        $randstring .= $characters[rand(0, strlen($characters))];
    }
    return $randstring;
}

RandomString();

echo $randstring;
?>
 2
Author: Constantin,
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-01-02 16:13:17
<?php
    /**
     * Creates a random string
     *
     * @param (int) $length
     *   Length in characters
     * @param (array) $ranges
     *   (optional) Array of ranges to be used
     *
     * @return
     * Random string
    */
    function random_string($length, $ranges = array('0-9', 'a-z', 'A-Z')) {
        foreach ($ranges as $r) $s .= implode(range(array_shift($r = explode('-', $r)), $r[1]));
        while (strlen($s) < $length) $s .= $s;
        return substr(str_shuffle($s), 0, $length);
    }

    // Examples:
    $l = 100;
    echo '<b>Default:</b> ' . random_string($l) . '<br />';
    echo '<b>Lower Case only:</b> ' . random_string($l, array('a-z')) . '<br />';
    echo '<b>HEX only:</b> ' . random_string($l, array('0-9', 'A-F')) . '<br />';
    echo '<b>BIN only:</b> ' . random_string($l, array('0-1')) . '<br />';

/* End of file */
 1
Author: Geo,
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
2013-09-03 18:33:05
function getRandomString($length) {
  $salt = array_merge(range('a', 'z'), range(0, 9));
  $maxIndex = count($salt) - 1;

  $result = '';
  for ($i = 0; $i < $length; $i++) {
    $index = mt_rand(0, $maxIndex);
    $result .= $salt[$index];
  }
  return $result
}
 1
Author: Ryan Williams,
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
2013-10-02 00:10:43

Así es como lo estoy haciendo para obtener una verdadera clave aleatoria única:

$Length = 10;
$RandomString = substr(str_shuffle(md5(time())), 0, $Length);
echo $RandomString;

Puede usar time() ya que es una marca de tiempo Unix y siempre es única en comparación con otras aleatorias mencionadas anteriormente. A continuación, puede generar el md5sum de eso y tomar la longitud deseada que necesita de la cadena generada MD5. En este caso estoy usando 10 caracteres, y podría usar una cadena más larga si quisiera hacerla más única.

Espero que esto ayude.

 1
Author: sherpa,
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
2014-04-21 15:54:14

Fuente: Función PHP que Genera Caracteres Aleatorios

Esta función PHP funcionó para mí:

function cvf_ps_generate_random_code($length=10) {

   $string = '';
   // You can define your own characters here.
   $characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";

   for ($p = 0; $p < $length; $p++) {
       $string .= $characters[mt_rand(0, strlen($characters)-1)];
   }

   return $string;

}

Uso:

echo cvf_ps_generate_random_code(5);
 1
Author: Carl,
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-01-09 07:46:35