好吧,这并不是真正的问题,但我检查用户是否存在并将其登录并重定向到 site/members_area,但我不想将用户发送到特定页面,但我想重新加载当前控制器。
因此,如果我登录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();
}
}
我自己解决了这个问题,方法是在标头中设置一个始终提交到一个登录控制器的登录表单,但问题是标头登录表单(出现在每一页上)始终有一个名为“重定向”的隐藏输入,实际登录控制器会捕获该输入...
这是基本设置(确保 url 帮助程序已加载):
标题登录表单
<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>
登录控制器表单
<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>
最好的部分是,您可以在失败时继续设置重定向,并且仅当您从其他地方登录时才会设置重定向输入。
控制器
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");
}
这里发生的事情是这样的:
- 用户在不同的页面登录。
- 登录表单提交到单个登录控制器,其中包含一个隐藏的输入元素,说明他们从哪里登录。
- 登录控制器处理登录,然后根据输入进行重定向。
- 登录失败时,重定向会再次设置,因此无论如何,用户都会返回到原始页面。
这只是一个基本的例子。显然,您可以根据需要对其进行调整。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)