phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


Zend Framework Login: Creating Authentication

Tag: framework, zend, zend framework, authentication, Zend_Auth   Category: PHP Framework
post: 22 Apr 2008 read: 5,102


Zend Framework Login System Step by Step Tutorial - Part 3: After create form login, we need authentication. Data will be checked with existing data at database.

Just remembering, login form send two parameter: username and password. They are sent to user/auth page. So, we must build authAction() at UserController.

authAction() for data validation. The data that sent by login form will be checked at authAction(). Open your "UserController.php". Firs, load Zend/Auth.php and Zend/Auth/Adapter/DbTable.php. Please place at first line before any method():


<php
require_once 'Zend/Auth.php';
require_once 'Zend/Auth/Adapter/DbTable.php';

...
>

Add authAction() like this:


  public function authAction(){
    $request 	= $this->getRequest();
    $registry 	= Zend_Registry::getInstance();
	$auth		= Zend_Auth::getInstance(); 
	
	$DB = $registry['DB'];
		
    $authAdapter = new Zend_Auth_Adapter_DbTable($DB);
    $authAdapter->setTableName('users')
                ->setIdentityColumn('username')
                ->setCredentialColumn('password');    
	
	// Set the input credential values
	$uname = $request->getParam('username');
	$paswd = $request->getParam('password');
    $authAdapter->setIdentity($uname);
    $authAdapter->setCredential(md5($paswd));

    // Perform the authentication query, saving the result
    $result = $auth->authenticate($authAdapter);

    if($result->isValid()){
	  $data = $authAdapter->getResultRowObject(null,'password');
	  $auth->getStorage()->write($data);
	  $this->_redirect('/user/userpage');
	}else{
	  $this->_redirect('/user/loginform');
	}
 }

First, load database adapter from registry (line 3, 6). If you still don't understand about this code, please read tutorial about Zend Framework Database and Zend Framework Registry.

Then, define authentication adapter:


$authAdapter = new Zend_Auth_Adapter_DbTable($DB);

Next, we define table name, column that contains username and password.


    $authAdapter->setTableName('users')
                ->setIdentityColumn('username')
                ->setCredentialColumn('password');  

Next, we catch HTTP parameter that contains username and password:


	$uname = $request->getParam('username');
	$paswd = $request->getParam('password');
    $authAdapter->setIdentity($uname);
    $authAdapter->setCredential(md5($paswd));

Next, do authentication:


    $result = $auth->authenticate($authAdapter);

    if($result->isValid()){
	  $data = $authAdapter->getResultRowObject(null,'password');
	  $auth->getStorage()->write($data);
	  $this->_redirect('/user/userpage');
	}else{
	  $this->_redirect('/user/loginform');
	}
 }

If valid user, we will save user data at session using:


	  $data = $authAdapter->getResultRowObject(null,'password');
	  $auth->getStorage()->write($data);

Then, page will be redirect to protected page (named userpage in this tutorial). Next post, we will talk about protected page. It is simple, isn't it?

Ok, this is our complete UserController:


<?php

require_once 'Zend/Controller/Action.php';
require_once 'Zend/Auth.php';
require_once 'Zend/Auth/Adapter/DbTable.php';

class UserController extends Zend_Controller_Action
{

  
  public function loginFormAction()
  {
    $request = $this->getRequest();  
	$this->view->assign('action', $request->getBaseURL()."/user/auth");  
    $this->view->assign('title', 'Login Form');
    $this->view->assign('username', 'User Name');	
    $this->view->assign('password', 'Password');	
	    
  }
  
  public function authAction(){
    $request 	= $this->getRequest();
    $registry 	= Zend_Registry::getInstance();
	$auth		= Zend_Auth::getInstance(); 
	
	$DB = $registry['DB'];
		
	$authAdapter = new Zend_Auth_Adapter_DbTable($DB);
    $authAdapter->setTableName('users')
                ->setIdentityColumn('username')
                ->setCredentialColumn('password');    
	
	// Set the input credential values
	$uname = $request->getParam('username');
	$paswd = $request->getParam('password');
    $authAdapter->setIdentity($uname);
    $authAdapter->setCredential(md5($paswd));

    // Perform the authentication query, saving the result
    $result = $auth->authenticate($authAdapter);

    if($result->isValid()){
      //print_r($result);	
	  $data = $authAdapter->getResultRowObject(null,'password');
	  $auth->getStorage()->write($data);
	  $this->_redirect('/user');
	}else{
	  $this->_redirect('/user/loginform');
	}
    	
  }
  
  
  public function nameAction()
  {
  
    $request = $this->getRequest();
    $this->view->assign('name', $request->getParam('username'));
    $this->view->assign('gender', $request->getParam('gender'));	  
		
    $this->view->assign('title', 'User Name');
  }  
  
