Sometimes we need to create a random string or token using PHP. For example, it’s quite common that when we want to reset our password on some website a message is sent to the mail we registered.

Probably the message have a link like this:

Where 123 is the token. Today we will see how to create a token cryptographically secure using PHP. We can use this token as a password or as random string to reset something.

This works for PHP 5 and for PHP 7.

Generate cryptographically secure token using PHP

Let’s see how to generate a token in PHP, which is nothing more than a set of characters that should not be guessed in any way (except by brute force, but that’s another story).

There are 2 versions of this script, the first for PHP 5 and the second for PHP 7.

This is because PHP 7 incorporates new functions that are not present in the other versions, so we must look for alternatives.

In PHP 5

If we use PHP in its version 5 (although we should update) this will generate a secure token:

We divide the length between 2, since when representing each byte in hexadecimal format these are converted into 2 digits.

For example, “Hola” in hexadecimal is 48656c6c6f.

And to call it we call it with an argument: the length. That is, how many characters we want or the expected length of the string.


It is important to note that when we pass 7 it actually returns a string of length 6, so we better pass even numbers and greater than 4.


We would modify the function and call random_bytes instead of openssl_random_pseudo_bytes. It looks like this:


We can call the function and it will return a random string like this:

Just as seen in the following image:

Demostración de cómo generar un token en PHP que sea seguro criptográficamente

Demostración de cómo generar un token en PHP que sea seguro criptográficamente

¿Encontraste lo que buscabas?

Si es así, suscríbete para que estés enterado de mis nuevos posts sobre programación e informática

Estoy interesado en trabajar contigo de manera remota para llevar tu idea a la realidad, formar parte de tu equipo de desarrolladores, ayudarte con tu tarea, dar asesorías y todo lo relacionado con tecnología y programación. Contáctame para más información
No te vayas sin seguirme en Twitter, Facebook y GitHub
Si tienes dudas déjalas en un comentario, pero asegúrate de seguirme antes como agradecimiento (no te cuesta nada y me ayudas mucho)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
%d bloggers like this: