How to allow access to authorized members in Zend using Zend_Session_Namespace

You can maintain and manage sessions and cookies in Zend framework just like you can do in normal PHP code or any other language/framework. Zend provides the Zend_Session_Namespace which allows you to create and manage sessions. Once you have created a session variable you can then use it to authorize a user’s access to any web page. You can use it by placing the code in the init() action event of the controller which you wish to restrict access to only authorized members of the website. The init() action event is executed first by the controller before any other action event. Therefore it’s the best place to put this code.

Consider the following code

public function init() {
	$uid = new Zend_Session_Namespace('uid');
	if (isset($uid->id)) {
               // Do nothing here
	}
	else {
               // Take the user to the login page
		$this->_helper->redirector('index','login');
	}			
}

The above code checks for a uid session variable. If it has been created then it means that the user has successfully logged into the system. If not then the user is taken to the login page to login into the system. You can also use an intermediary page to display any custom message to the user instead of redirecting to the login page.

Hope the above helped. Let me know how it went for you. I appreciate your comments.

Leave a Comment