Zend Framework

Zend Framework Tutorial- simple signup and login authentication

Posted by Faheem Abbas on January 17, 2009

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,

PRIMARY KEY  (‘id’)

)

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 said

    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 said

    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 said

    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]);
    break;

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

    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] );
    }
    break;

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

    public static function logout() {
    $storage = new Zend_Auth_Storage_Session();
    $storage->clear();
    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)) {
    try{
    $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']);
    $this->_redirect('index/login');
    } catch(Exception $e){
    echo $responseLogin = $e->getMessage();
    $this->_redirect('index');
    }
    $this->view->responseLogin = $responseLogin;
    }
    }
    }

    public function logoutAction() {
    $this->user->logout();
    $this->loggedIn=false;
    $this->_redirect('/index');

    }
    }

    hojala puedas ayudarme gracias please help me

  4. Faheem Abbas said

    Gracias.
    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 said

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

  6. jack said

    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…

    if(!$data){
    $this->_redirect(‘auth/login’);
    }

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

    Any ideas? Thanks again.

    Jack

  7. jack said

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

    You're logged in.

    Thats what it should be.

  8. Prashant said

    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.

    Thanks!
    Prashant

  9. Faheem Abbas said

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

  10. nawtab said

    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 said

    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 said

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

  13. Terrahawk said

    Gracias for this Tutorial and Greetz from Germany :)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>