And now the fun begins! Today we’re going to really show some of the power of Zend Framework. All the steps that you’ve taken in the previous tutorials will suddenly make sense — you’re going to be set up to authenticate users in a few minutes flat.

If you don’t know basic OOP (Object-Oriented Programming) principles, now would be a good time to go do some reading on them. We’re going to make heavy use of inheritance, as well as overriding. Just keep in mind that PHP is not a strongly typed language.

Let’s get started. For authentication, we’re going to build the form the old fashioned way so that you can get a good example for ‘how it was done’ versus ‘how smoothly it can be done’ with Zend Framework. Let’s create the login form. In /app/views/scripts/index/, create login.phtml — do note the .phtml extension on it. To keep us moving right along, here’s the code for it.

<? if(!empty($this->message)): ?>
    <?=$this->message?>
<? endif; ?>
<form name="login" action="index/login" method="post">
Login: <input type="text" name="login" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" name="submit" value="submit" />
</form>

Now we’ll head back to your controller. If you look at the work you did in the form, you’ll see that the index controller’s login action will be responsible for both displaying and processing this form.

First, to get the form to display, you’ll need to add just a blank login action to your IndexController. For security purposes, I’ve cleared out the ‘list of users’ that was in yesterday’s indexAction() (we don’t really want to give an attacker a list of users to try, do we?) and replaced it with a call to $this->_forward() to direct users that come to the index page to the login. Later on, when we’re checking for authenticated users, we’ll replace this with a conditional.

class IndexController extends Zend_Controller_Action {
  function indexAction() {
     $this->forward('login');
  }
  function loginAction() {
 
  }
}

Now, if you visit /index/login in your browser, you should get the login form. Let’s add some logic to make it do something. We’re going to use Zend_Auth’s database methods for this.

function loginAction() {
  $params = $this->_getAllParams();
 
  if(!empty($params['submit']) && $params['submit'] == 'submit') {
        $auth = Zend_Auth::getInstance();
 
        $adapt = new Zend_Auth_Adapter_DbTable(Zend_Registry::get('db'));
        $adapt->setTableName('users');
        $adapt->setIdentityColumn('id');
        $adapt->setCredentialColumn('password');
        $adapt->setCredential(sha1($param['password']));
        $adapt->setIdentity(htmlspecialchars($param['login']));
 
        $result = $auth->authenticate($adapt);
        $this->initView();
        if($result->isValid()) {
	          $storage = new Zend_Auth_Storage_Session();
                  $storage->write($adapt->getResultRowObject(array('id')));
	          $auth->setStorage($storage);
 	          $this->view->message = 'Login Successful!';
        } else {
	          $this->view->message = 'Invalid login. Please try again.';
        }
    } 
}

There’s a few very important things we want to note here.

  1. Zend_Auth is written in a Singleton Pattern.
  2. We make use of the database handle that we stored in the registry in the front controller.
  3. We’re encoding the password in the code before we send it to the database. In the database, the password is already encoded in sha1 format.
  4. We’re setting the identity for later retrieval.
  5. We pass a message back to the user via the view script.

You know what? I know I promised that we’d get into some fancier stuff using Zend_Form and Zend_Mail, but I think that’s enough new concepts for one day. We’ll extend the tutorial into next week and spend tomorrow working with Zend_Form and Zend_Mail.

Happy coding!

5 comments on ' Your First Zend Framework Application: Day Four '

  1. Hi Karl,

    really helpful tutorial!
    You have a typo above: it should be
    $this->_forward(’login’);
    (with the underscore)

    Greets,
    Horst

  2. and also in:
    $adapt->setCredential(sha1($param['password']));
    $adapt->setIdentity(htmlspecialchars($param['login']));

    shouldn’t the $param be $params?

    Besides that I get a
    “File does not exist: H:/workspace.zend/ZAccred/html/index”
    It seems as if the mapping to the script doesn’t work in
    index.phtml with action=”index/login”. (my login.phtml
    is located in folder app/views/script/index and the form is shown
    correctly).

  3. The “File does not…” is gone with the RewriteBase directive (see my comment for day 2.

  4. this has been a very helpful tutorial. thanks so much.

    however, i had some problems that i want to share to help anyone else who might be struggling.

    hitting submit with a blank login will cause a fatal error. a simple check to see if the login is not empty will fix this. not a big deal but just wanted to let people know.

    after entering a login and pressing submit, it changed the url incorrectly. so if i started with ‘localhost/’ after hitting submit i had ‘localhost/index/login’ which was correct but if i had ‘localhost/index/login’ and i hit submit, i would get ‘localhost/index/index/login’ by changing the action to be action=”/index/login” i eliminated the problem.

    also, i used the .htaccess from the zend quickstart tutorial and it worked fine:

    RewriteEngine on
    RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

      Written by ben on May 29, 2008 at 2:31pm

  5. Really good one . i got this after a long search.

      Written by Logu on July 23, 2008 at 9:13am

Leave a comment

name (req'd)

email (req'd)

website