How to Work with Zend Auth of Zend Framework

You cann’t imagine how easy to work with authorization process in Zend Framework. We have to take help of  Zend_Auth.

Steps to get start with Zend_Auth

  • Get your Database Instance
  • Get Zend_Auth Instance
  • Get your submitted userid/password by post or get method
  • Create Auth Adapter for Database connectivity
  • Tell the adapter about the table,user name DB column,password DB column of the login table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public function authAction()
{
    $db = Zend_Db_Table::getDefaultAdapter();
    $request     = $this->getRequest();
    $auth        = Zend_Auth::getInstance();
    $authAdapter = new Zend_Auth_Adapter_DbTable($db);
    $authAdapter->setTableName('users')
                ->setIdentityColumn('username')
                ->setCredentialColumn('password');
 
    $uname = $request->getParam('username');
    $paswd = $request->getParam('password');
    $authAdapter->setIdentity($uname);
    $authAdapter->setCredential(md5($paswd));
 
    $result = $auth->authenticate($authAdapter);
 
    if($result->isValid())
    {
       $data = $authAdapter->getResultRowObject(null,'password');
       $auth->getStorage()->write($data);
       $this->_redirect('/user/myprofile');
    }
    else
    {
       foreach ($result->getMessages() as $message)
       {
         $this->view->err = $message;
       }
    }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<form action="<?php echo $this->baseUrl('login')?>" method="post">
<table width="50%" align="center">
<tbody>
<tr>
<td style="color: red; font-weight: bold;" colspan="2" align="center">
< ?php echo $this->err; ?></td>
</tr>
<tr>
<td align="left">User Name:</td>
<td align="left">
<input name="username" type="text" value="<?php $this-/>data['username']?>" /></td>
</tr>
<tr>
<td align="left">Password:</td>
<td align="left">
<input name="password" type="password" /></td>
</tr>
<tr>
<td align="left">
</td>
<td align="left">
<input name="login" type="submit" value="login" /></td>
</tr>
</tbody>
</table>
</form>