create a password with a custom length and uppercase letters in php

To create a password with a custom length and uppercase letters in PHP, you can use the random_bytes() function to generate a sequence of random bytes, and then convert these bytes into characters using bin2hex().

Here is a PHP function that will generate a random password with a specified length and at least one uppercase letter:

main.php
function generate_password($length) {
    $bytes = random_bytes($length);
    $password = '';
    for ($i = 0; $i < $length; ++$i) {
        // Convert the byte to a character
        $char = chr($bytes[$i]);
        // If this is the first character, make it uppercase
        if ($i === 0) {
            $char = strtoupper($char);
        }
        $password .= $char;
    }
    return $password;
}
401 chars
15 lines

You can call this function with the desired length to generate a random password:

main.php
$password = generate_password(8);  // Generates an 8-character password
echo $password;
88 chars
3 lines

This will output a random password with the specified length, containing at least one uppercase letter.

gistlibby LogSnag