  public function registerAction()
  {
    $request = $this->getRequest();
	
	$this->view->assign('action',"process");
    $this->view->assign('title','Member Registration');
	$this->view->assign('label_fname','First Name');
	$this->view->assign('label_lname','Last Name');	
	$this->view->assign('label_uname','User Name');	
	$this->view->assign('label_pass','Password');
	$this->view->assign('label_submit','Register');		
	$this->view->assign('description','Please enter this form completely:');		
  }
  
  public function editAction()
  {
    $registry = Zend_Registry::getInstance();  
	$DB = $registry['DB'];
	
    $request = $this->getRequest();
	$id 	 = $request->getParam("id");
	
	$sql = "SELECT * FROM `user` WHERE id='".$id."'";
	$result = $DB->fetchRow($sql);
	
	$this->view->assign('data',$result);
	$this->view->assign('action', $request->getBaseURL()."/user/processedit");
    $this->view->assign('title','Member Editing');
	$this->view->assign('label_fname','First Name');
	$this->view->assign('label_lname','Last Name');	
	$this->view->assign('label_uname','User Name');	
	$this->view->assign('label_pass','Password');
	$this->view->assign('label_submit','Edit');		
	$this->view->assign('description','Please update this form completely:');		
  }  
  
  public function processAction()
  {
  
    $registry = Zend_Registry::getInstance();  
	$DB = $registry['DB'];
	
    $request = $this->getRequest();
	$data = array('first_name' => $request->getParam('first_name'),
	              'last_name' => $request->getParam('last_name'),
				  'user_name' => $request->getParam('user_name'),
				  'password' => md5($request->getParam('password'))
	              );
    $DB->insert('user', $data);
	
    $this->view->assign('title','Registration Process');
	$this->view->assign('description','Registration succes');  	
	
  }
  
  public function listAction()
  {
    
    $registry = Zend_Registry::getInstance();  
	$DB = $registry['DB'];
	
	$sql = "SELECT * FROM `user` ORDER BY user_name ASC";
	$result = $DB->fetchAssoc($sql);
	
    $this->view->assign('title','Member List');
	$this->view->assign('description','Below, our members:');
	$this->view->assign('datas',$result);		
  
  }
  
  public function processeditAction()
  {
  
    $registry = Zend_Registry::getInstance();  
	$DB = $registry['DB'];
	
	$request = $this->getRequest();
	
	$data = array('first_name' => $request->getParam('first_name'),
	              'last_name' => $request->getParam('last_name'),
				  'user_name' => $request->getParam('user_name'),
				  'password' => md5($request->getParam('password'))
	              );
    $DB->update('user', $data,'id = '.$request->getParam('id'));	
    
    $this->view->assign('title','Editing Process');
	$this->view->assign('description','Editing succes');  	
		
  }
  
  public function delAction()
  {
    $registry = Zend_Registry::getInstance();  
	$DB = $registry['DB'];
	
	$request = $this->getRequest();
	
    $DB->delete('user', 'id = '.$request->getParam('id'));	
	
    $this->view->assign('title','Delete Data');
	$this->view->assign('description','Deleting succes');  		  
    $this->view->assign('list',$request->getBaseURL()."/user/list");  
  
  }
  
}
?>


Series this article:
Zend Framework Login: Preparing Database
Zend Framework Login: Creating Form Login
Zend Framework Login: Creating Authentication
Zend Framework Login: Fatal error Cannot use object of type stdClass as array
Zend Framework Login: Protected Page
Zend Framework Login: Creating Logout
Zend Framework Login: Creating Switching for Front Page

| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

2 Responses to Zend Framework Login: Creating Authentication:

Nice tutorial. I changed a little bit to my Zend MVC implementation and works great so far!

Thanks you very much! website is very good.

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting