27.5.4 修改密码

如果一个用户点击"Change Password"这个菜单选项,系统将打开如图27-7所示的表单。

27.5.4 修改密码 - 图1

图 27-7 change_passwd_form.php脚本为用户提供一个修改密码的表单

表单是由脚本change_passwd_form.php生成的。该脚本比较简单,只是调用了输出库中的一些函数,因而在这里,我们没有介绍它的源代码。

在用户提交该表单之后,将触发change_passwd.php脚本,如程序清单27-15所示。

程序清单27-15 change_passwd.php——该脚本将改变用户密码


<?php

require_once('bookmark_fns.php');

session_start();

do_html_header('Changing password');

//create short variable names

$old_passwd=$_POST['old_passwd'];

$new_passwd=$_POST['new_passwd'];

$new_passwd2=$_POST['new_passwd2'];

try{

check_valid_user();

if(!filled_out($_POST)){

throw new Exception('You have not filled out the form completely.

Please try again.');

}

if($new_passwd!=$new_passwd2){

throw new Exception('Passwords entered were not the same.

Not changed.');

}

if((strlen($new_passwd)>16)||(strlen($new_passwd)<6)){

throw new Exception('New password must be between 6 and 16 characters.

Try again.');

}

//attempt update

change_password($_SESSION['valid_user'],$old_passwd,$new_passwd);

echo'Password changed.';

}

catch(Exception$e){

echo$e->getMessage();

}

display_user_menu();

do_html_footer();

?>


以上脚本将检查用户是否已经登录(使用check_valid_user()函数),是否已经填好密码表单(使用filled_out()函数),新密码是否一致以及其长度是否符合规定。这些都不是新内容,我们已经在以前介绍过了。如果所有这些都已经完成,可以调用change_password()函数,如下所示:


change_password($_SESSION['valid_user'],$old_passwd,$new_passwd);

echo'Password changed.';


该函数来自user_auth_fns.php函数库。其源代码如程序清单27-16所示。

程序清单27-16 user_auth_fns.php文件中的change_password()函数——该函数更新数据库中的用户密码


function change_password($username,$old_password,$new_password){

//change password for username/old_password to new_password

//return true or false

//if the old password is right

//change their password to new_password and return true

//else throw an exception

login($username,$old_password);

$conn=db_connect();

$result=$conn->query("update user

set passwd=sha1('".$new_password."')

where username='".$username."'");

if(!$result){

throw new Exception('Password could not be changed.');

}else{

return true;//changed successfully

}

}


该函数调用了前面所介绍的login()函数来判断用户输入的旧密码是否正确。如果正确,函数将连接到数据库并将它更新为新密码。