Tutorial: Getting Started with Zend_Auth

This tutorial is intended to give a very basic introduction to using Zend_Auth for authentication of users. It builds on the Getting Started with the Zend Framework tutorial, so please read that one first!

NOTE: This tutorial has been tested on version 1.0.0 of the Zend Framework and is not very compatible with versions later than 1.4! It is unlikely to on any version prior to version 1.0.0 due to dependency on the ViewRenderer action helper.

English version: Download the PDF (v1.0.8).
Simplified Chinese version by Jason Qi (offsite): Visit Jason's download area.
French version by R Benyacoub (offsite): Débutez avec Zend_Auth.
Spanish translation by Claudio Cossio (offsite): Como usar Zend_Auth del Zend Framework: PDF (v1.0.4).
Latvian version by Ingus (offsite): Ievads Zend_Auth
Brazilian Portuguese version by Ricardo Klein (offsite): Começando com Zend_Auth PDF (v1.0.8).

The associated code is available in my subversion repository or you can download a zip file.

Code

The associated code is available:

Changelog

1.0.8
Fixed path error found by Terence Yap.
1.0.7
Fixed typos found by         Greg Wilson and Ma Ding.
1.0.6
Fixed compatibility issues with the Zend Framework Tutorial.
1.0.5
Add a note about session.save_path.
1.0.4
Fix some of the phrasing as noticed by Jason Qi. Also fixed handling of empty login form as noticed by Tom and John Baldock. Zip file updated too.
1.0.3
More typos found by Wayne Roesner.
1.0.2
First typo found by Greg. Use the request's isPost() function as suggested by sleek.
1.0.1
First typos found by David Goodwin within 15 mins of the release of 1.0.0!
1.0
First version

