Login & Signup in Zend Framework

Zend Framework is an Open-Source object-oriented Web application framework implemented in PHP .The goal of ZF is to simplify Web development while maintaining object-oriented best practices for building Web 2.0 applications and Web services.

I am starting with simple Signup & Login Authentication .

Requirements:-

(i)Latest version of PHP,My SQL Database and Apache Web Server must be installed on your system.

(ii)mod_rewrite must be enabled by using this command

sudo a2enmod rewrite

(iii)Restart Apache

sudo service apache2 restart

(iv)Download Zend minimal package

Make a Directory Structure like this

project/

application/

controllers/

forms/

models/

views/

scripts/

index/

Steps:-

1.Extract the library folder from zend package to the main working project/ directory.

2.Create a index.php file and placed in project/ directory

index.php

<?php

define(‘ROOT_DIR’, dirname(__FILE__));

set_include_path(‘.’

. PATH_SEPARATOR . ROOT_DIR . ‘/library’

. PATH_SEPARATOR . ROOT_DIR . ‘/application/models’

. PATH_SEPARATOR . ROOT_DIR . ‘/application/forms’

. PATH_SEPARATOR . get_include_path()

);

require_once “Zend/Loader/Autoloader.php”;

$autoloader = Zend_Loader_Autoloader::getInstance();

$autoloader->setFallbackAutoloader(true);

$config = new Zend_Config_Ini(ROOT_DIR.’/application/config.ini’, ‘general’);

$db = Zend_Db::factory($config->db);

Zend_Db_Table::setDefaultAdapter($db);

$frontController = Zend_Controller_Front::getInstance();

$frontController->throwExceptions(true);

$frontController->setControllerDirectory(ROOT_DIR.’/application/controllers’);

$frontController->dispatch();

?>

3.Create a Database by executing this following sql query.

CREATE TABLE IF NOT EXISTS `Users` (

`id` int(100) NOT NULL AUTO_INCREMENT,

`firstname` varchar(100) NOT NULL,

`lastname` varchar(100) NOT NULL,

`email` varchar(255) NOT NULL,

`username` varchar(100) NOT NULL,

`password` int(20) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

4.Create a config.ini file in project/application/ Directory

[general]

db.adapter = “PDO_MYSQL”

db.params.host = “localhost”

db.params.username = “root”

db.params.password = ” “

db.params.dbname = ” “

5.Create a Controller named IndexController.php and placed in application/controllers/ Directory.

IndexController.php

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
    } 
    public function signupAction()
    {
    } 
    public function logoutAction()
    {
    }
    public function homeAction()
    {
    }
}

 

6.Now we will need to create template files in application/views/scripts/index/ named

   index.phtml
   signup.phtml
   logout.phtml
   home.phtml

 

7.Now we begin with us forms create LoginForm in applications/forms/

LoginForm.php

<?php

class LoginForm extends Zend_Form

{

public function init()

{

$this->setMethod(‘post’);

$username = $this->createElement(‘text’,’username’);

$username->setLabel(‘Username’)

->setAttrib(‘maxlength’,75);

 

$password = $this->createElement(‘password’,’password’);

$password->setLabel(‘password:’)

->setAttrib(‘maxlength’,75);

 

$signin = $this->createElement(‘submit’,’signin’);

$signin->setLabel(“sign in”)

->setIgnore(true);

 

$this->addElements(array(

$username,

$password,

$signin

));

}

}

?>

 

8.Next form is RegistrationForm in application/forms/ Directory.

RegistrationForm.php

 

<?php

class RegistrationForm extends Zend_Form

{

public function init()

{

$firstname = $this->createElement(‘text’,’firstname’);

$firstname->setLabel(‘First Name:’)

->setRequired(false);

 

$lastname = $this->createElement(‘text’,’lastname’);

$lastname->setLabel(‘Last Name:’)

->setRequired(false);

 

$email = $this->createElement(‘text’,’email’);

$email->setLabel(‘Email:’)

->setRequired(false);

 

$username = $this->createElement(‘text’,’username’);

$username->setLabel(‘Username:’)

->setRequired(true);

 

$password = $this->createElement(‘password’,’password’);

$password->setLabel(‘Password:’)

->setRequired(true);

 

$confirmPassword = $this->createElement(‘password’,’confirmPassword’);

$confirmPassword->setLabel(‘Confirm Password:’)

->setRequired(true);

 

$register = $this->createElement(‘submit’,’register’);

$register->setLabel(‘Sign up’)

->setIgnore(true);

 

$this->addElements(array(

$firstname,

$lastname,

$email,

$username,

$password,

$confirmPassword,

$register

));

}

}

?>

 

 

9.Now add homeAction fuction to the IndexController.php

 

public function homeAction()

{

$storage = new Zend_Auth_Storage_Session();

$data = $storage->read();

if(!$data){

$this->_redirect(‘index/index’);

}

$this->view->username = $data->username;

}

 

Create template file for this home.phtml in application/views/scripts/index/ Directory

Welcome <?=$this->username?>,<br>

This is your home page<br>

<a href='<?php $i=$this->baseUrl().”/index/logout”; echo $i; ?>’>click here to logout</a>

 

10.Now add indexAction fuction to the IndexController.php

 

public function indexAction()

{

$users = new Users();

$form = new LoginForm();

$this->view->form = $form;

if($this->getRequest()->isPost()){

if($form->isValid($_POST)){

$data = $form->getValues();

$auth = Zend_Auth::getInstance();

$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),’Users’);

$authAdapter->setIdentityColumn(‘username’)

->setCredentialColumn(‘password’);

$authAdapter->setIdentity($data[‘username’])

->setCredential($data[‘password’]);

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

if($result->isValid()){

$storage = new Zend_Auth_Storage_Session();

$storage->write($authAdapter->getResultRowObject());

$this->_redirect(‘index/home’);

} else {

$this->view->errorMessage = “Invalid username or password. Please try again.”;

}

}

}

}

Create template file for this index.phtml in application/views/scripts/index/ Directory

<?

if(isset($this->errorMessage)){

echo $this->errorMessage;

}?>

<?

echo $this->form;

?>

<a href='<?php $i=$this->baseUrl().”/index/signup”; echo $i; ?>’>New users click here?</a>

11.Now add signupAction fuction to the IndexController.php

public function signupAction()

{

$users = new Users();

$form = new RegistrationForm();

$this->view->form=$form;

if($this->getRequest()->isPost()){

if($form->isValid($_POST)){

$data = $form->getValues();

if($data[‘password’] != $data[‘confirmPassword’]){

$this->view->errorMessage = “Password and confirm password don’t match.”;

return;

}

unset($data[‘confirmPassword’]);

$users->insert($data);

$this->_redirect(‘index/index’);

}

}

}

 

Create template file for this signup.phtml in application/views/scripts/index/ Directory

<?

if(isset($this->errorMessage)){

echo $this->errorMessage;

}?>

<h4>Sign up</h4>

<?

echo $this->form;

?>

 

12.Now add logoutAction fuction to the IndexController.php

 

public function logoutAction()

{

$storage = new Zend_Auth_Storage_Session();

$storage->clear();

$this->_redirect(‘index/index’);

}

 

13.Our model class is placed in applications/models/ Directory

Users.php

<?php

class Users extends Zend_Db_Table

{

public function checkUnique($username)

{

$select = $this->_dbTable->select()

->from($this->_name,array(‘username’))

->where(‘username=?’,$username);

$stmt = $select->query();

$result = $stmt->fetchAll();

if($result){

return true;

}

return false;

}

}

?>

 

14.Now you can run your project by put this URL on your browser bar

http://localhost/project_name/index

 

15.Thankiew

12 thoughts on “Login & Signup in Zend Framework”

  1. hello ! Navdeep nice article.. but which framewrok version diid you use in this i mean which library should i include ??
    i have include library of framework 1.12

    but i am getting error like this

    Fatal error: Uncaught exception ‘Zend_Config_Exception’ with message ‘Section ‘general’ cannot be found in C:wampwwwProject/application/config.ini’ in C:wampwwwProjectlibraryZendConfigIni.php on line 151

    1. i solved that error but now i can’t redirect lo signup or home after login Error says
      The requested URL /Project//index/signup was not found on this server. !!!

        1. Yes i have the same directory structures like yours,
          Project
          application
          controllers
          IndexController.php
          forms
          LoginForm.php
          RegistrationForm.php
          models
          Users.php
          views
          scripts
          index
          index.phtml
          home.phtml
          signup.phtml
          logout.phtml
          config.ini

          library
          index.php

  2. The working of application is

    On Index page you found signup link and login form.
    For signup click on “New users click here?”
    After Register yourself, you can login.
    After login You can see welcome message and logout link.

    If all things which I written above is working.
    Then you have done all with this application.

  3. Thanks navdeep The Error was for index.php Every time if i have to access login or signup link,
    i have to write index.php/index/signup instead of index/signup in address bar and had to change according in code..
    and then all the things were working fine..
    but then again the session was not working and sometimes the back link would redirect to home after logout..

    so.. then i realize that i can solve that with one .htaccess file which can rout all request via index.php.. !!
    so now it is working very fine and thanks again i have learned a lot..

  4. I don’t even understand how I stopped up here, however I believed this put up was once great. I don’t understand who you are but certainly you are
    going to a famous blogger when you aren’t already. Cheers!

  5. hello ! Navdeep nice article.. but which framewrok version diid you use in this i mean which library should i include ??
    i have include library of framework 1.12

    but i am getting error like this

    Fatal error: Uncaught exception ‘Zend_Config_Exception’ with message ‘Section ‘general’ cannot be found in C:wampwwwProject/application/config.ini’ in C:wampwwwProjectlibraryZendConfigIni.php on line 151

    1. Hii Dileep

      Have you followed requirement instructions carefully?

      Follow these steps to remove error.

      (ii)mod_rewrite must be enabled by using this command

      sudo a2enmod rewrite

      (iii)Restart Apache

      sudo service apache2 restart

      From your file system “C:wamp” I came to know that you are window users. You can find how to enable mod_rewrite in windows.

      Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *