PHP教程.應用實例12
Jun 21, 2016 am 09:14 AM教程|應用實例
PHP中用戶身份認證實現(xiàn)二法(1)
用戶在設計和維護站點的時候,經常需要限制對某些重要文件或信息的訪問。通常,我們可以采用內置于WEB服務器的基于HTTP協(xié)議的用戶身份驗證機制。當訪問者瀏覽受保護頁面時,客戶端瀏覽器會彈出對話窗口要求用戶輸入用戶名和密碼,對用戶的身份進行驗證,以決定用戶是否有權訪問頁面。下面用兩種方法來說明其實現(xiàn)原理。
一、用HTTP標頭來實現(xiàn)
標頭是服務器以HTTP協(xié)議傳送HTML信息到瀏覽器前所送出的字串。HTTP采用一種挑戰(zhàn)/響應模式對試圖進入受密碼保護區(qū)域的用戶進行身份驗證。具體來說,當用戶首次向WEB服務器發(fā)出訪問受保護區(qū)域的請求時,挑戰(zhàn)進程被啟動,服務器返回特殊的401標頭,表明該用戶身份未經驗證??蛻舳藶g覽器在檢測到上述響應之后自動彈出對話框,要求用戶輸入用戶名和密碼。用戶完成輸入之后點擊確定,其身份識別信息就被傳送到服務端進行驗證。如果用戶輸入的用戶名和密碼有效,WEB服務器將允許用戶進入受保護區(qū)域,并且在整個訪問過程中保持其身份的有效性。相反,若用戶輸入的用戶名稱或密碼無法通過驗證,客戶端瀏覽器會不斷彈出輸入窗口要求用戶再次嘗試輸入正確的信息。整個過程將一直持續(xù)到用戶輸入正確的信息位置,也可以設定允許用戶進行嘗試的最大次數(shù),超出時將自動拒絕用戶的訪問請求。
在PHP腳本中,使用函數(shù)header()直接給客戶端的瀏覽器發(fā)送HTTP標頭,這樣在客戶端將會自動彈出用戶名和密碼輸入窗口,來實現(xiàn)我們的身份認證功能。在PHP中,客戶端用戶輸入的信息傳送到服務器之后自動保存在 $PHP_AUTH_USER,$PHP_AUTH_PW,以及 $PHP_AUTH_TYPE這三個全局變量中。利用這三個變量,我們可以根據(jù)保存在數(shù)據(jù)文件或者數(shù)據(jù)庫中用戶帳號信息來驗證用戶身份!
不過,需要提醒使用者注意的是:只有在以模塊方式安裝的PHP中才能使用$PHP_AUTH_USER,$PHP_AUTH_PW,以及 $PHP_AUTH_TYPE這三個變量。如果用戶使用的是CGI模式的PHP則無法實現(xiàn)驗證功能。在本節(jié)后附有PHP的模塊方式安裝方法。
下面我們用Mysql數(shù)據(jù)庫來存儲用戶的身份。我們需要從數(shù)據(jù)庫中提取每個帳號的用戶名和密碼以便與$PHP_AUTH_USER和$PHP_AUTH_PW變量進行比較,判斷用戶的真實性。
首先,在MySql中建立一個存放用戶信息的數(shù)據(jù)庫
數(shù)據(jù)庫名為XinXiKu ,表名為user;表定義如下:
create table user(
ID INT(4) NOT NULL AUTO_INCREMENT,
name VARCHAR(8) NOT NULL,
password CHAR(8) NOT NULL,
PRIMARY KEY(ID)
)
說明:
1、ID為一個序列號,不為零而且自動遞增,為主鍵;
2、name為用戶名,不能為空;
3、password為用戶密碼,不能為空;
以下是用戶驗證文件login.php
//判斷用戶名是否設置
if(!isset($PHP_AUTH_USER))
{
header("WWW-Authenticate:Basic realm="身份驗證功能"");
header("HTTP/1.0 401 Unauthorized");
echo "身份驗證失敗,您無權共享網(wǎng)絡資源!";
exit();
}
/*連接數(shù)據(jù)庫*/
$db=mysql_connect("localhost","root","");
//選擇數(shù)據(jù)庫
mysql_select_db("XinXiKu",$db);
//查詢用戶是否存在
$result=mysql_query("SELECT * FROM user where name='$PHP_AUTH_USER' and password='$PHP_AUTH_PW'",$db);
if ($myrow = mysql_fetch_row($result))
{
//以下為身份驗證成功后的相關操作
...
}
else
{
//身份驗證不成功,提示用戶重新輸入
header("WWW-Authenticate:Basic realm="身份驗證功能"");
header("HTTP/1.0 401 Unauthorized");
echo "身份驗證失敗,您無權共享網(wǎng)絡資源!";
exit();
}
?>
程序說明:
在程序中,首先檢查變量$PHP_AUTH_USER是否已經設置。如果沒有設置,說明需要驗證,腳本發(fā)出HTTP 401錯誤號頭標,告訴客戶端的瀏覽器需要進行身份驗證,由客戶端的瀏覽器彈出一個身份驗證窗口,提示用戶輸入用戶名和密碼,輸入完成后,連接數(shù)據(jù)庫,查詢該用用戶名及密碼是否正確,如果正確,允許登錄進行相關操作,如果不正確,繼續(xù)要求用戶輸入用戶名和密碼。
函數(shù)說明:
1、isset():用于確定某個變量是否已被賦值。根據(jù)變量值是否存在,返回true或false
2、header():用于發(fā)送特定的HTTP標頭。注意,使用header()函數(shù)時,一定要在任何產生實際輸出的HTML或PHP代碼前面調用該函數(shù)。
3、mysql_connect():打開 MySQL 服務器連接。
4、mysql_db_query():送查詢字符串 (query) 到 MySQL 數(shù)據(jù)庫。
5、mysql_fetch_row():返回單列的各字段。
二、用session實現(xiàn)服務器驗證
對于需要身份驗證的頁面,使用apache服務器驗證是最好不過的了。但是,apache服務器驗證的界面不夠友好。而且,cgi模式的php,iis下的php,都不能使用apache服務器驗證。這樣,我們可以利用session在不同頁面間保存用戶身份,達到身份驗證的目的。
在后端我們同樣利用上面的Mysql數(shù)據(jù)庫存放用戶信息。
我們先編寫一個用戶登錄界面,文件名為login.php,代碼職下:
____________________________________________________________
____________________________________________________________
login1.php處理提交的表單,代碼如下:
$db=mysql_connect("localhost","root","");
mysql_select_db("XinXiKu",$db);
$result=mysql_query("SELECT * FROM user where name='$name' and password='$pass'",$db);
if ($myrow = mysql_fetch_row($result))
{
//注冊用戶
session_start();
session_register("user");
$user=$myrow["user"];
// 身份驗證成功,進行相關操作
...
}
else
{
echo"身份驗證失敗,您無權共享網(wǎng)絡資源!";
}
?>
這里需要說明的是,用戶可以使用在后續(xù)的操作中用**http://domainname/next.php?user=用戶名 **來繞過身份驗證。所以,后續(xù)的操作應先檢查變量是否注冊:已注冊,則進行相應操作,否則視為非法登錄。相關代碼如下:
session_start();
if (!session_is_registered("user"))
{
echo "身份驗證失敗,屬于非法登錄!";
}
else
{
//成功登錄進行相關操作
...
}
?>
附錄:PHP以模塊方式安裝方法
1、首先下載文件:mod_php4-4.0.1-pl2。[如果你的不是PHP4,那么就趕快升級吧!]
解開后有三個文件:mod_php4.dll、mod_php4.conf、readme.txt
2、相關文件拷貝
把mod_php4.dll拷貝到apache安裝目錄的modules目錄下面
把mod_php4.conf拷貝到apache安裝目錄的conf目錄下面
把msvcrt.dll文件拷貝到apache的安裝目錄下面
3、打開conf/srm.conf文件 ,在其中加上一句
Include conf/mod_php4.conf
在做這一些之前請把您的httpd.conf中關于CGI模式的所以設置語句都去掉,即類似下面的部分!
ScripAlias /php4/ "C:/php4/"
AddType application/x-httpd-php4 .php

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

When writing PHP comments, you should clarify the purpose, logic and structure. 1. Each function and class uses DocBlock format to explain the role, parameters and return values; 2. Explain "why" in the key logic rather than just "what was done"; 3. Add a brief description at the top of the file, including functions, dependencies and usage scenarios; 4. Avoid nonsense comments, add only necessary instructions before complex logic, and do not record the modification history. This improves code readability and maintenance efficiency.

Comments should explain "why" rather than "what was done", such as explaining business reasons rather than repeating code operations; 2. Add overview comments before complex logic, briefly explaining the process steps to help establish an overall impression; 3. Comments the "strange" code to explain the intention of unconventional writing, and avoid misunderstandings as bugs; 4. Comments are recommended to be concise, use // in single lines, use // in functions/classes/*.../ in order to maintain a unified style; 5. Avoid issues such as out of synchronization with the comments, too long comments or not deletion of the code, and ensure that the comments truly improve the readability and maintenance of the code.

When using if/else control structure for conditional judgment in PHP, the following points should be followed: 1. Use if/else when different code blocks need to be executed according to the conditions; 2. Execute if branches if the condition is true, enter else or elseif if they are false; 3. When multi-conditional judgment, elseif should be arranged in logical order, and the range should be placed in front of the front; 4. Avoid too deep nesting, it is recommended to consider switch or reconstruction above three layers; 5. Always use curly braces {} to improve readability; 6. Pay attention to Boolean conversion issues to prevent type misjudgment; 7. Use ternary operators to simplify the code in simple conditions; 8. Merge and repeat judgments to reduce redundancy; 9. Test boundary values to ensure the complete logic. Mastering these techniques can help improve code quality and stability.

