1.11. Forgotten Passwords

Sometimes users will forget their passwords and not be able to log in. Since the actual password is never stored, there's no way to retrieve it for them. Instead, a new password must be generated and sent to the user's e-mail address on file. Code to accomplish this can be saved as forgotpass.php:

<?php
// include shared code
include '../lib/common.php';
include '../lib/db.php';
include '../lib/functions.php';
include '../lib/User.php';

// construct password request form HTML
ob_start();
?>
<form action="<?php echo htmlspecialchars($_SEVER['PHP_SELF']); ?>"
 method="post">
<p>Enter your username. A new password will be sent to the email address on
 file.</p>
<table>
<tr>
 <td><label for="username">Username</label></td>
 <td><input type="text" name="username" id="username"
  value="<?php if (isset($_POST['username']))
  echo htmlspecialchars($_POST['username']); ?>"/></td>
</tr><tr>
 <td> </td>
 <td><input type="submit" value="Submit"/></td>
 <td><input type="hidden" name="submitted" value="1"/></td>
</tr><tr>
</table>
</form>
<?php
$form = ob_get_clean();

// show the form if this is the first time the page is viewed
if (!isset($_POST['submitted']))
{
    $GLOBALS['TEMPLATE']['content'] = $form;
}
// otherwise process incoming data
else { // validate username if (User::validateUsername($_POST['username'])) { $user = User::getByUsername($_POST['username']); if (!$user->userId) { $GLOBALS['TEMPLATE']['content'] = '<p><strong>Sorry, that ' . 'account does not exist.</strong></p> ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.