Wednesday, January 7, 2009

Zend framework Zend_Auth

We can use Zend_Auth to process user authentication.

$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) { //user already login
$this->_redirect(/*redirect url*/);

$request = $this->getRequest();
if ($request->isPost()) {
$username = trim($request->getPost('username'));
$password = trim($request->getPost('password'));
//below is the key part of authentication
//$this->db must be a db adapter
$adapter = new Zend_Auth_Adapter_DbTable($this->db, 'username', 'password', 'md5(?)');
$result = $auth->authenticate($adapter);
if ($result->isValid()) { //login successful
$auth->getStorage()->write($identity); //save itentity
} else {//login failed


logout is simple as well: Zend_Auth::getInstance()->clearIdentity(); That is it.

No comments: