PHP password hash generator code example

Example 1: hash a password php

// To hash the password, use
password_hash("MySuperSafePassword!", PASSWORD_DEFAULT)
  
// To compare hash with plain text, use
password_verify("MySuperSafePassword!", $hashed_password)

Example 2: online password generator in php

<?php
function randomPassword() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

echo randomPassword();
?>

Example 3: php hash password

/* User's password. */
$password = 'my secret password';

/* Secure password hash. */
$hash = password_hash($password, PASSWORD_DEFAULT);

Example 4: password_hash

<?php
/**
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you.
 */
$password = 'idkWhatToUse';

$hashedPassword= password_hash($password, PASSWORD_DEFAULT);
?>

Example 5: php hash password

/* Include the database connection script. */
include 'pdo.php';

/* Username. */
$username = 'John';

/* Password. */
$password = 'my secret password';

/* Secure password hash. */
$hash = password_hash($password, PASSWORD_DEFAULT);

/* Insert query template. */
$query = 'INSERT INTO accounts (account_name, account_passwd) VALUES (:name, :passwd)';

/* Values array for PDO. */
$values = [':name' => $username, ':passwd' => $hash];

/* Execute the query. */
try
{
  $res = $pdo->prepare($query);
  $res->execute($values);
}
catch (PDOException $e)
{
  /* Query error. */
  echo 'Query error.';
  die();
}

Example 6: php hash password

<?php
/**
 * We just want to hash our password using the current DEFAULT algorithm.
 * This is presently BCRYPT, and will produce a 60 character result.
 *
 * Beware that DEFAULT may change over time, so you would want to prepare
 * By allowing your storage to expand past 60 characters (255 would be good)
 */
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
?>

Tags:

Php Example