Challenge 2 — Solution Task: Write a function verifyAndUpgradePassword(string $password, string &$storedHash): bool that returns false immediately if the password doesn't verify, otherwise checks password_needs_rehash() and updates $storedHash (passed by reference) with a freshly generated hash if needed, then returns true. Explain in a comment why $storedHash needs to be passed by reference here. " : "Login failed.
"; echo "Hash after check: " . $userHash; // Why $storedHash needs to be passed by reference: // The whole point of this function is to potentially UPDATE the // caller's own stored hash value in place - if it were passed by // value (the normal PHP default), the function would only ever be // able to modify its own local COPY of $storedHash, and that // change would be completely invisible to the calling code once // the function returned. Passing by reference (&$storedHash) means // the function can directly modify the exact same variable the // caller passed in, so the caller's own $userHash variable // genuinely ends up holding the freshly generated hash - ready to // be saved back to the database - without needing the function to // return a second value or the caller to manually reassign // anything itself. ?> Output: Login successful. Hash after check: $2y$10$...(a real bcrypt hash string)... Notes: - The function returns false immediately (a genuine early return) if the password doesn't even verify - there's no reason to check password_needs_rehash() at all for a password that was wrong to begin with. - password_needs_rehash() only returns true if $storedHash was created with older, weaker settings than PHP's current PASSWORD_DEFAULT - in many real runs (like this example, where the hash was just freshly created with PASSWORD_DEFAULT moments earlier), it would actually return false, and $storedHash would be left unchanged - the rehash only happens when genuinely needed. - In a real login flow, the calling code would save $userHash back to the database only if it actually changed - comparing the value before and after the call, or simply always re-saving it, since an unnecessary re-save of an identical hash is harmless.