我正在使用zend framework-2做项目。我想通过URL限制对某些web目录的访问(如果用户没有登录)。如果用户尝试登录,我需要重定向登录页面。这就是我所做的(粗略的想法而不是代码)。
AuthController
if(username and password ok){
setcookie('username', $username);
setcookie('password', $password);
//redirect to AlbumController indexAction
return $this->redirect()->toRoute('album', array('controller' => 'album', 'action' => 'index'));
}因此,我在AlbumControoler中添加了以下代码
public function indexAction()
{
if(isset ($_COOKIE['username']) && isset ($_COOKIE['password'])){
//some codes
}
else{
//if user not logged redirect to loogin page
return $this->redirect()->toRoute('auth', array('controller' => 'auth', 'action' => 'index'));
}
}因此,如果我以这种方式使用,我需要在每个操作中添加上述代码。所以我的问题是这样行吗?还是说这是他们的简单方法?
发布于 2012-11-30 16:03:57
作为实际问题的答案,你可以在你的控制器构造中这样做……就像这样..。
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController {
public function __construct() {
$session = new \Zend\Session\Container('auth');
if ( !isset($session->name) || !is_string($session->name) ) {
echo "The following is not set:".$session->name;
header('Location: /user/login');
exit();
}
}但正如之前的帖子所指出的那样,cookie用来做这样的事情真的很糟糕。这是一个非常通用的示例,尽管exit();部分在这个意义上非常重要,因为您想要终止脚本,以便在用户在浏览器上按Esc键的情况下不显示任何数据。exit();实际上将会终止,并且不会显示任何内容。
https://stackoverflow.com/questions/13639746
复制相似问题