I am trying to set up a random password generator function in php but this is not working for me. I get the error:
Notice: Array to string conversion in C:\xampp\htdocs\php-testing\index.php on line 12
Array
What am I doing wrong?
<?php
function pwGenerator($len = 10) {
$charRange = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$%^&*()";
$pw = array();
$length = strlen($charRange);
for ($x = 0; $x < $len; $x++) {
$n = rand(0, $length);
$pw[] = $charRange[$n];
}
return $pw;
}
echo pwGenerator();
This is how I would do it. Not only is it fast, it is significantly more random (and thus secure) than some of the others, due to allowing characters to repeat and using
mt_rand()
.Declaring
$chars
and$charsLength
asstatic
may be overkill, but it does result in a performance improvement. Additionally,mt_rand()
is more secure thanrand()
.The original error you received about "array to string conversion" is because you returned an array from your function. If you wanted to fix this, just change:
To:
try this
you should define $pw as string not array
and
$pw.=
to concatenate the string sequence like thisi think here your mistake is no need to declare
$pw
as array declare as normal string variable. try below code is working.your are return single password string value so no need to decalre as Array simple declare string variable. may it helps you.
Reliable passwords You can only make from ascii characters a-zA-Z and numbers 0-9. To do that best way is using only cryptographically secure methods, like random_int() or random_bytes() from PHP7. Rest functions as base64_encode() You can use only as support functions to make reliability of string and change it to ASCII characters.
rand() is not secure and is very old. From any string You must use random_int(). From binary string You should use base64_encode() to make binary string reliable or bin2hex, but then You will cut byte only to 16 positions (values). See my implementation of this functions.
You cannot convert array into string directly. So instead of storing it in array you can attach characters with a string. and now it is working.
A faster approach might be to shuffle a character set then grab a string of the proper length.
Borrowed from https://stackoverflow.com/a/21768419/2712737