Zend Framework Tutorial- simple signup and login authentication

17 Jan

After writing separate articles on different Zend framework topics, its now time to write a full fledge tutorials. I am starting from a simple sign up and login authentication example and hopefully will discuss some advance topic in future.

So lets get started.

First create a table in your database by executing the following sql query.

CREATE TABLE ‘users’ (

‘id’ int(11) NOT NULL auto_increment,

‘firstname’ varchar(100) default NULL,

‘lastname’ varchar(100) default NULL,

’email’ varchar(255) NOT NULL,

‘username’ varchar(100) NOT NULL,

‘password’ varchar(15) NULL,



Next create a model against this table in your application/model/ directory. I am creating Users.php and writing the following code in it.


class Users extends Zend_Db_Table


protected $_name=”users”;



Now create a controller named AuthController.php in application/controllers/ directory and place the following code in it


class AuthController extends Zend_Controller_Action


public function loginAction()



public function signupAction()



public function logoutAction()



public function homeAction()





Sorry this blog is deprecated.

“Read new version of this article here”.http://zendgeek.blogspot.com/2009/07/zend-framework-sign-up-and.html


13 Responses to “Zend Framework Tutorial- simple signup and login authentication”

  1. ronnie January 22, 2009 at 10:35 am #

    Hey I am trying to install this form on my site and and looks like it works but the actual forms are not showing up on the site. Can you help with this.

  2. Kelly January 22, 2009 at 1:00 pm #

    Great tutorial.. I’m getting errors of missing user Class etc but I assume that is due to not setting the model in the controller. I heop you have time to finish this tutorial up to a working version it would be very nice to see it.

  3. paolo January 22, 2009 at 6:46 pm #

    hola no hablo ingles y escribo menos hojala puedas entenderme y ayudarme todo anda okey menos el logout se hacen persistentes en el navegador las cookies del usuario y se siguen mostrando sus datos despues de hacer el logout no se cual podria ser el problema por fis si podrias ayudarme este es mi codigo

    "Not existent identity. A record with the supplied identity could not be found.",
    self::INVALID_CREDENTIAL => "Invalid credential. Supplied credential is invalid.",
    self::INVALID_USER => "Invalid User. Supplied credential is invalid",
    self::INVALID_LOGIN => "Invalid Login. Fields are empty"

    * @param string $messageString
    * @param string $messageKey OPTIONAL
    * @return UserModel
    * @throws Exception
    public function setMessage($messageString, $messageKey = null)
    if ($messageKey === null) {
    $keys = array_keys($this->_messages);
    $messageKey = current($keys);
    if (!isset($this->_messages[$messageKey])) {
    throw new Exception("No message exists for key '$messageKey'");
    $this->_messages[$messageKey] = $messageString;
    return $this;

    * @param array $messages
    * @return UserModel
    public function setMessages(array $messages)
    foreach ($messages as $key => $message) {
    $this->setMessage($message, $key);
    return $this;

    public function login($nick, $password)
    if (! empty ( $nick ) && ! empty ( $password )) {
    Zend_Loader::loadClass ( 'Zend_Auth_Adapter_DbTable' );
    $autAdapter = new Zend_Auth_Adapter_DbTable ( self::getAdapter () );
    $autAdapter->setTableName ( 'persona' );
    $autAdapter->setIdentityColumn ( 'identificador' );
    $autAdapter->setCredentialColumn ( 'contrasenia' );
    $autAdapter->setIdentity ( $nick );
    $autAdapter->setCredential ( md5 ( $password ) );
    $autAdapter->setCredentialTreatment(" AND estado='Activo'");
    $auth = Zend_Auth::getInstance ();
    $result = $auth->authenticate ( $autAdapter );
    switch ($result->getCode ())
    case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND :
    throw new Exception($this->_messages [self::NOT_IDENTITY]);

    case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID :
    throw new Exception ( $this->_messages [self::INVALID_CREDENTIAL] );

    case Zend_Auth_Result::SUCCESS :
    if ($result->isValid ()) {
    $storage = new Zend_Auth_Storage_Session();
    $storage->write($autAdapter->getResultRowObject ());
    } else {
    throw new Exception ( $this->_messages [self::INVALID_USER] );

    default :
    throw new Exception ( $this->_messages [self::INVALID_LOGIN] );
    } else {
    throw new Exception ( $this->_messages [self::INVALID_LOGIN] );
    return $this;

    public static function logout() {
    $storage = new Zend_Auth_Storage_Session();
    return $this;

    public static function getIdentity()
    $auth = Zend_Auth::getInstance();
    if ($auth->hasIdentity()) {
    return $auth->getIdentity();
    return null;

    public static function isLoggedIn()
    return Zend_Auth::getInstance()->hasIdentity();

    y este es el controler

    view->baseUrl = $this->_request->getBaseUrl();
    $this->user = new PersonaModel();

    public function getForm() {
    return new LoginForm ( array ('action' => '/index/login/', 'method' => 'post' ) );

    public function preDispatch() {
    if (PersonaModel::isLoggedIn()) {
    $this->view->loggedIn = true;
    $this->view->user = PersonaModel::getIdentity();

    public function indexAction() {
    $this->view->headTile = "Index Page";
    $this->view->form = $this->getForm ();

    public function loginAction() {
    $form = new LoginForm();
    if ($this->_request->isPost()) {
    $credentials = $this->_request->getPost();
    if ($form->isValid($credentials)) {
    $this->user->setMessage('El nombre de Usuario y Password no coinciden.', PersonaModel::NOT_IDENTITY);
    $this->user->setMessage('La contraseña ingresada es incorrecta. Inténtelo de nuevo.', PersonaModel::INVALID_CREDENTIAL);
    $this->user->setMessage('Los campos de Usuario y Password no pueden dejarse en blanco.', PersonaModel::INVALID_LOGIN);
    $this->user->login($credentials['username'], $credentials['password']);
    } catch(Exception $e){
    echo $responseLogin = $e->getMessage();
    $this->view->responseLogin = $responseLogin;

    public function logoutAction() {


    hojala puedas ayudarme gracias please help me

  4. Faheem Abbas January 22, 2009 at 7:26 pm #

    However extremely sorry Paolo. Although I love spanish, but can’t understand.
    I tried few months back to learn it, however didn’t succeeded.

  5. biophonc January 27, 2009 at 1:14 pm #

    Thanks a lot – works like charm for me – at least my modification of it 🙂

  6. jack March 8, 2009 at 4:16 pm #

    Hi, firstly, thanks for the tutorial!

    I am wondering how I would use if statements in the home.phtml file. I want to display different content depending on whether somebody is logged in or not, using something like:

    You’re logged in.

    I removed the…


    … so it wouldn’t redirect to login if not logged in on the index page.

    Any ideas? Thanks again.


  7. jack March 8, 2009 at 4:20 pm #

    I’m sorry, I always forget about code stripping..

    You're logged in.

    Thats what it should be.

  8. Prashant April 1, 2009 at 5:19 am #

    Its a great tutorial. It helped me to get the basic of zend.

    I have faced a issue while implementing this

    When I execute the application with the url
    “http://localhost/Auth/signup” it shown me an error but I fixed it by including the “RegistrationForm.php” file in the AuthController.php file.

    I was wondering is I have missed something or is this the right way to do this?
    Kindly confirm.


  9. Faheem Abbas April 2, 2009 at 8:13 am #

    Correct. but better to use autoload function provided by Zend Loader class.

  10. nawtab May 17, 2009 at 3:26 pm #

    Hi Faheem,

    thx a lot for this easy-to-understand tutorial. After some minor modifications I got it working for me.
    In case you modify this tutorial, please exclude the password while storing the user-information in the session:
    Instead of $storage->write($authAdapter->getResultRowObject()); just use $storage->write($authAdapter->getResultRowObject(null, ‘password’)); in the loginAction.

  11. sumesh June 19, 2009 at 10:31 am #

    HI ,

    Thanks a lot for ur help.but am getting an error while running http://localhost/schoolslp/public/auth/login
    schoolslp(folder in root(var/www/schoolslp/)
    Fatal error: Class ‘Users’ not found in /var/www/schoolslp/application/controllers/AuthController.php on line 33
    kindly help me as soon as possible.

  12. atrus123 June 23, 2009 at 12:53 am #

    Excellent tutorial, thanks. I’ve spent some time digging through Zend_Auth tutorials, and this is the best one I’ve seen.

  13. Terrahawk October 7, 2009 at 7:52 am #

    Gracias for this Tutorial and Greetz from Germany 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: