今天會教大家如何使用Zend_Auth去驗証使用者.Zend_Auth是一個很方便而且很安全的認證module.只要配合Zend_Filter和Zend_Validate過濾和驗証使用者輸入的資料,就不用擔心使用者輸入一些奇怪的東西.Zend_Auth提供Storage功能,它會把login者的資料儲存到Session裡.
Zend_Filter的主要功能是把一些你不想要的東西拿掉,例如 HTML entities,alphabetic,white space,digit characters...etc.
Zend_Validate是用來證實使用者輸入的資料是你想要的type,例如 Not Empty,Alpha,Date,EmailAddress...etc
如果想要用到ACL的話.可以把Zend_Auth,Zend_Acl一起使用.是一個十分利害的武器.
不過今天我只會教大家如何使用Zend_Auth.
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
)
運作流程:
1. 新增login.phtml,logout.phtml,success.phtml.
2. 建立一個Auth介面,把table名,認證時候要使用到column的名設定好.
4. 建立一個Auth Object.
5. 核對使用者輸入的資料.如果成功,重導使用者到success.phtml,如果不係的話就顯示錯誤信息.
6. 重導使用者到success.phtml的時候,還要重新檢查一次使用者是否登入.
index.php<?php
set_include_path('.'.PATH_SEPARATOR.'./library/'.PATH_SEPARATOR.'./application/m odels/'); // 設定module的位置
include "Zend/Loader.php"; // 必需要include的module,它是把需要的module導入
Zend_Loader::loadClass('Zend_Controller_Front'); // Zend_Controller_Front是必需的module,它是用來控制route
Zend_Loader::loadClass('Zend_Db');
Zend_Loader::loadClass('Zend_Config_Ini');
Zend_Loader::loadClass('Zend_Registry');
Zend_Loader::loadClass('Zend_Auth'); // 加入 Auth Module
Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable'); //加入 Auth Adapter Table Module
$config = new Zend_Config_Ini('./application/config/config.ini','general'); // 引入資料庫config檔案
// 設定資料庫介面
$dbAdapter = Zend_Db::factory($config->db->adapter,$config->db->config->toArray());
Zend_Registry::set('dbAdapter',$dbAdapter);
$frontController = Zend_Controller_front::getInstance(); // create一個Front Object
$frontController->setControllerDirectory('./application/controllers'); // 設定Controller目錄的路徑
$frontController->dispatch();
IndexController.php<?php
class IndexController extends Zend_Controller_Action
{
public function init() {
$this->view->baseUrl = $this->_request->getBaseUrl(); // 設定baseUrl
}
public function indexAction()
{
// 檢查使用者是否登入
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) : // 如果登入,重導使用者到success page
$this->_redirect('/index/success');
else :
$this->_redirect('/index/login'); // 重導使用者到login page
endif;
}
public function loginAction()
{
// 檢查使用者是否登入
$auth = Zend_Auth::getInstance(); // 建立一個Auth Object
if ($auth->hasIdentity()) : // 如果登入,重導使用者到success page
$this->_redirect('/index/success');
endif;
try {
if ($this->_request->isPost()) : // 如果資料是從post傳過來,就開始做認證
$db = Zend_Registry::get('dbAdapter'); // 引入資料庫介面
// 使用者輸入的資料
$username = $this->_request->getParam('username');
$password = $this->_request->getParam('password');
$authAdapter = new Zend_Auth_Adapter_DbTable($db,'users','username','password'); // 設定Auth介面.
//@ param1: database adapter
//@ param2: table
//@ param3: username column
//@ param 4: password column
// 把使用者輸入的username and password儲存到Auth介面
$authAdapter->setIdentity($username);
$authAdapter->setCredential($password);
// 開始做認證工作
$validate = $auth->authenticate($authAdapter); // 對比使用者輸入的資料跟資料庫是否一樣
// 如果認證成功,就把table裡頭的資料寫入到Storage裡,除了password
if ($validate->isValid()) :
$auth->getStorage()->write($authAdapter->getResultRowObject(null,'password')); // 寫入到Storage裡頭
//@param1 : null代表全部column,如果你只想寫入某些資料,例如 username and realname,可以使用array,array('username','realname')
//@param2 : 不需要寫入的column,password是一個很重要的資料,千萬不要把它寫到session裡頭去.
$this->_redirect('/index/success'); // 重導使用者到success page
else :
$this->view->errorMessage = 'Login failed,Please try again.'; //如果登入失敗.重導使用者到login page,顯示失敗訊息.
endif;
endif;
}
catch(Zend_Exception $e) {
echo "Error: ".$e->getMessage();
}
}
public function logoutAction()
{
try {
Zend_Auth::getInstance()->clearIdentity(); //清除Storage裡頭的資料
$this->_redirect('/'); //重導使用者到login page
}
catch(Zend_Exception $e) {
echo "Error: ".$e->getMessage();
}
}
public function successAction()
{
// 檢查使用者是否登入
$auth = Zend_Auth::getInstance();
if (!$auth->hasIdentity()) : // 如果沒有登入,重導使用者到login page
$this->_redirect('/index/login');
endif;
}
}
login.phtml<? if (!empty($this->errorMessage)) :
echo $this->errorMessage; //顯示錯鋘訊息
endif;
?>
<form method="post" name="login" action="<?echo $this->baseUrl; ?>/index/login">
username:<input type="text" name="username" /><br>
password:<input type="password" name="password" /><br>
<input type="submit" value="login" />
</form>
success.phtml<?
echo "Login successed";
?>
<form method="post" name="logout" action="<?echo $this->baseUrl; ?>/index/logout">
<input type="submit" value="logout" />
</form>
Demo:http://wingning.no-ip.org/studyarea/zend_auth/
username: demo
password: 123456
下載:http://wingning.no-ip.org/studyarea/download/zend_auth.tar.gz天創科技網頁設計公司