开发者

How do you generate a security string in PHP?

开发者 https://www.devze.com 2023-03-25 09:45 出处:网络
I am building a login system for my website, however I have always used the $_SESSION variable before for remembering people l开发者_JAVA技巧ogged in, but this time they need to be remembered via cook

I am building a login system for my website, however I have always used the $_SESSION variable before for remembering people l开发者_JAVA技巧ogged 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 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);


You could make a Cryptographically Secure Random String as suggested here

Here you generate a 32charater long string contaning (A-Z) & (0-9)

$token = bin2hex(openssl_random_pseudo_bytes(16));

# or in php7
$token = bin2hex(random_bytes(16));
0

精彩评论

暂无评论...
验证码 换一张
取 消