简体   繁体   中英

apply and call a session in different controllers

I am using zend framework. I have built a simple login screen. when the user logs in, I want to set a session and then in the init function of the member area controller its meant to check for the session and grant access, else, redirect to login screen.

I have set my login controller like so, this check the username and password and sets the session:

if (isset($_POST['loginSubmit']) && $form->isValid($_POST)){
            $inputtedUsername = $_POST['username'];
            $inputtedPassword = $_POST['password'];
            if ($inputtedUsername == $username && $inputtedPassword == $password) {
                $loggedIn = new Zend_Session_Namespace('loggedIn');
                $loggedIn->success;
                $this->_forward('index', 'home');
            } else {
                echo 'invalid';
            }
        }

I have a home controller, which only logged in users should be able to see, so in the innit function I have: $loggedIn = new Zend_Session_Namespace('loggedIn');

if (isset($loggedIn->success)) {
            echo 'success';
        }else{
            $url = $this->view->url(array(
                'controller' => 'index',
                'action' => 'index'));
            header('Location:' . $url);
        }
    }

when i log in, using the correct credentials, it redirects me to login screen as stated in the else function.

what am i doing wrong?

First your use of Zend_Session_Namespace is incomplete (you never assigned a value to the namespace):

$loggedIn = new Zend_Session_Namespace('loggedIn');//here you created a namespace
$loggedIn->success;//here you created a key in that namespace with no value

The way your code seems to be structured any value assigned to $loggedIn->success would return true, so maybe try :

$loggedIn = new Zend_Session_Namespace('loggedIn');//here you created a namespace
$loggedIn->success = true;

While this might fix your current issue, I want to suggest you take a look at two Zend components that can really help with authentication and authorization.

The first is Zend_Auth , a component that deals with application authentication and will also help handle user session persistence. Rob Allen has a tutorial to help get you started.

The second is Zend_Acl , The Access Control List component, deals with authorization, who has access to what. A place to start with Zend_Acl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM