zend framework 之 登入 退出 session 會話

來源:互聯網
上載者:User

在入口檔案中加上Zend_Session::start();//啟動SESSION
UserController.php檔案:
//使用者登入
function loginAction()
{
//auth實現使用者登入
if(strtolower($_SERVER['REQUEST_METHOD'])=='post')
{
Zend_Loader::loadClass('Zend_Filter_StripTags');
$filter=new Zend_Filter_StripTags();
//表單的post值
$username = $filter->filter($this->_request->getPost('username'));
$password = $filter->filter($this->_request->getPost('pwd'));
//$validcode = $filter->filter($this->_request->getPost('validcode'));//驗證碼
//echo $validcode; exit;
if( !empty($username) )
{
$db = Zend_Registry::get('dbAdapter');
$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('m_user')//資料庫表名
// 資料庫表的列的名稱,用來表示身份。身份列必須包含唯一的值,例如使用者名稱或者e-mail地址。
->setIdentityColumn('username')
//資料庫表的列的名稱,用來表示認證。在一個簡單的身份和密碼認證scheme下,認證的值對應為密碼
->setCredentialColumn('pwd')
->setIdentity($username)//認證的值
->setCredential($password);

$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);// 執行認證查詢,並儲存結果
// 輸出身份
//echo $result->getIdentity() . "/n/n";
// 輸出結果行
//echo '<pre>';print_r($authAdapter->getResultRowObject());exit;

if( $result->isValid())//isValid() - 返回 true 若且唯若結果表示一個成功的認證嘗試
{
$data = $authAdapter->getResultRowObject(null,'password');
//echo '<pre>';print_r($data);exit;
if( $auth->hasIdentity() )//成功登入
{
//auth之後寫入session
$user = new Zend_Session_Namespace('user');
$user->name = $username;
$user->setExpirationSeconds(60);//命名空間 "user" 將在第一次訪問後 60 秒到期
echo '<h3><font color=red> 登入成功!</font></h3>';                              
}
}else{
echo '<h3><font color=red> 登入失敗,請重新登入!</font></h3>';
}
}else{
echo "<h3><font color='red'>使用者名稱不可為空,請輸入使用者名稱.</font></h3>";
}
}else{
echo '呵呵,對不起,你的操作是非法';
}
}

//使用者退出
function loginoutAction()
{
$user = new Zend_Session_Namespace('user');
$user->__unset();//銷毀session
echo '已經安全退出!';
}

//在任何地方輸出
$user = new Zend_Session_Namespace('user');
if( isset( $user->name ) )
{
echo '會員'.$user->name;
}else{
echo '遊客';
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.