1

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.

//script to return the 7th character in the string and compare it to the entered character.

Thanks in advance :)

Aiden Ryan
  • 845
  • 2
  • 11
  • 15
  • 2
    Perhaps you should start with [rand](http://php.net/manual/en/function.rand.php) and work from there? – GWW Jun 27 '11 at 03:30
  • I have, I am wondering how to select a random character from a string rather then creating one – Aiden Ryan Jun 27 '11 at 03:31
  • A quick google search gives me the PHP `substr($string, $start, [$length])` function. Did you even try to search for this? – Wylie Jun 27 '11 at 03:33

2 Answers2

4
$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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    @Aiden Ryan: The first line gets a random number from 0 to the length of the string minus 1. (e.g: if string length is 8, then it will return a random number between 0 and 7). The second line pulls that character out of your string... – NotMe Jun 27 '11 at 03:35
  • Right, I understand, the only thing I don't quite understand is the need for the subtraction of 1 number? – Aiden Ryan Jun 27 '11 at 03:42
  • @Aiden Strings, just like arrays, are zero-indexed. For a 10 character string, the first letter is at index 0, the last at index 9. `strlen` tells you *how many* characters there are. The last index is `length - 1`. That's a very common thing in programming, better get used to it soon. ;o) – deceze Jun 27 '11 at 03:46
0

Try substr, strlen and rand

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

Then compare..

shernshiou
  • 518
  • 2
  • 10