作者 主題: php下的MVC [Zend Framework] Part 3 登入認證  (閱讀 15242 次)

0 會員 與 1 訪客 正在閱讀本文。

uberr

  • 懷疑的國中生
  • **
  • 文章數: 62
    • 檢視個人資料
    • 天創科技網頁設計公司
今天會教大家如何使用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
(&#39;.&#39;.PATH_SEPARATOR.&#39;./library/&#39;.PATH_SEPARATOR.&#39;./application/m                                              odels/&#39;); // 設定module的位置
include "Zend/Loader.php"// 必需要include的module,它是把需要的module導入

Zend_Loader::loadClass(&#39;Zend_Controller_Front&#39;); // Zend_Controller_Front是必需的module,它是用來控制route
Zend_Loader::loadClass(&#39;Zend_Db&#39;);
Zend_Loader::loadClass(&#39;Zend_Config_Ini&#39;);
Zend_Loader::loadClass(&#39;Zend_Registry&#39;);
Zend_Loader::loadClass(&#39;Zend_Auth&#39;); // 加入 Auth Module
Zend_Loader::loadClass(&#39;Zend_Auth_Adapter_DbTable&#39;); //加入 Auth Adapter Table Module

$config = new Zend_Config_Ini(&#39;./application/config/config.ini&#39;,&#39;general&#39;); // 引入資料庫config檔案

// 設定資料庫介面
$dbAdapter Zend_Db::factory($config->db->adapter,$config->db->config->toArray());
Zend_Registry::set(&#39;dbAdapter&#39;,$dbAdapter);

$frontController Zend_Controller_front::getInstance(); // create一個Front Object
$frontController->setControllerDirectory(&#39;./application/controllers&#39;); // 設定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(&#39;/index/success&#39;);
               
else :
 
        $this->_redirect(&#39;/index/login&#39;); // 重導使用者到login page
       endif;
    }

    public function 
loginAction()
    {
               
// 檢查使用者是否登入
$auth Zend_Auth::getInstance(); // 建立一個Auth Object

        if ($auth->hasIdentity()) : // 如果登入,重導使用者到success page
      $this->_redirect(&#39;/index/success&#39;);
                
endif;

try {
if ($this->_request->isPost()) : // 如果資料是從post傳過來,就開始做認證

$db Zend_Registry::get(&#39;dbAdapter&#39;); // 引入資料庫介面
                                // 使用者輸入的資料
$username $this->_request->getParam(&#39;username&#39;);
$password $this->_request->getParam(&#39;password&#39;);

$authAdapter = new Zend_Auth_Adapter_DbTable($db,&#39;users&#39;,&#39;username&#39;,&#39;password&#39;); // 設定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,&#39;password&#39;)); // 寫入到Storage裡頭
//@param1 : null代表全部column,如果你只想寫入某些資料,例如 username and realname,可以使用array,array(&#39;username&#39;,&#39;realname&#39;)
//@param2 : 不需要寫入的column,password是一個很重要的資料,千萬不要把它寫到session裡頭去.

$this->_redirect(&#39;/index/success&#39;); // 重導使用者到success page
else :
$this->view->errorMessage = &#39;Login failed,Please try again.&#39;; //如果登入失敗.重導使用者到login page,顯示失敗訊息.
endif; 
endif;
      
}
catch(Zend_Exception $e) {
echo "Error: ".$e->getMessage();
}
    }

    public function 
logoutAction()
    {
try {
Zend_Auth::getInstance()->clearIdentity(); //清除Storage裡頭的資料
$this->_redirect(&#39;/&#39;); //重導使用者到login page
      
}
catch(Zend_Exception $e) {
echo "Error: ".$e->getMessage(); 
}
    }

public function successAction()
{
               // 檢查使用者是否登入
$auth Zend_Auth::getInstance();

if (!$auth->hasIdentity()) : // 如果沒有登入,重導使用者到login page
$this->_redirect(&#39;/index/login&#39;);
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

天創科技網頁設計公司
« 上次編輯: 2011-10-03 15:08 由 uberr »