Header函數和PHP_AUTH_USER作用戶驗證

php Header PHP_AUTH_USER PHP_AUTH_PW 用戶驗證php

在php中,能夠使用Header函數作一些有趣的事情,用戶驗證就是其中一個頗有意思的功能。具體用法:html

Header("WWW-Authenticate: Basic realm="USER LOGIN"");mysql

Header("HTTP/1.0 401 Unauthorized");web

在頁首設計這兩個Header函數,頁面在載入前會出現一個登陸框,要求輸入用戶名和密碼。習慣了在頁面登陸的咱們,是否以爲這樣的登陸很原始,又很新奇呢?sql

爲了獲取從這個對話框中傳來的用戶名和密碼,須要用到php提供的兩個特殊變量$PHP_AUTH_USER和$PHP_AUTH_PW,要這樣使用這兩個特殊變量好像須要在php.ini中設置相關的選項,否則就只能像下面這樣引用:函數

$_SERVER['PHP_AUTH_USER']this

$_SERVER['PHP_AUTH_PW']設計

獲取到用戶提交上來的用戶名和密碼以後,要怎樣處理邏輯就跟咱們通常的程序處理沒有什麼區別了。下面提供兩個例程供參考:server

<?htm

if(!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 XXX

subscriber. If you are a subscriber and you are having trouble logging

in,

please contact <a href="mailto:support@xxx.com">support@xxx.com</a>.

</blockquote>

<?

exit;

} else {

mysql_pconnect("localhost","nobody","") or die("Unable to connect to

SQL server");

mysql_select_db("xxx") or die("Unable to select database");

$user_id=strtolower($PHP_AUTH_USER);

$password=$PHP_AUTH_PW;

$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 XXX

subscriber. If you are a subscriber and you are having trouble

logging in,

please contact <a href="mailto:support@xxx.com">support@xxx.com</a>.

</blockquote>

<?

exit;

}

$name=mysql_result($query,0,"name");

$email=mysql_result($query,0,"email");

mysql_free_result($query);

}

?>

來源頁面:http://www.weberdev.com/get_example-82.html

另一個參考的例程:

<?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

include 'db_connect.php';

//SQL query to find if this entered username/password is in the db

$sql = "SELECT * FROM healthed_workshop_admin WHERE

user = '$PHP_AUTH_USER' AND

pass = '$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('WWW-Authenticate: Basic realm="Health Ed Presentation Admin"');

header('HTTP/1.0 401 Unauthorized');

echo 'You must enter a valid username & password.';

exit;

}

else

{

echo 'Success!';

}

?>

相關文章
相關標籤/搜索