Consider the following PHP code that hashes a password and then verifies it. What will be the output?
<?php $password = 'secret123'; $hash = password_hash($password, PASSWORD_DEFAULT); if (password_verify('secret123', $hash)) { echo 'Access granted'; } else { echo 'Access denied'; } ?>
Think about what password_hash and password_verify do together.
The password_hash function creates a secure hash of the password. The password_verify function checks if the given password matches the hash. Since the password matches, it prints 'Access granted'.
In PHP's password_hash function, what does the constant PASSWORD_DEFAULT represent?
Think about why PHP would choose a default algorithm.
PASSWORD_DEFAULT tells PHP to use the best available hashing algorithm at the time, which can change as better algorithms become available. It ensures your code stays secure without manual updates.
Look at this PHP code snippet. It tries to verify a password but always prints 'Access denied'. What is the problem?
<?php $password = 'mypassword'; $hash = password_hash($password, PASSWORD_DEFAULT); if (password_verify($password, '$hash')) { echo 'Access granted'; } else { echo 'Access denied'; } ?>
Check how the hash variable is used inside password_verify.
The hash is passed as a string literal '$hash' instead of the variable $hash. This means password_verify compares the password to the string '$hash', which is not the actual hash, so it fails.
Which of the following PHP code snippets correctly hashes a password and verifies it?
Look carefully for missing commas, semicolons, and argument order.
Option A is correct: it uses a comma between arguments, has semicolons, and calls password_verify with password first, then hash. Others have syntax errors or wrong argument order.
This PHP code stores user passwords hashed. It then updates the hash if the algorithm changes. How many items will be in the $users array after running this code?
<?php
$users = [
['username' => 'alice', 'hash' => password_hash('pass1', PASSWORD_DEFAULT)],
['username' => 'bob', 'hash' => password_hash('pass2', PASSWORD_DEFAULT)]
];
foreach ($users as &$user) {
if (password_needs_rehash($user['hash'], PASSWORD_DEFAULT)) {
$user['hash'] = password_hash('pass' . substr($user['username'], 0, 1), PASSWORD_DEFAULT);
}
}
// How many items in $users?
Think about whether the array changes size during the loop.
The code updates hashes in place but does not add or remove users. The array still has 2 items after the loop.