PHP string processing requires mastering core functions and scenarios. 1. Use dot numbers or .= for splicing, and recommend arrays for splicing large amounts of splicing; 2. Use strpos() to search, replace str_replace(), pay attention to case sensitivity and regular usage conditions; 3. Use substr() to intercept, and use sprintf() to format; 4. Use htmlspecialchars() to output HTML, and use parameterized query to database operations. Familiar with these function behaviors can deal with most development scenarios.

The "undefinedindex" error appears because you try to access a key that does not exist in the array. To solve this problem, first, you need to confirm whether the array key exists. You can use isset() or array_key_exists() function to check; second, make sure the form data is submitted correctly, including verifying the existence of the request method and field; third, pay attention to the case sensitivity of the key names to avoid spelling errors; finally, when using hyperglobal arrays such as $_SESSION and $_COOKIE, you should also first check whether the key exists to avoid errors.

There are two ways to correctly use PHP annotation: // or # for single-line comments, and /.../ for multi-line comments. PHP syntax requires attention to the fact that each statement ends with a semicolon, add $ before the variable name, and case sensitivity, use dots (.) for string splicing, and maintain good indentation to improve readability. The PHP tag specification is for use to avoid unnecessary gaps. Mastering these basic but key details can help improve code quality and collaboration efficiency.

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

The key to writing PHP comments is to explain "why" rather than "what to do", unify the team's annotation style, avoid duplicate code comments, and use TODO and FIXME tags reasonably. 1. Comments should focus on explaining the logical reasons behind the code, such as performance optimization, algorithm selection, etc.; 2. The team needs to unify the annotation specifications, such as //, single-line comments, function classes use docblock format, and include @author, @since and other tags; 3. Avoid meaningless annotations that only retell the content of the code, and should supplement the business meaning; 4. Use TODO and FIXME to mark to do things, and can cooperate with tool tracking to ensure that the annotations and code are updated synchronously and improve project maintenance.
