大家在浏览网站的时候,常常会遇到某些网页会需要用户和密码的验证,这就需要我们编写相应的身份验证程序来实现此功能。以下是我的一些学习过程和体会,希望对大家有所帮助。
(一)、基于http验证的单用户身份验证:
我们利用函数header()发送http标头强制进行验证,客户端浏览器则弹出要输入用户名和密码的对话框,这时客户端的用户输入的信息,被传送到服务端之后保存为$php_auth_user, $php_auth_pw这两个全局变量中。利用这些变量,就可以进行用户和密码的验证。
下面的程序可以进行简单的身份验证
<?
if ($php_auth_user!='jane'||$php_auth_pw!='123456')
{
header("www-authenticate: basic realm=\"爆米花登陆\"");
header("http/1.0 401 unauthorized");
echo "身份验证错误!";
exit;
}
?>
(注意:使用http验证的时候,必须以apache的模块方式运行,如果使用的是cgi模式的php则无法实现基于http的验证功能。)
(二)基于http的多用户验证
上次给大家介绍了基于http的单用户验证,这次利用mysql数据库
储存多用户数据,进行多用户验证。
1、首先建立mysql数据库
mysql>create database user; //建立数据库user
mysql>use user; //打开数据库user
mysql>create table user_data( //建立数据表user_data
id int(9) not null aoto_increment, //id为自动增加整数字段
username varchar(10) not null, //用户姓名
password varcher(10) not noll, //密码
primary key(id); //设id为主键
);
2、身份验证程序
<?php
$error = "/www/error/error.php";
if ($php_auth_pw=="") //如密码为空
{
header("www-authenticate: basic realm=\"用户登陆\"");
header("http/1.0 401 unauthorized"); //验证
include($error); //定向error,php文件
exit;
}
else
{
mysql_connect("localhost", "root", "1234"); //连接数据库
$result = mysql_db_query("user","select password
from user_data where username='$php_auth_user'");
//送查询字符串到mysql数据库中
$row = mysql_fetch_array($result); //返回数组资料
$passwd = $row[0];
mysql_close($db_id); //关闭数据库
if ($php_auth_pw!=$passwd) //密码验证
{
header("www-authenticate: basic realm=\"用户登陆\"");
header("http/1.0 401 unauthorized");
include($error);
exit;
}
}
前面讲了基于http多用户验证,我们采用的mysql数据库,在密码验证方面孤狼大哥建议非常好,密码验证的时候,最好在数据库中进行,所以程序为:select id from user where user='$php_auth_user' and password='$php_auth_user'.
大家好,前面几节讲了这个基于http单用户和多用户的密码验证的编写程序的方法,这种方法对于需要身份验证的页面,是最好不过的了。但是,这种验证不能在cgi模式的php,iis下的php使用。所以,我们就可以利用session在不同页面之间来保存用户信息,达到验证的目的。
session是指一个终端用户与交互系统进行通信的时间间隔,通常指从注册进入系统到注销退出系统之间所经过的时间。session功能是它通过php脚本中定义全局变量的方法,使得这个全局变量在同一session中所有的php脚本都有效。
以下为用户登陆表单处理程序:
<?
$db=mysql_connect("localhost","root","1234");
//连接数据库服务器
mysql_select_db("jane",$db);
//连接数据库
$result=mysql_query("select * from user where name='$name' and password='$pass'",$db);
//送查询是字符串到数据库
if ($myrow = mysql_fetch_row($result))
//如果记录指针为真
{
session_start(); //session初始化
session_register("user");//注册user变量
$user=$myrow["user"];
echo "验证成功!";
}
else
{
echo"身份验证失败!";
}
?>
将下面的程序加入要保护的页面开头:
<?
session_start();
if (!session_is_registered("user"))//检查session变量是否注册
{
echo "验证失败,属非法登录!";
}
else
{
......
}
?>