开发者

Selecting a random character froma string in PHP

I'm creating a security system in PHP which requires the user to enter a certain character from their unique security key, I was wondering how it is possible to make php return a selected character from a string.

For example, the security code is 1234567, I want php to randomly select 1 character from this string, and then compare that character to the character asked for in the security process

$number = rand(1,7); // The number = 7

E.G, please enter the 7th character of your security code.

//s开发者_Go百科cript to return the 7th character in the string and compare it to the entered character.

Thanks in advance :)


$randomIndex = mt_rand(0, strlen($securityCode) - 1);
$randomChar = $securityCode[$randomIndex];

This creates a random number (mt_rand) between 0 and the last index of your string (strlen($securityCode) - 1). If your string is 10 characters long, that's a number between 0 and 9. It then takes the character at that index.


Try substr, strlen and rand

$numbers = rand(0,strlen($securitycode) - 1);
$randChar = substr($securitycode, $numbers, 1);

Then compare..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