I am using randomly generated numbers as session variables to identify the sessions in a PHP application. To make further security proof what ways should I follow?

  • Well, I guess that you should just try to be sure that your random numbers are not predictable in any way. Meaning, you should not depend on obvious parameter such as date, time or know parameters. – perror Nov 12 '13 at 9:14
  • I used mt_rand(). Whether its better to encrypt it. – Jayanta Kumar Nath Nov 12 '13 at 9:29
  • 1
    This is really not safe, look at this question on StackOverflow. If you are under Linux, try to use /dev/urandom (a better source of randomness than mt_rand()). – perror Nov 12 '13 at 9:39

The best way to generate random tokens for security purposes in PHP is using openssl_random_pseudo_bytes() to obtain some random bytes, and then bin2hex to make them printable.

$token = bin2hex(openssl_random_pseudo_bytes(16));

You can safely use $token for your session identifier, CSRF tokens, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.