我有一个页面,用户登录后就可以访问。如果用户在没有登录的情况下点击页面链接,我想重定向到索引页面。如何做到这一点?
顺便说一句,这是我一直在尝试的代码,它很有效,但我只想知道这是否正确。谢谢
<?php
session_start();
if(!isset($_SESSION['admin_id'])){ //if login option in session is not set then
header("Location: index.php");
}
?>
you can do this by using $_SESSION management.
if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id']))
{
header('Location:'your path');
exit;
}
只需使用一个绝对路径。看看这篇文章中的区别使用绝对路径还是相对路径?
使用Symfony HTTPFoundation组件来处理会话、重定向、HTTP请求、HTTP响应等等。
简短回答:
你可以像这样检查会话并处理重定向:
use Symfony'Component'HttpFoundation'RedirectResponse;
// ...
if ($request->hasPreviousSession() && $request->getSession()->get('admin_id') {
$response = new RedirectResponse('http://success.url');
$response->send();
}
漫长的回答
使用HTTPFoundation与普通PHP相比的优势在于,您可以非常容易地扩展系统的功能,并将代码分割成更小的部分。
"免费"扩展功能的一个简单示例是为会话使用不同的存储引擎(Memcached、Mongo或PDO),而不是本地PHP会话。
您还可以将HTTP Foundation与其他组件(如Symfony Routing和HTTP Kernel)配对。有了这两个,你可以使你的系统
- 具有干净的URL
- 使用配置文件描述的路由
- 解析哪些类(控制器)处理特定请求
- 自动将请求参数注入控制器方法
安装:
使用composer将其安装为您的项目依赖
{
"require": {
"symfony/http-foundation": "~2.5"
}
}
使用:
从PHP全局创建一个Request
对象,如以下
use Symfony'Component'HttpFoundation'Request;
// ...
$request = Request::createFromGlobals();
创建会话并设置值:
use Symfony'Component'HttpFoundation'Session'Session;
// ...
$session = new Session();
$request->setSession($session);
$request->getSession()->set('admin_id', $id);
在重新引导用户之前,请检查会话
use Symfony'Component'HttpFoundation'RedirectResponse;
// ...
if ($request->hasPreviousSession() && $request->getSession()->get('admin_id') {
$response = new RedirectResponse('http://success.url');
$response->send();
}