php使用Header函数,PHP_AUTH_PW和PHP_AUTH_USER做用户验证的方法。具体如下:
在php中,可以使用Header函数做一些有趣的事情,用户验证就是其中一个很有意思的功能。具体用法:
|
1
2
|
Header("WWW-Authenticate: Basic realm="USER LOGIN""); |
在页首设计这两个Header函数,页面在载入前会出现一个登录框,要求输入用户名和密码。习惯了在页面登录的我们,是否觉得这样的登录很原始,又很新奇呢?
为了获取从这个对话框中传来的用户名和密码,需要用到php提供的两个特殊变量$PHP_AUTH_USER和$PHP_AUTH_PW,要这样使用这两个特殊变量好像需要在php.ini中设置相关的选项,不然就只能像下面这样引用:
|
1
2
|
$_SERVER['PHP_AUTH_USER']$_SERVER['PHP_AUTH_PW'] |
获取到用户提交上来的用户名和密码之后,要怎样处理逻辑就跟我们一般的程序处理没有什么区别了。下面提供两个例程供参考:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<?phpif(!isset($PHP_AUTH_USER)) {Header("WWW-authenticate: basic realm="XXX"");Header("HTTP/1.0 401 Unauthorized");$title="Login Instructions";?><blockquote>In order to enter this section of the web site, you must be an XXXsubscriber. If you are a subscriber and you are having trouble loggingin,please contact <a href="mailto:support@xxx.com">support@xxx.com</a>.</blockquote><?phpexit;} else {mysql_select_db("xxx") or die("Unable to select database");$user_id=strtolower($PHP_AUTH_USER);$query = mysql_query("select * from users where user_id='$user_id' and password='$password'");if(!mysql_num_rows($query)) {Header("WWW-authenticate: basic realm="XXX"");Header("HTTP/1.0 401 Unauthorized");$title="Login Instructions";?><blockquote>In order to enter this section of the web site, you must be an XXXsubscriber. If you are a subscriber and you are having troublelogging in,please contact <a href="mailto:support@xxx.com">support@xxx.com</a>.</blockquote><?phpexit;}$name=mysql_result($query,0,"name");$email=mysql_result($query,0,"email");mysql_free_result($query);}?> |
另外一个参考的例程:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<?php//assume user is not authenticated$auth = false;$user = $_SERVER['PHP_AUTH_USER'];$pass = $_SERVER['PHP_AUTH_PW'];if ( isset($user) && isset($pass) ){//connect to db//SQL query to find if this entered username/password is in the db$sql = "SELECT * FROM healthed_workshop_admin WHEREuser = '$PHP_AUTH_USER' ANDpass = '$PHP_AUTH_PW'";//put the SQL command and SQL instructions into variable$result = mysql_query($sql) or die('Unable to connect.');//get number or rows in command; if more than 0, row is found$num_matches = mysql_num_rows($result);if ($num_matches !=0){//matching row found authenticates user$auth = true;}}if (!$auth){header('HTTP/1.0 401 Unauthorized');echo 'You must enter a valid username & password.';exit;}else{echo 'Success!';}?> |
© 版权声明
本文刊载的所有内容,包括文字、图片、音频、视频、软件、程序、以及网页版式设计等部门来源于互联网,版权均归原作者所有!本网站提供的内容服务于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯本网站及相关权利人的合法权利。
联系信息:邮箱aoxolcom@163.com或见网站底部。
联系信息:邮箱aoxolcom@163.com或见网站底部。
THE END
















请登录后发表评论
注册
社交帐号登录