如何在PHP中生成安全字符串?

问题描述:

I am building a login system for my website, however I have always used the $_SESSION variable before for remembering people logged in, but this time they need to be remembered via cookies. The cookie will store their username and security code which I will also store in a database allowing me to confirm that they are the correct user. I have seen various approaches to this, however I would like to generate a completely secure string.

我正在为我的网站构建登录系统,但是我之前总是使用$ _SESSION变量来记住记录的人 在,但这次他们需要通过cookie记住。 cookie将存储他们的用户名和安全码,我也将其存储在数据库中,以便我确认他们是正确的用户。 我已经看到了各种方法,但是我想生成一个完全安全的字符串。 p> div>

$_SESSION already uses cookies by default, so you don't have to change anything. Just make sure the use_cookies and use_only_cookies configuration options are set to on.

A secret is usually a random number, which you can compute its md5 and put it inside a cookie, this is how I do it for one of my applications ($salt is a unique large arbitrary string):

$rnd = mt_rand( 0, 0x7fffffff ) ^ crc32( $salt ) ^ crc32( microtime() );

$secret = md5( $rnd );

if you want to make it even more secure everytime you make a $rnd save it somewhere (in DB perhaps) and shift your next $rnd by its value and save that next $rnd in the DB...

I use the ASCII code with the function chr, from the character 33 to 126.

The function is like this:

$seed = "";
for ($i = 1; $i <= 20; $i++) {
    $seed .= chr( mt_rand(33,126) );
}
return md5($seed);