The assumption is that only logged-in users are allowed to change their passwords. So the script checks for the existence of the $_SESSION['first_name'] variable. If it is not set, the users cannot change the passwords.
<?php
// This is the change password page
include ('start.php');
if (isset($_POST['submit'])) {
process_form();
}
else {
display_form();// display form for the first time
}
function display_form() {
echo <<<HTML
<h2>Change Password</h2>
<form action = "$_SERVER[SCRIPT_NAME]" method="post">
New Password:
<input type="password" name="password1" size="20" maxlength="20"/>
<br />
Confirm Password <br /><small>(must be between 4 and 20 characters)</small>:
<input type="password" name="password2" size="20" maxlength="20"/>
<br />
<input type="submit" name="submit" value="Register" />
</form>
HTML;
}
function process_form() {
if (isset($_SESSION['first_name'])) {
// connect to the database server
include ('db_connect.php');
// check for a new password and match against the confirmed password
$p = FALSE;
if (preg_match('/^\w{4,20}$/', $_POST['password1'])) {
if ($_POST['password1'] == $_POST['password2']) {
// Escapes special characters in the password for use in a SQL statement
$p = mysql_real_escape_string($_POST['password1']);
}
else {
echo '<p>Your password did not match the confirmed password!</p>';
}
}
else {
echo '<p>Please enter a valid password!</p>';
}
if ($p) {
//Use SHA1() function to encrypt the password
// Calculate the sha1 hash of a password
// http://www.faqs.org/rfcs/rfc3174
$newp = SHA1('$p');
// create the query
$query = "UPDATE " . TABLE_NAME . " SET pass= " . "'$p' WHERE user_id={$_SESSION['user_id']} LIMIT 1";
// run the query
$r = mysql_query($query) or trigger_error("Query: $query<br />MySQL Error: " . mysql_error());
// if data
if (mysql_affected_rows($link) == 1) {
// if it ran OK
//send the email
$body = "Your password has been changed to $p. Please login using this password and this email.\n\n";
mail($_POST['email'], 'Your new password', $body, 'From: hso@voyager.deanza.edu');
// finish the page
echo '<h3>Your password has been changed.</h3>';
}
else { // not OK
echo '<p>Sorry, but your password was not changed. Make sure your new password is different from the current password..</p>';
}
}
else {
// if the password is invalid
echo '<p> Please try again.</p>';
display_form();
}
// include the footer
include('footer.html');
// close the connection
mysql_close($link);
}
?>
|