嗯,这不是一个真正的问题,但我检查用户是否存在并登录并重定向到站点/members_area,但我不想将用户发送到特定页面,但我想重新加载当前 Controller 。
因此,如果我在 index/home 中登录,我想在 index/home 上重定向,我应该如何进行?
在常规 php 中,我会执行重定向到当前页面的操作
<?php echo $_SERVER['PHP_SELF']; ?>
这是框架中的代码
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area'); //<-- this line here should be dynamic
}
else // incorrect username or password
{
$this->index();
}
}
最佳答案
我自己解决了这个问题,在 header 中有一个登录表单,它总是提交给一个登录 Controller ,但问题是 header 登录表单(出现在每个页面上)总是有一个隐藏的输入,称为重定向,实际登录 Controller 捕获它...
这是基本设置(确保加载了 url helper):
标题登录表单
<form action="/login" method="post">
<input type="hidden" name="redirect" value="<?php echo current_url(); ?>" />
<input type="text" name="username" value="" />
<input type="password" name="password" value="" />
<input type="submit" name="login" value="Login" id="submit">
</form>
登录 Controller 表单
<form id="login" action="" method="post">
<input type="text" name="username" id="username" value="" />
<input type="password" name="password" id="password" value=""/>
<?php if(isset($_POST['redirect'])) : ?>
<input type="hidden" name="redirect" value="<?php echo $_POST['redirect']; ?>" />
<?php endif; ?>
<input type="submit" name="login" id="submit" value="Login" />
</form>
最好的部分是您在失败时继续设置重定向,并且只有在您从其他地方登录时才会设置重定向输入。
Controller
function index()
{
if( ! $this->form_validation->run())
{
// do your error handling thing
}
else
{
// log the user in, then redirect accordingly
$this->_redirect();
}
}
function _redirect()
{
// Is there a redirect to handle?
if( ! isset($_POST['redirect']))
{
redirect("site/members_area", "location");
return;
}
// Basic check to make sure we aren't redirecting to the login page
// current_url would be your login controller
if($_POST['redirect'] === current_url())
{
redirect("site/members_area", "location");
return;
}
redirect($_POST['redirect'], "location");
}
这里发生的事情是这样的:
这只是一个基本的例子。您显然可以根据需要调整它。
关于codeigniter:登录后如何重定向到当前 Controller (常规 php 中的 php_self),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2652930/