PDA

View Full Version : Multiplying Strings


Lorem Ipsum
11-18-2008, 05:54 PM
I'm trying to code an improved pass generator in PHP, and I figured that it would be much simpler to do if instead of coding all 36 outcomes, I just multiplied the string by the input number.

The thing is, I tried to do this yesterday, and it isn't coming out correctly. I just get a single digit number (usually 0) instead of a clearly generated password.

The Password Generator itself (http://violetmist.aoriohoshi.com/password.php).

The main PHP for the output:

<?php
$numer = array('1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i','j','k', 'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$alpha = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u', 'v','w','x','y','z');

if ($_POST["features"] == 'alphanumeric' && $_POST["length"] > 3 && $_POST["length"] < 23)
echo $numer[rand(0,35)]*$_POST["length"];
elseif ($_POST["features"] == 'alphabetical' && $_POST["length"] > 3 && $_POST["length"] < 23)
echo $alpha[rand(0,35)]*$_POST["length"];
else
echo "One of your entries was not recognised. Please return to the form and re-fill it in.";
?>


Note: $_POST["features"] is whether the password is alphanumeric or not, and $_POST["length"] is how long it is.

I know that in Ruby you can use the .to_i function, but I'm not sure if there is anything similar for PHP.

Eevee
11-18-2008, 06:03 PM
PHP doesn't believe in operators that don't exist in C, and has no concept of numbers

you want http://www.php.net/str_repeat

of course, note that this will give you the same character repeated, not a random one each time

Butterfree
11-18-2008, 07:29 PM
Uh. Why aren't you just using a loop? In fact, what's with having those silly complicated if statements just to change the name of the array that is used - in fact, it seems a kind of a waste to be using predefined arrays in the first place, as it seems likely you could just generate a random character code, but I haven't really done that in PHP. Also, I must doubt why you're making the user input an exact string manually instead of just having radio buttons or a drop-down. And you'll get an index out of bounds error since you're generating a random number up to 35 both ways. But with the current design, I'd do it like this:

if (($_POST["features"] == 'alphanumeric' OR $_POST["features"] == 'alphabetical') AND $_POST["length"] > 3 AND $_POST["length"] < 23) {
$alpha = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u', 'v','w','x','y','z');
if ($_POST["features"] == 'alphanumeric') {
array_merge($alpha, array('0','1','2','3','4','5','6','7','8','9'));
}
for ($i = 0; $i < $length, $i++) {
echo $alpha[array_rand($alpha)];
}
}
else {
echo "One of your entries was not recognised. Please return to the form and re-fill it in.";
}