PHP MVC and setting Session variable

userTester used Ask the Experts™
Hi there,

After validating a user's email and password, where should the user's session variable be set, in the Controller or can it be set in the View? Does it matter where it is set?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2016
It should probably be set in the Controller or the Model.  Views should not change the state of the data model.  Here is an article that is MVC-agnostic - it just shows the basics of PHP client authentication.
Marco GasiFreelancer
Top Expert 2010

As MVC I use CodeIgniter, so I don't know if this can be true for your specific environment, but I usually set session values from the controller. It is possible to do it even in view but the correct way is to keep code in controller (as keeping database stuff in models).
In the controller, you can use standard php $_SESSION array or, it it exists, your framework session class.


Thank you Ray, you provided valuable extra information with that link. Thanks to you too Marco, you basically confirmed what Ray had mentioned.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial