Generating a salt in PHP

This is easier in PHP 7: Just use $salt = random_bytes($numberOfDesiredBytes); to generate a salt.

What do you need a salt for, anyway? If it's for passwords, just use password_hash() and password_verify().


Note: mcrypt has been deprecated in PHP 7.1. Skip to the up-to-date answer.

You can use the function mycrypt_create_iv(), since PHP Version 5.3 it also uses the random source on a Windows server (not only on Unix). Before using it, you should check if the constant MCRYPT_DEV_URANDOM is defined.

mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);

Unlike random, urandom does not block the server, if there is not enough entropy available. Since the password salt should be unique (not necessarily random), urandom seems to be a good choice to me.


Note: mcrypt has been deprecated in PHP 7.1. Skip to the up-to-date answer.

You might want to take a look at the documentation (and comments) for mcrypt_create_iv().