160 Responses to “Tutorial: Getting Started with Zend_Auth”

  1. 1 rbyt3

    This is what I've been waiting for. :D
    Thanks Rob

  2. 2 DaHey

    Great work.

    Thank you.

  3. 3 Matjaz

    YESssss :)

    Thank you.

  4. 4 sleek

    You might consider using $this->getRequest()->isPost() from within your controller action instead of strtolower($_SERVER['REQUEST_METHOD']) === 'post'

  5. 5 Greg

    On page 6 at the top you mention the init function in IndexController but the example actually shows the AuthController.

    Thanks for the tutorials...

  6. 6 Fábio TC

    Great work.

    I'm waiting for the Zend_Acl tutorial.

    Thanks

  7. 7 Rob...

    sleek,

    Good idea. $this->_request->isPost() would also work.

    Greg,

    Fixed already in 1.0.1 :)

    Regards,

    Rob...

  8. 8 Rob...

    Fábio TC,

    *grin*

    Regards,

    Rob...

  9. 9 Greg

    Actually, it is still there in 1.0.1:

    "First thing to do is to get it to the view,
    which we do in the init() function of IndexController():
    zf-tutorial/application/controllers/AuthController.php:
    class AuthController..."

    :)

  10. 10 Rob...

    Greg,

    Thought, I'd fixed that - clearly not ;)

    Fixed in 1.0.2 though!

    Regards,

    Rob...

  11. 11 Tom

    If you submit the form without any values you receive an exception from the DB Auth.

    It is maybe wise to surround the line
    "$result = $auth->authenticate($authAdapter); "

    with a try catch statement

  12. 12 Henry Bjornskov

    Hey Rob
    I had some trouble following your script until i found out you need to do a:
    Zend_Loader::loadClass("Zend_Session");
    Zend_Session::start();

    just if any other got the same problems.

    ps. Sry for my bad english.. I am a Dane :)

  13. 13 Luke Barton

    I'm having issues with getResultRowObject().

    "Call to undefined method Zend_Auth_Adapter_DbTable::getResultRowObject()"

    It functions perfectly except where writing to the singleton for that reason. However, Obviously, ommiting those 2 lines prevents the session being carried.

    What am I missing?
    All help appreciated.

  14. 14 Luke Barton

    I think my issue is related to ZF 0.9.0-Beta because using 0.9.1-Beta solved my issue completely.

  15. 15 Rob...

    Luke,

    Thanks for letting me know!

    Regards,

    Rob...

  16. 16 DaHey

    Is there a simple way to authenticate against passwords that are hashed in the database using the mysql password function?

  17. 17 Tom

    DaHey,

    Just add the following code to your auth controller

    $authAdapter->setCredentialTreatment('PASSWORD(?)');

    But you could also use SHA1 and MD5

  18. 18 DaHey

    Thanks Tom.

  19. 19 John Baldock

    Another great tutorial! *thumbs up*

    "If you submit the form without any values you receive an exception from the DB Auth."

    I encountered this too, what I did was to add the following under "if ($this->_request->isPost()":

    if ($this->_request->getPost('username') == null and $this->_request->getPost('password') == null) {
    $this->view->message = 'Login failed.';
    $this->render();
    return;
    }

    If you do this you need to make sure you assign the view variables, like "$this->view->title = "Log in";" before the "if ($this->_request->isPost()" block.

    Thanks again,
    John

  20. 20 Rob...

    Tom, John,

    Fixed in 1.0.4.

    Regards,

    Rob...

  21. 21 Dahey

    The link to the English version pdf leads to the front page.

  22. 22 Rob...

    Doh!

    Thanks Dahey. Fixed now!

    Regards,

    Rob...

  23. 23 Bojan

    Great tutorials Rob!

    I finished your 'Getting strated tutorial...' and it all worked great but when I was trying to do this tutorial I encountered a problem. When I go to zf-tutorial/auth I get 404 Page Not Found error.

    I thought that I made an error so I copied the IndexController and all files asociated with it into IndeController (also the files in the views directory...) and it didn't work either.
    It only redirects fine with IndexController. For everything else I get a 404 error.

    Can you pleas help me with this problem.

  24. 24 Tom

    To simplify things you can also use Zend_Controller_Request_Http's magic __get method to access POST keys:

    $this->_request->username
    $this->_request->password

  25. 25 Rob...

    Tom,

    True, but the magic method doesn't let you confirm where the value has come from.

    Makes the code cleaner though :)

    Regards,

    Rob...

  26. 26 Russell

    Great stuff, just what I needed.

    I too look forward to Zend_Acl getting the Rob Allen treatment! The one on zftutorials looks way too complicated to me.

  27. 27 José

    I too look forward to Zend_Acl getting the Rob Allen treatment!

    I really need something for know, if its possible (some verbal talking)...

    ------------

    I was thinking of tree roles (guest, member and admin)

    guest -> only see the albums
    member -> can add albums but can't delete them.
    admin -> can do everything

    The resources are the actions builded by the Akra's ZF tutorial?

  28. 28 nour

    Hai Rob, this is a great work.
    I had Aa quetion, Do you know how i the sessionid get of zend_session.
    thanks

  29. 29 zly

    cool,, thanks

  30. 30 nour

    Hallo rob what s new in zf 0.9.3

  31. 31 Rob...

    Nour,

    http://framework.zend.com/issues/secure/IssueNavigator.jspa?mode=hide&requestId=10280

    Regards,

    Rob...

  32. 32 Stig Benning

    Hi Rob,

    I have the two tutorials up and running, but trying out the login procedure in another context results in the following:

    When I press the login button the browser adds %22 to baseUrl/auth/login so that it reads baseUrl/auth/login%22 and I am served an error message stating that login22Action does not exist. Do you know what is the error here?

    Thanks
    Stig

  33. 33 Stig Benning

    Ups type error :/ problem solved :)

  34. 34 Rob...

    Stig,

    *grin*

    Regards,

    Rob...

  35. 35 Stig Benning

    Hi Rob *grin* here too.

    Now the following: On my production server I get a message stating that the session save path is unwriteable. On my test server it runs to perfection.

    Any ideas?

    Thanks
    Stig

  36. 36 Stig Benning

    I tried leaving the entire error message here, but couldn't do it :*

  37. 37 Gert Vanspringel

    Following the tutorial, and after installing the demofiles, I've got this message:"Fatal error: Uncaught exception 'Zend_Session_Exception' with message 'session has already been started by session.auto-start or session_start()' in C:\Program Files\xampp\htdocs\zf-tutorial_2\library\Zend\Session.php:383 Stack trace: #0 C:\Program Files\xampp\htdocs\zf-tutorial_2\library\Zend\Session\Namespace.php(116): Zend_Session::start(true) #1 C:\Program Files\xampp\htdocs\zf-tutorial_2\library\Zend\Auth\Storage\Session.php(85): Zend_Session_Namespace->__construct('Zend_Auth') #2 C:\Program Files\xampp\htdocs\zf-tutorial_2\library\Zend\Auth.php(92): Zend_Auth_Storage_Session->__construct() #3 C:\Program Files\xampp\htdocs\zf-tutorial_2\library\Zend\Auth.php(144): Zend_Auth->getStorage() #4 C:\Program Files\xampp\htdocs\zf-tutorial_2\application\controllers\IndexController.php(10): Zend_Auth->getIdentity() #5 C:\Program Files\xampp\htdocs\zf-tutorial_2\library\Zend\Controller\Action.php(123): IndexController->init() #6 C:\Program Files\xampp\htdocs\zf-tutorial_2\library\Zend\Controller\Dispatcher\Standard.php(193): Z in C:\Program Files\xampp\htdocs\zf-tutorial_2\library\Zend\Session.php on line 383" Zend Framework 0.9.3 on latest xampp release (php 5.2.1). Anyone, any idea?
    Gert

  38. 38 Gert Vanspringel

    Resolved!

    Found out that changing session.auto_start to 0 in my php.ini file, resolved the problem. Brilliant tutorrial!

    Gert

  39. 39 Brent

    Great tutorial-- really appreciate it. That said, the current implementation seems to have a giant security hole. Try this:
    (1) Log in successfully
    (2) Log out
    (3) Attempt to log in with totally bogus credentials

    When the attempt in (3) fails, the page is posted with the failure message, but the username and password fields are also populated with the correct login credentials from (1)!! Simply clicking submit logs you in as the user from (1).

    I could be mistaken, as I typed up all the code by hand following the instructions given and may have missed something, but everything else seems to work great. BTW, in case it matters I'm using Firefox 2.0 (of course).

    Also, this is my very first foray into PHP (though I've got lots of experience in Java, C#, Javascript, ML, Scheme, Prolog, and some others), so I have nothing to offer as a solution. Sorry if this insight is bogus (i.e. results from a mistake of mine). And thanks again for the great tutorials!

    Brent

  40. 40 Stig Benning

    Hi Brent - and Rob.

    Interesting. If I perform the steps you describe in IE 7, I just get at message in the message field saying: "Login failed" with empty username and password fields. If I do the same in Firefox 2.0 it is as you describe. I would of course never suggest a flaw in the way Firefox handles credentials :) and under all circumstances there should be a way to prevent this.

    Stig

  41. 41 Stig Benning

    Hi Brent - and Rob - again :)

    As far as I can judge it may have to do with the auth session handling. On sites I have developed with login functionality, I destroy the session and unset cookies on logout, and here there are no problems neither in IE 7 nor in Firefox 2.0.

    Looking forward to see your input, Rob.

    Stig

  42. 42 Brent

    Hi Stig and Rob,

    Having explored this a bit more, it appears that it has nothing to do with the PHP code, but rather with my auto-complete settings in Firefox. If I disable auto-complete for the site (add it to my exceptions list) then the fields are cleared upon an unsuccessful login. Sorry for the confusion... and thanks again for the great tutorials Rob!

    Brent

  43. 43 Stig Benning

    Hi Brent and Rob,

    "Having explored this a bit more..."

    You're right. I experimented with this on my own sites too, and get the same result as you, because of my settings in Firefox.

    You do not have to input anything to this subject, Rob *gg*, but I am still curious regarding posting #35.

    Stig

    Stig

  44. 44 Rob...

    Bit snowed under with stuff atm. I will have a look when I get time.

    Regards,

    Rob...

  45. 45 nour

    I found your tut great. do you like to write a tut about zend_acl

  46. 46 Rob...

    Nour,

    It's all about time... and my lack of it!

    Regards,

    Rob...

  47. 47 Chris

    Just posting to help out some would be users of the "Getting Started With Zend Framework - Tutorial". On page 12 zf-tutorial/index.php will have to read: $db = Zend_Db::factory($config->db->adapter,
    $config->db->config->toArray()); instead of $db = Zend_Db::factory($config->db->adapter,
    $config->db->config->asArray()); -- in order to be used with ZF-RC2. Just a friendly reminder. Your tutorials aare great. I would hate to see someone new to the framework give up because of something so small. Keep upt the good work.

  48. 48 Peter

    Great tutorial!

    How can I send the session data to a database instant of the file system> Can you put that also in the tutorial?

    Greets,
    Peter

  49. 49 Bastien

    GREAT tut !!!!
    What about using cookies for a "Remember me" function ? You could add a chapter for it :p . Not essential, but interesting !!

    Looking forward to the Zend_Acl tut !
    By now, I'll try to modify the preDispatch() function of each controller in order to check the identity params. If params are not allowed to access this controller --> redirect!
    One question : Is it possible to save more params than identity and credential in auth's storage (a profile id for instance) ?

    Furthermore, I don't know how to protect each Action separately ... I'm definetly looking forward to the Zend_Acl tut...

  50. 50 Case

    =(
    Fatal error: Using $this when not in object context in /var/www/localhost/htdocs/zend_auth-tutorial_104/application/views/scripts/auth/login.phtml on line 1

    What fixed?

  51. 51 Nicholas

    Hey, I'm working on an ACL tutorial, and I was wondering if you minded if I built my tutorial off of this one. I will direct users to your site for this tutorial, but just pick up where this one leaves off. Let me know if this is a problem.

  52. 52 Rob...

    Hi Nicholas,

    Free free!

    Regards,

    Rob...

  53. 53 Rob...

    Re #35 (& #43!),

    It's telling the truth! Check your php.ini file and fix the permissions on the directory for session.save_path.

    Regards,

    Rob...

  54. 54 Mathias

    Excellent work!!! I'm looking forward to more tutorials you might write.

    If Nicholas would be so kind and provide a link to his web page where one eventually might find the Acl tutorial built upon this one it would be great :-)

    Kind regards, Mathias

  55. 55 nour

    Hi Rob, how can i do this with ZF:
    LOCK TABLE nested_category WRITE;
    SELECT @myRight := rgt FROM nested_category
    WHERE name = ‘TELEVISIONS’;
    UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myRight;
    UPDATE nested_category SET lft = lft + 2 WHERE lft > @myRight;
    INSERT INTO nested_category(name, lft, rgt) VALUES(’GAME CONSOLES’, @myRight + 1, @myRight + 2);
    UNLOCK TABLES;

    Thanks

  56. 56 Rob...

    nour,

    I would write that directly using SQL!

    Regards,

    Rob...

  57. 57 cocoi

    Rob, great tutorial. How to create pagging in view album page?

    im new in zend and i need your help.
    thanks

  58. 58 Rob...

    Cocoi,

    There's no built in support for paging within Zend_Db_Table, so you'll have to roll your own.

    Regards,

    Rob...

  59. 59 Adam

    Just noticed a changed between the Getting started boostrapper(index.php) and the zend_auth_tutorial bootstrapper(index.php):

    In the "setup database" section you changed the variable name "$db" to "$dbAdapter". I caught it because of PHP notices after completing page 2 of the zend_auth tutorial.

  60. 60 Stig Benning

    Regarding #35

    Thank you for your answer. Have been away. Will check with my provider what to do. Can this maybe be handled via .htaccess?

    Stig

  61. 61 cocoi

    Thank you for your answer Rob. How to change fetchAll() in indexaction function to some sql code like 'select id, title from album where id > 1 order by id desc limit 0,10' ??

    i now im trying to create the pagging based on your tutorial :) Thanks for your kind Rob.

  62. 62 Steven

    Thanks. Your work helps me a lot.

  63. 63 Stuart

    I love your Zend Framework tutorials! They are so useful.
    My question is this: How do I pass info from loginAction to a different action?

    Currently loginAction is passing info (like "Login failed") to login.pthml for display. However, if I want to embed the login form in my main index.phtml thus not needing a separate view for logging in, how do I get loginAction to pass that info so I can use it on my index.phtml? I hope that is clear. Any help you can offer with this is greatly appreciated!

  64. 64 RhythmScout

    Hello,
    If I navigate directly to any page w/o logging in, (ie http://mysite.com/index/edit/id/1) I get the msg "Firefox has detected that the server is redirecting the request for this address in a way that will never complete." and the url reads:
    http://mysite.com/index/edit/id/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/login
    I've checked over for typos and can't see what is causing this. Does this occur for anyone else?

  65. 65 RhythmScout

    OK, pertaining to #64, here is what I did that seems to fix my issue:

    In IndexController.php, preDispatch() function replaced:

    $this->_redirect('/auth/login');
    with
    $this->_redirect($this->_request->getBaseUrl().'/auth/login');

  66. 66 Michael Ray

    Has this been addressed? It is messing up everything and I don't know which variable is correct to use in which page:

    #59 Adam
    July 12th, 2007 at 20:04 #

    Just noticed a changed between the Getting started boostrapper(index.php) and the zend_auth_tutorial bootstrapper(index.php):

    In the “setup database” section you changed the variable name “$db” to “$dbAdapter”. I caught it because of PHP notices after completing page 2 of the zend_auth tutorial.

  67. 67 Michael Ray

    I can't figure out this error:

    Fatal error: Argument 1 passed to Zend_Auth_Adapter_DbTable::__construct() must be an object of class Zend_Db_Adapter_Abstract, called in /home/content/g/r/a/grandillusion/html/application/controllers/AuthController.php on line 30 and defined in /home/content/g/r/a/grandillusion/html/library/Zend/Auth/Adapter/DbTable.php on line 112

  68. 68 Michael Ray

    Well, I fixed the error. It was a syntax error of course, and the error message was telling me exactly what variable was the problem.

    Thanks Rob for a very helpful tutorial!

  69. 69 Rob...

    Michael,

    Sorry, I was away last week. I'm glad you sorted it!

    Regards,

    Rob...

  70. 70 Peter

    This tutorial has been a great starting point for me!

    It would be wise however to add a note to this tutorial that in case of applying the _redirect method, output buffering should be ON (in php.ini or .htaccess) otherwise an exception error (headers already sent) will be raised!!

  71. 71 Joep Rongen

    Hey Rob, Great tutorial there.
    Everything worked out just fine!
    Now i really want to get further with it, and protect a full module with the same code.
    Ofcourse i can protect all controllers within that module, but i rather not.
    Can you give me a pointer to the solution? Is it with a plugin? or Zend_Acl ?
    Thanks in advance

  72. 72 Ricardo Klein

    wow....
    Rob, thanx for the tutorials...
    cant wait for the next...

    haha, if you continue with this
    we all will have a great way to learning about ZendFramework

    very very thanx
    great work

  73. 73 Ricardo Klein

    Rob, where are the sources of the
    PDF's of the Getting started with ZF and Getting Started with Zend_Auth

    if you apreciate I want to translate it to Brazilian Portuguese.....

  74. 74 Rob...

    Ricardo,

    Send me an email .

    Regards,

    Rob...

  75. 75 Mark

    Rob, I'm getting the same error as Bojan. The IndexController works fine but anything on the AuthController and I get a 404 error.

    I even copied in your zipped files (changing the config.ini for my db settings) and the 404 still persist for the AuthController. The error log says:
    File does not exist: /Users/mark/Sites/samplezendfw/httpdocs/auth/login

    My /etc/httpd/httpd.conf is set to:
    ...

    ServerName samplezendfw.localhost
    DocumentRoot "/Users/mark/Sites/samplezendfw/httpdocs"

    ErrorLog /var/log/httpd/samplezendfw_error.log
    CustomLog /var/log/httpd/samplezendfw_access.log combined

    ...

    Again, the first tutorial (Getting Started with Zend Framework) worked flawlessly.

    Any help would be appreciated, thanks.

  76. 76 Rob...

    Mark,

    I'd assume an .htaccess file issue personally. It's almost certainly related to mod_rewrite.

    Regards,

    Rob...

  77. 77 Mark

    The problem appears to be is that I'm developing on Mac OS X. I've tried a number of "fixes" and updated all these files and updated all of the .htaccess files in the web directory:

    /etc/httpd/httpd.conf
    /private/etc/httpd/httpd.conf
    /private/etc/httpd/users/mark.conf
    /etc/httpd/users/mark.conf

    Can you point me to the right location? Is there a good tutorial for Zend Frameworks installation for Mac OS X?

  78. 78 Mark

    Just got it working on a Fedora box with no issues. Must be something simple I'm missing on the Mac OS X. I still wouldn't mind to know if anyone has a Mac OS X solution though.

    Btw, great tutorial.

  79. 79 VJ

    Hello Rob,

    First of Thanks a lot for a great tutorial on Zend_Auth... I have been following ur doc ver: 1.0.8. and in the end I got this error message when entering username and password:

    Fatal error: Uncaught exception 'Zend_Auth_Adapter_Exception' with message 'A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.' in C:\wamp\www\zftutorial\library\Zend\Auth\Adapter\DbTable.php:286 Stack trace: #0 C:\wamp\www\zftutorial\library\Zend\Auth.php(118): Zend_Auth_Adapter_DbTable->authenticate() #1 C:\wamp\www\zftutorial\application\controllers\AuthController.php(49): Zend_Auth->authenticate(Object(Zend_Auth_Adapter_DbTable)) #2 C:\wamp\www\zftutorial\library\Zend\Controller\Action.php(497): AuthController->loginAction() #3 C:\wamp\www\zftutorial\library\Zend\Controller\Dispatcher\Standard.php(237): Zend_Controller_Action->dispatch('loginAction') #4 C:\wamp\www\zftutorial\library\Zend\Controller\Front.php(911): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #5 C:\wamp\www\zftutorial\index.php(33): Zend_Controller_Front->dispatch() #6 {main} thrown in C:\wamp\www\zftutorial\library\Zend\Auth\Adapter\DbTable.php on line 286

    I cannot figure out what is wrond could u plz help. Thanks in advance!!!

  80. 80 Don

    Hello,

    great tutorial, really. It helps me alot with the ZF. But can you give me a hint how i cam refactor the addAction() and editAction() Methods.

  81. 81 Rob...

    Hi Don,

    You should be able to merge the functionality into one function as the commonality between them is striking.

    Regards,

    Rob...

  82. 82 Lam

    Hi Mark,
    I have also the same problem, that the log says: File does not exist in ..auth/login .

    Did you solve your problem ?

  83. 83 Sebastien

    Hi all,
    I'm looking for a function 'Remember me'. Is someone has already do it ?
    Is it possible to see the code ?

    Thanks

  84. 84 Jimy

    I'm really looking forward to more tutorials from you, Rob. The first two you've published have been fantastic!

  85. 85 Marc

    Mark (77, 78)

    On OS X 10.5 I had the same problem. I changed AllowOverride to All from None in httpd.conf. I'm not sure why the original zf_tutorial worked without this, but none the less it seems to have solved the problem.

    Oh and Rob, thanks for the best ZF tutorial(s) out there! Write a book, I'll buy it. :)

  86. 86 Rob...

    Marc,

    Glad you got it sorted.

    Book is in the works...

    Regards,

    Rob...

  87. 87 Jon

    I agree, I will buy the book. Thanks again for all the hard work. This tutorial style truly is the easiest way to learn.

  88. 88 Marc

    Rob,

    On OS X worth noting. I had to change the DB adapter to work with the stock PHP install, the MySQLi worked fine.

    I just read the home page and saw your were already writing a book, .

  89. 89 Rob...

    Marc,

    Yeah - I found that too, but it didn't help with GD.

    Regards,

    Rob...

  90. 90 Toni

    Thanks! Just whan I've been looking for!

  91. 91 mark

    Hi,

    nice tutorial, I found an error though. In the editController you get the parameter using getParam and you attempt to typecast it using

    (int)($this->_request->getParam('id', 0);

    It should be

    intval($this->_request->getParam('id'));

    Nice tutorial!
    I'm waiting for the ACL one myself!!

  92. 92 Rob...

    Hi Mark,

    Casting to an int using (int) will work fine. (see http://uk2.php.net/language.types.type-juggling#language.types.typecasting)

    Regards,

    Rob...

  93. 93 Kareem

    hey! great tutorials! You're the reason I'm still using ZF!

    I am actually trying to create a login form on every page of the site. So I want the user to be able to login on any page and stay at that page. I am unsure how to go about doing this following your example because ZF needs a view for the login right? So how do this?

    thanks,
    kareem

  94. 94 Rob...

    Kareem,

    When you redirect to the the login action, keep track of where you came from so you can redirect back there after authentication.

    I use a hidden field on the login form personally.

    Regards,

    Rob...

  95. 95 Ingus

    Latvian translation of 1.0.8 available at:
    http://webtech.lv/rakstu-darbi/zend-auth/

  96. 96 Rob...

    Thanks Ingus!

  97. 97 Ribamar FS

    I'm translating this tutorial to portuguese Brazil.
    You want I sendo for your?

  98. 98 Rob...

    Ribamar,

    Sure :)

    Regards,

    Rob...

  99. 99 Mic

    Thanks Rob,

    A great tutorial! I've had hard problems to understand to implement a login-system. Perhaps id would be a goog idea and integrate acl and user roles in this tutorial.

    Once again
    thanks a lot
    Mic

  100. 100 Doc Olson

    Hi & thx for the tutorial.
    I have a question though. Once successfully logged in one should be redirected to some site ('/' in your example). But that does not work, i get a "headers already sent" error. Seems the controller renders the view before the redirect can take place.
    In #70 Peter suggests to make sure the output buffer is turned on but that doesn't make too much sense to me as the render process is redundant. After the login you get redirected to another part of the site anyway.
    How can i prevent this?

  101. 101 Doc Olson

    Jesus, what a dork i am. Oh well, something for your amusement: it was the old "whitespace after ?>" problem.

    Merry Xmas

  102. 102 Rob...

    Hi Doc,

    Glad you sorted it!

    Merry Christmas to you and a Happy New Year.

    Regards,

    Rob..

  103. 103 melvin

    Catchable fatal error: Argument 1 passed to Zend_Auth_Adapter_DbTable::__construct() must be an instance of Zend_Db_Adapter_Abstract, instance of Zend_Config_Ini given, called in C:\xampp\htdocs\mytb_zf\application\controllers\UserController.php on line 65 and defined in C:\xampp\htdocs\mytb_zf\library\Zend\Auth\Adapter\DbTable.php on line 112

    ===========

    Hi Rob,
    i got this fatal error.
    how do i fix this problems.

    btw thanks for great tutorial.

  104. 104 jeff Walters

    For the Mac OS X Leopard users having problems with .htaccess. (I've seen a few respond here.) Leopard uses apache 2, so the place to edit httpd.conf has changed as well. The directory is /etc/apache2.

    Also you will likely have to edit the conf for your virtual server as well. You'll find it here:
    /etc/apache2/users/*.conf

    I struggled with this myself. Had to wrap my head around the changes with leopard.

    The reason the old tutorial still works is that it only uses the indexController. Index will still resolve to index.php. It falls on its butt when accessing the authController because the apache server can't resolve the path without .htaccess working.

    I thank you Rob for your tutorials. They've got me up and running with the ZF. I have ordered your book and have been following your pdf's.

    You the man!

  105. 105 Erdal Yazicioglu

    Hello Rob,

    I am studying on your tutorial "Getting Started with Zend_Auth" and first of all I want to thank you for this great source.

    Actually I finished the first part of your tutorials and moved to the Zend_auth...

    I have downloaded the latest version code and gone through tutorial. Very nice and helpful..

    Is it okey to translate in Turkish and publish on my blog with your reference...

    Best Regards..

    Erdal Yazicioglu

  106. 106 Rob...

    Hi Erdal,

    Of course!

    Regards,

    Rob...

  107. 107 Kenneth

    Excellent tutorials, congratulations. The examples at zend.com could learn a lot from you...

  108. 108 Rob...

    Thanks Kenneth!

    Regards,

    Rob...

  109. 109 Chris

    Hi Rob!
    Thanks for the great tutorial. It works fine. But now i have to change my login and check against ldap. Is it possible to modify your solution to check against ldap instead of checking against db?

    Chris

  110. 110 mike

    Is this compatible with the 1.5 release? Seems to do things differently than the (GREAT GREAT GREAT) tutorial on 1.5 :)

    PS did I mention that the tutorial on 1.5 was great? I think so.. :) Thanks!

  111. 111 Rob...

    Mike,

    I'm glad you like the 1.5 tutorial :)

    This tutorial should work too, but as you noticed doesn't take advantage of the new bits and bobs in Zend Framework 1.5.

    The "Auth" bits shouldn't be hard to port to the new code though.

    Regards,

    Rob...

  112. 112 Tetek

    hi, the link to polish version is not working.. Can u repair it?

    Regards,
    Tetek

  113. 113 Piotr Czachur (zimnyx)

    Stripping tags before passing username/paswword to auth adapter is redundant.
    ==
    $username = $f->filter($this->_request->getPost('username'));
    ==

    Auth adapter makes sql escaping on it's own.

    Cheers

  114. 114 Rob...

    Hi Tetek,

    Stripping tags is different from SQL escaping.

    Regards,

    Rob...

  115. 115 Piotr Czachur

    Hi Rob!
    Yeah, stripping tags and sql escaping is entirely different thing, but what is point of using strip-tags before passing login and passowrd to zend auth adapter? I see none.

    What I meant was that "cleaning job" here is made internaly by zend_auth/zend_db and is achieved by SQL escaping those values.

    Regards,
    Piotrek

  116. 116 Rob...

    Piotr,

    I agree, that the HTML is "safe", but as usernames should not include HTML, I don't want it in my application :)

    Regards,

    Rob...

  117. 117 Pete

    Hi Rob!

    First of all this is a great Tutorial.
    But i have a question, how can a user change/edit his password on an extra "change password" site.

    So i need a new controller with an edit/change Action.

    I dont know how it works with the database.

    Regards Pete

  118. 118 Christian

    I think this tutorial needs a revision since the file index.php doesn't seem to be the same as the latest getting started tutorial. Hope you can update it soon :)

  119. 119 walter

    yet another wonderful tutorial!

    2 questions...

    1) why does this tutorial explicitly define all the classes to load while the "Getting Started" tutorial doesn't?

    2) I'm stuck at...

    Fatal error: Call to a member function asArray() on a non-object in U:\home\zend\public\index.php on line 29

    line 29: $db = Zend_Db::factory($config->db->adapter, $config->db->config->toArray());

    and if I use the "Getting Started" line...

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

    I get this error:

    Zend_Controller_Dispatcher_Exception: Invalid controller specified (index) in U:\home\zend\library\Zend\Controller\Dispatcher\Standard.php on line 249

    Like I said: I'm stuck.

    Thx

    Walter

  120. 120 walter

    To make this tutorial work with the "Getting Started with the Zend Framework tutorial", you will have to make the following updates to some files.

    First: don't use the 'public/index.php' file from this tutorial.

    Modify the original bootstrap file.

    After:
    Zend_Loader::registerAutoload();

    add:
    // Start Sessions
    Zend_Session::start();

    after:
    Zend_Db_Table::setDefaultAdapter($db);

    add:
    Zend_Registry::set('dbAdapter', $db);

    Do not use: 'model/album.php

    Do not use: 'controllers/IndexController.php'

    Modify the original.

    Copy 'function init()' and 'function preDispatch()' from the auth tutorial 'IndexController.php' fiel to the orginal 'IndexController.php' file

    This is all I did (with Robs help!) to make this tutorial work on top of the original tutorial.

    Hope this helps someone.

  121. 121 Serch

    Great work Rob!

    I've found ZF quite difficult to learn it but this tutorials are definitely a life saver!

    Just a comment. Within the IndexController.php on the preDispatch function, I would add a ELSE statement that performs the following:

    function preDispatch(){
    ...
    if(!$auth->hasIdentity()){
    ...
    }else{
    $this->view->user = $auth->getIdentity();
    }
    }

    Kind regards!

  122. 122 Onur Özgür ÖZKAN

    Hi All,

    Turkish translate is avaible

    http://www.onurozgurozkan.org/2008/05/17/zend-autha-giris/

    But i should update some sentences. Anyway it is a good job.

    Best Regards.

  123. 123 dogggg

    Having problems getting bootstrapper to work. My error in apache is

    .htaccess: Invalid command 'php_flag', perhaps misspelled or defined by a module not included in the server configuration

    I'm not sure what to do with mod_php.

  124. 124 dogggg

    sorry I posted the above message on the wrong tutorial, I will repost it to the correct one.

  125. 125 Mark

    This tutorial works with ZF 1.5 too.

    Many thanks for this tutorial.

  126. 126 Same

    Thanks Rob,

    I create new field: 'status TINYINT(1)', how do we check the status of user?
    If i use $authAdapter->setCredentialTreatment('MD5(?) AND status=1'); the status checking works
    But if $authAdapter->setCredentialTreatment('status=1'); the status checking doesn't work

    Could you advice?

  127. 127 keogh

    Thanks for this tutorial, it make me understand a few losing thinks about Zend_Auth.

    S4lu2

  128. 128 Bill

    I've gone through the tutorial and had everything working up until the very last part and then it broke. I keep getting the following message:
    Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (index)' etc. I went so far as to download the zip file and substitute Robs files for what I had done, same thing. Bummed.

  129. 129 mike

    I've tried and tried to desperation point with the tutorial, but for some reason the session is destroyed as soon as the redirect line in AuthController is reached ($this->_redirect('/');). I've even tried using Registry to store the user details but he registry is destroyed by the redirect line as well. I've followed the advice in response 120 as well - still lose all session and registry data on Redirect... can anyone help?

  130. 130 ninky

    Catchable fatal error: Argument 1 passed to Zend_Auth_Adapter_DbTable::__construct() must be an instance of Zend_Db_Adapter_Abstract, none given, called in C:\xampp\htdocs\zend2\application\controllers\AuthController.php on line 34 and defined in C:\xampp\htdocs\zend2\library\Zend\Auth\Adapter\DbTable.php on line 122

    What's wrong guys?

  131. 131 ninky

    If you get error as I do (look previous post) change line
    $authAdadapter = new Zend_Auth_Adapter_DbTable;
    to
    $authAdadapter = new Zend_Auth_Adapter_DbTable($db);

  132. 132 Rob...

    Ninky,

    Good catch

    Regards,

    Rob...

  133. 133 arturo

    please zend_auth and zend_acl for zend framework 1.5, because l working with zend framework 1.5.
    tanks......

  134. 134 Vibhor

    Rob,
    Thanks for another great tutorial...helped me a lot..hope these stuffs will keep coming from you..

  135. 135 JJ

    Hi,

    I have the "session has already been started by session.auto-start or session_start()" error message.

    I've read in the comments someone faced the same problem.

    I'm integrating the Zend_Auth component to an existing application, which uses session_start() as you may expect.

    Is there a way to work around this issue without having to provide my own storage class?

    Regards,

    -jj. :)

  136. 136 Vibhor

    jj,

    you need to remove the trailing spaces at the end of your files..

  137. 137 Vibhor

    jj,
    sorry i was trying to reply in another forum...

  138. 138 Mark

    Thanks,

    I got the error call "Error: A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable." But Now I fixed Thansk Lot for Your Help

    Mark
    http://www.outsourceitindia.com

  139. 139 Thijs

    I know this might not be the correct place for this but:

    is it possible to write information to the Zend_auth instance after I have authenticated.

    I use 3 tables for my users.
    the first being users with username and password.
    after authenticating this I can simply use
    echo Zend_Auth::getInstance()->getIdentity()->username;
    and it will return "rob"

    but for Zend_Acl I want to use the same options but then
    Zend_Auth::getInstance()->getIdentity()->role;

    which is not stored in my users table.
    I can retrieve this value with some Selects. but is it possible to add it to the current identity?
    example:
    Zend_Auth->write('role', 'admin');
    and then retrieve this with Zend_Auth::getInstance()->getIdentity()->role;?

    or should I be looking another way for this?

    Thanks you,
    and thank you for taking your time. love your tutorials

  140. 140 Rob...

    Thijs,

    I would suggest asking on the mailing lists.

    Regards,

    Rob...

  141. 141 Outsourcing India

    Rob,
    Thanks for another great tutorial…helped me a lot

  142. 142 Thijs

    I fixed it rob.

    I created a new namespace and used that to insert authentication rights. (namespace works the same as sessions (I know you know that but for other people who might be wondering)

    and am just using it as any other session in php.

  143. 143 yours

    I finished your 'Getting strated tutorial…' and it all worked great but when I was trying to do this tutorial I encountered a problem. When I go to zf-tutorial/auth I get 404 Page Not Found error.

    I thought that I made an error so I copied the IndexController and all files asociated with it into IndeController (also the files in the views directory…) and it didn't work either.
    It only redirects fine with IndexController. For everything else I get a 404 error.

    Any suggestion?Wait u online

  144. 144 yours

    And when I remove the file 'login.phtml' to /index.and copy the code of AuthController.php into the IndexController,then in the browser:"http://localhost/zf-tutoria/public/login",it shows the correct view~

    and I echo the baseUrl,it shows "/zf-tutoria/public".

    why the code in the '/scripts/index' can work but in '/scripts/auth ' can not work? Should I change anywhere?
    Thanks again.

  145. 145 unknown

    I'm new to the Zend framework and I found this tutorial really useful. Thanks!

  146. 146 Benj_em

    Hey, this tutorial is great! To help improve of course, I did find an error and typo:

    On page. 6, it mentions the init() function. This function was never entered in the previous tutorial on getting started so I pasted the whole thing but got an error having to do with Album.php. That file doesn't exist in the models folder, so the line 'Zend_Loader::loadClass('Album');' must be updated by adding an 's' to 'Albums'.

    That fixes the error!

  147. 147 Benj_em

    Also I wanted to mention that I could not find any mention of 'header.phtml' or 'footer.phtml' in 'Getting Started...' Maybe I'm missing another tutorial in between?
    In any case, those files can just go in the 'views/scripts' folder and they don't need their own opening and closing tags since they're basically includes.
    Then the header/footer include lines should be placed within the layout.phtml file rather than the login.phtml file so you can see your user name on the index view scripts.
    I hope that helped any other confused person.

  148. 148 erz

    Hello and thanks for these great tutorials. I would love to see an updated version of this so it works with the new Getting started tutorial.

  149. 149 Sims

    I will second what erz has said. This is not to be lazy rather to reflect what it says:

    "This tutorial is intended to give a very basic introduction to using the Zend_Auth component
    with the Zend Framework. It builds on the previous tutorial “Getting Started with the Zend
    Tutorial” which is available at http://akrabat.com/zend-framework-tutorial."

    Either it should be made clear that this tutorial no longer has much in common with the previous tute or it should be updated. Otherwise unsuspecting readers with be confused.

    Off me goes to read more docs... ;)

  150. 150 Rob...

    I have made the version text red and bolded so that it's clearer!

    Regards,

    Rob...

  151. 151 sims

    Nice! Yes, I think that does the trick!

    BTW, I learned a lot from your tutorial no matter the version. d

  152. 152 alejandro rosales

    Good book, it works on version 1.7, what changes i need to do to it works on version 1.8.x. how i need to change de bootstrap? Hi to everybody

  153. 153 Jagat

    Hi,

    Thanks A Lot for The Nice Tutorial & Sample Code.

  154. 154 rakesh

    Hi Rob,

    I am getting Page Load Error while clicking submit button of my form. Its giving error as "The connection to the server was reset while the page was loading" "The network link was interrupted while negotiating a connection."

    Same form is working fine earlier I don't know what I have changed making this error

    Any suggestions
    thanks
    rakesh

  155. 155 ck

    Hey Rob, great site, great zf tutorials - I was wondering if and when you were going to re-do this tutoral for zf 1.9?

  156. 156 Rob...

    ck,

    It's on my list to be done. The list is much longer than I'd like though :(

    Regards,

    Rob...

  157. 157 dguiarj

    Hi Rob,

    Great tutorials in did!

    I manage to mix this tutorial with the more recent "Getting Started with the Zend
    Tutorial" (Zend 1.9) of yours... (I also did mix some Dojo frontEnd on it)

    Its not that hard to mixit (at least the way a maded)... but I dont know if im going in the right direction here!

    At layout.php I added some dojo code like:

    between the "css/site.css" and the "" :

     
    $this->dojo()->enable()
    ->setDjConfigOption('isDebug'true)
    ->setDjConfigOption('parseOnLoad'true);
    
    if ($this->dojo()->isEnabled()){
        //$this->dojo()->setLocalPath($this->baseUrl().'Dojo/dojo/dojo.js')
        $this->dojo()->setLocalPath('http://YOUR_DOJO_PLACE/Dojo/dojo/dojo.js')
    ->addStyleSheetModule('dijit.themes.tundra')               ->addStyleSheetModule('dojo.resources')
    ->addStyleSheetModule('dojox.resources')
    ->addStyleSheetModule('dojox.grid.resources')
    ->addStyleSheetModule('dojox.grid._grid');
        $this->dojo()->requireModule('dojo.parser')               ->requireModule('dijit.Toolbar')          ->requireModule('dijit.Menu')             ->requireModule('dojox.grid.DataGrid')    ->requireModule('dijit.form.ValidationTextBox')
    ->requireModule('dijit.TitlePane')
    ->requireModule('dijit.form.Form')
    ->requireModule('dijit.dataGrid')
    ->requireModule('dijit.form.FilteringSelect');
        echo $this->dojo();
    
    

    the goes as

    and after the body:

    
       user) : ?>
        hasIdentity()) : ?>
         Logged in as
        escape($this->user->real_name); ?>.
        <a href= "baseUrl; ?>/auth/logout">Logout
         
    

    At the "AuthController" u change the "loginAction" adding (at top):

    
                $form = new Form_Login();
                $form->setMethod('post');
                $this->view->form $form;
    
    

    At "logoutAction":

    
            $auth Zend_Auth::getInstance();
            $auth->clearIdentity();
            $this->_redirect('/');
    
    

    Create a form (at application->forms->Login.php) with:

    
    setName('frmLogin');
            $username = new Zend_Dojo_Form_Element_ValidationTextBox('username');
            $username->setLabel('Login: ')
                    ->setRequired(true)
                    ->setRegExp("[wd]*");
            $password = new Zend_Dojo_Form_Element_PasswordTextBox('password');
            $password->setLabel('Senha: ')
                    ->setRequired(true)
                    ->setRegExp("[dw]*");
            $submit = new Zend_Dojo_Form_Element_SubmitButton('Ok');
            
            $this->addElements(array($username,$password,$submit));
        }
    }
    
    

    And "login.phtml" goes like:

    
    escape($this->title); ?>
    message)) :?>
        escape($this->message);?>
    
    form;
    ?>
    

    Its working... but at layout.phml the:

    "$this->escape($this->user->real_name);"

    dont return blank (but its filled at db)

    Now Im kinda a lost... I would like to build a dojo "menu" using ACL... =P

    PS: (I use Dojo 1.3... at public directory)

    Best regards!

  158. 158 yafa

    Can you please repeat this Zend_Auth form example for the last version of ZF?

    Thanks

  159. 159 dguiarj

    @yafa
    Sorry... there is many parts of my code that need some work and might be missing somethings...

    The "class" for the "form" goes like:
    (But to use it u most have the dojo "included" on your default layout as I post)

    It have a "minor" javascript (dojo) validation that sets user and pass to be a alphanumeric charset (by regex)

    class Form_Login extends Zend_Dojo_Form
    {
    // public function __costructor($options)
    public function init ()
    {
    //parent::__construct($options);
    $this->setName('frmLogin');
    $username = new Zend_Dojo_Form_Element_ValidationTextBox('txtUserName');
    $username->setLabel('Login: ')
    ->setRequired(true)
    ->setRegExp("[\w\d]*");
    $password = new Zend_Dojo_Form_Element_PasswordTextBox('txtPassword');
    $password->setLabel('Password: ')
    ->setRequired(true)
    ->setRegExp("[\d\w]*");
    $submit = new Zend_Dojo_Form_Element_SubmitButton('Ok');

    $this->addElements(array($username,$password,$submit));
    }
    }class Form_Login extends Zend_Dojo_Form
    {
    // public function __costructor($options)
    public function init ()
    {
    //parent::__construct($options);
    $this->setName('frmLogin');
    $username = new Zend_Dojo_Form_Element_ValidationTextBox('txtUserName');
    $username->setLabel('Login: ')
    ->setRequired(true)
    ->setRegExp("[\w\d]*");
    $password = new Zend_Dojo_Form_Element_PasswordTextBox('txtPassword');
    $password->setLabel('Password: ')
    ->setRequired(true)
    ->setRegExp("[\d\w]*");
    $submit = new Zend_Dojo_Form_Element_SubmitButton('Ok');

    $this->addElements(array($username,$password,$submit));
    }
    }

  160. 160 Christian

    I Really wish this tutorial was updated to work with the lastest ZF and your other tutorial "Getting started with ZF.."

The views expressed in these comments are not the views of the publisher. However, we believe in the rights of others to express their legitimate views and concerns. Any legitimate complaint emailed to rob@akrabat.com will be seriously considered and the post reviewed as desirable and necessary.

Leave a Reply

Buy now!