create a function to hash and salt a password in php

Here's an example function that utilizes the password_hash() function to hash and salt a password:

main.php
function hashAndSaltPassword($password) {
  // Generate a random salt
  $salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
  
  // Prefix the salt to the password and hash it with BCRYPT algorithm (default cost is 10)
  $hashedPassword = password_hash($salt . $password, PASSWORD_BCRYPT);
  
  // Return the hashed password
  return $hashedPassword;
}
351 chars
11 lines

To use the function, simply pass in the user's password:

main.php
// User inputted password
$password = "password123";

// Hash and salt the password
$hashedPassword = hashAndSaltPassword($password);

// Store the hashed password in the database
180 chars
8 lines

This function generates a random salt using mcrypt_create_iv() function, then concatenates the salt with the user's password, and finally hashes the combined string using the password_hash() function with the BCRYPT algorithm. The resulting hashed password includes the salt, so you can store it directly in the database.

related categories

gistlibby LogSnag