I would like to create a random string of 25 alpha-numerical characters that when ran via a cron, would print the results to a key.txt file.
What would be the best way to do it? Thank you.
There are tons of tutorials out there, one possible solution (for a learning purpose, that is) would be:
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// alternatively: implode('', array_merge(range(0,9),range('a', 'z'), range('A', 'Z')));
$length = 25;
$string = '';
for ($i = 0; $i < $length; $i++)
$string .= $chars[rand(0, strlen($chars) - 1)];
// save it to a file
file_put_contents("key.txt", $string);
I can give you answers as long as the bible on how to generate random strings but you'll be reading them and saying to yourself: "Well, this sucks.". So I'll keep it short and to the point.
// Generate random string
$randomString = uniqid();
This way it will not have to be 25 characters long as the generated string is always unique and would be a perfect key or filename.
For more information check the PHP Manual on uniqid()
.
This is easy function to resolve your problem.
Pass your length variable to define length of out put.
function random_string( $length = 25 ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$password = substr( str_shuffle( $chars ), 0, $length );
return $password;
}
PS. it's not guarantee uniqueness of each output.