我正在学习Zend Framework并遇到Zend_Session_Namespace问题。
以下是该方案:
用户再次点击登录页面。我正在检查isset($ session->名称)以防止再次登录并将其带到其他页面。 - >我在这里失败了。会话以某种方式重置,我不确定我错过了什么。
class IndexController extends Zend_Controller_Action
{
public function init()
{
}
public function indexAction()
{
$session = new Zend_Session_Namespace("login_session");
//Check if the session is already valid
if(isset($session->name)) {
$this->view->userLoggedIn="true";
$this->view->name=$session->name;
}
}
}
class LoginController extends Zend_Controller_Action
{
public function loginaction(){
$session = new Zend_Session_Namespace("login_session");
if(isset($session->name)){
//Redirect to New Page-Already Logged In
} else {
//Authenticate the user and if login is successful
$session->name="USER_NAME";
}
}
}
谢谢。
答案 0 :(得分:1)
除了前面提到的错字之外,这段代码看起来还不错。
您的代码中的某个其他地方可能会无意中覆盖会话命名空间。我想我们至少已经完成了一次。
我建议您不要尝试推出自己的身份验证解决方案,而应使用ZF提供的身份验证解决方案:Zend_Auth
基本的Zend_Auth登录/注销可能如下所示:
//non production code for example only
public function loginAction()
{
$form = new Application_Form_Login();
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$authAdapter = new My_Auth_Adapter($data['username'], $data['password']);
//authenticate
$result = $authAdapter->authenticate();
if ($result->isValid()) {
//store the user object
$auth = Zend_Auth::getInstance();
//access Zend_Auth session namespace
$storage = $auth->getStorage();
$storage->write($authAdapter->getUser());
//add message to flashmessenger
$this->message->addMessage('Welcome');
//redirect to the homepage
return $this->_redirect('/');
} else {
//handle authentication errors
$this->view->loginMessage =
"Sorry, your username or password was incorrect";
}
} else {
//handle form validation errors
$this->_redirect('/users/index/register');
}
} else {
//if not post render empty form
$this->view->form = $form;
}
}
public function logoutAction()
{
$authAdapter = Zend_Auth::getInstance();
$authAdapter->clearIdentity();
}
祝你好运!