flash session starting session啥意思

用Laravel开发应用,把原有的代码copy过来,以前的代码session使用了$_SESSION,本以为移植过来可以很好的运行的,因为没有依赖其他的组件,结果出现了这个
Undefined variable: _SESSION
Laravel的session的配置文件配置在 app/config/session.php 中,使用时可以看看 session 配置文件中可用的选项设定及注释。
Laravel 默认使用 file 的方式来实现 session的。她并不用php原生的$_SESSION(php原生的session要看php.ini的位置),所以忽略php相关的session函数,例如session_start(), $_SESSION。Laravel在运行过程中会在app/storage/session/目录写入session的信息,所以这个目录需要有写权限,否者session就无法写入成功。
Laravel除了使用默认的file作为session的实现,还支持cookie, Memcached, Redis 和数据库的后端驱动作为session的实现。必要的时候还需要自己实现一个session的实现方式,比如在微信公众账号和用户的交互,这中session就无法直接使用,因为每次都是微信服务器来请求,无法通过请求的来源来辨别用户。
laravel的session简要API
Session的API还是比较简单的,大家看看也大概知道是怎么个意思。但是有那么几个还不太好理解。
//session的永久保存(在不过期范围内)
Session::put('key', 'value');
//等同于PHP的原生session
$_SESSION['key'] = 'value';
$value = Session::get('key', 'default');
//去除操作并删除,类似pop概念
$value = Session::pull('key', 'default');
//检测是否存在key
Session::has('users');
Session::forget('key');
这个对应只要session不过期,基本上是永久保存,下次http请求也是存在的。不同于下面的flash概念。
laravel的session中flash概念
但是Laravel出了个快闪flash的概念,把我一下子给搞混了。这个flash两次请求有效(本次和下次请求有效),与本次请求取操作多少次无关。
//保存key,value
Session::flash('key', 'value');
//取值方法还是一样的
Session::get('key');
//刷新快闪数据时间,保持到下次请求
Session::keep(array('username', 'email'));
这个flash的概念和上面的put的概念不太一样。
:这个对应只要session不过期,基本上是永久保存,下次请求也是存在的。
flash :保存的值,本次请求可以使用,下次http请求可以使用,再下一次就不存在了。
也就是说下一次的请求用完就被销毁了,不会让session的值变的越来越大,可以保存一些临时的数据。
这中情况的使用场景比如有:
用户请求了页面,出现错误信息,重定向到一个新的页面,需要展示之前的数据。(虽然可以通过url参数来传递,处理不好可能会有xss漏洞)。
用户访问了一个页面,过滤器发现没权限,保存当前页面url,重定向到登录页面,登录成功,取出值,重定向到原先的页面。(这里可能需要刷新保存的快闪数据)
session落地的时间
我天真的以为使用了Session::put函数就能保存这个变量了。于是我的代码这样写:
class LoginController {
public function login(){
Session::put('key','value');
print_r( Session::all() ); //取出来看看是否put成功
//习惯性的调试都exit,不执行后续代码
//return Redirect::to(/); 框架在return后还会有后续的代码执行的
结果下次请求就是找不到本次的Session,而且看app/storage/session目录就是没有文件生成。总感觉不对劲啊。
后来看到网络上有个方法Session::save(),于是我也用了下,居然发现成功的生成了session的文件。于是我感觉到,Laravel不用php原生的session,那么在controller之后应该做了一些事情,将session写入到文件中,而不是每次put操作都写操作,这样会IO操作太频繁的,影响性能的。
查看调用相关的代码。laravel编译后,在bootstrap/compiled.php中
class Middleware implements HttpKernelInterface
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
$this-&checkRequestForArraySessions($request);
if ($this-&sessionConfigured()) {
$session = $this-&startSession($request); // 启动session
$request-&setSession($session);
$response = $this-&app-&handle($request, $type, $catch); // 调用controller的method
if ($this-&sessionConfigured()) {
$this-&closeSession($session);
//关闭session
$this-&addCookieToResponse($response, $session);
protected function closeSession(SessionInterface $session)
$session-&save();
// 保存session
$this-&collectGarbage($session);
小提示:如果不知道函数调用情况,可以在controller中throw new Exception();,然后在/config/app.php的debug更改为debug=&true。可以看到函数的调用关系。
可以看见,在调用完controller之后,调用了session-&save()的方法,来主动的保存session。这样session才能落地保存起来,如果在controller或者view里面写了,那么session是不会被保存的,除非主动的写Session::save()才能手工的保存起来。因此在debug调试的时候千万要注意啊。
声明:未经允许禁止转载 东东东
陈煜东的博客 文章,谢谢。如经授权,转载请注明: 转载自本文链接地址:
相关文章推荐:
Copyright & 2018asp.net flash上传文件session丢失问题?_百度知道
asp.net flash上传文件session丢失问题?
程序是asp.net mvc
由于flash上传文件时候,没有将页面的session_id传递至后台,所以我手动将页面的session_id传递过去,然后按照网上的做法在Global.asax文件中添加了Application_BeginRequest函数,向当前请求添加了ASP.NET_SessionId的cookie信息,但是处...
我有更好的答案
PostAuthenticateRequest += new EventHandler(RebuildPrincipal);
private void BuildSwfuploadAuthorizeCookie(object sender.AddHours(1), EventArgs e)
if (base.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
return, auth_cookie_Value).Form[&SwfUpload&quot.asax文件中.Request这是我的一个项目的flash上传cookies问题解决方法:在 Global:public override void Init()
this.BeginRequest += new EventHandler(BuildSwfuploadAuthorizeCookie);] == null)
HttpCookie cookie = new HttpCookie(auth_cookie_name.N
string auth_cookie_name = FormsAuthentication.FormsCookieN
string auth_cookie_Value = (
cookie.Expires = DateTime.Request.Form[auth_cookie_name]) ?? &&;
采纳率:36%
为您推荐:
其他类似问题
flash上传的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。Session中的flash一般是在什么情况下用呀? - CNode技术社区
There is nothing noble in being superior to some other man.The true nobility is being supior to your previous self.
在学习《第1章 一个简单的博客》中,看到了nswbmw使用了flash。虽然他大致讲解了flash的作用,但是小白我查了好久还是不明白为什么要用flash呀,求大家科普。
在nswbmw的文中他使用了flash用来显示注册的成功与否,然后让res重定向。我困户的地方是为什么他要这么麻烦的使用这种方法,为什么不直接发送注册成功或者失败的页面呢?感觉使用重定向岂不更麻烦了?我们在实际应用中是怎样使用flash的呢,能举个例子么?
另外就是connect-flash中使用flash的时候为什么是req.flash(…),而不是res.flash(…)?flash不应该是要返回给客户端的么?感觉上req不应该发送给客户端吧。
一般创建成功的提示,只显示一次,下一次就没了,此时使用flash
最早rails里有的,只1次作用
比如有一个博客,你做如下操作:
1、新增一篇博客,写好了然后发布
2、跳转到博客列表页或者博客首页,并且显示“发布成功”
3、刷新这个页面或者下次再进入这个页面就不会显示“发布成功”了
这个临时的状态就用flash,用了一次就销毁。
connect-flash是个通用中间件。。也就是在session里存储一个变量,展示完之后立即清除。
flash通常与重定向结合使用,确保消息可到下一个页面呈现。因为在session里 所以是req。
原理同: req.session.flash=“string”
貌似不用也麻烦不了多少
Flash data when set will be saved to the user’s session for exactly one more request.
CNode 社区为国内最专业的 Node.js 开源技术社区,致力于 Node.js 的技术研究。
服务器赞助商为
,存储赞助商为
,由提供应用性能服务。
新手搭建 Node.js 服务器,推荐使用无需备案的在 SegmentFault,学习技能、解决问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
这个问题并不是代码或异常方面的问题,而是理解方面的问题(我在网上查了相关问题,都是使用或用途方面的)。
如果这其中有我个人知识边界上的缺陷,或者大家觉得要把这个问题讲清楚会很绕,我很抱歉打扰大家,这个问题不论是问还是答都会很绕,如果大家能为我解释清楚,非常感谢。
我在学习ROR tutorial 这套教程中知道如何使用cookies 和 session,可是我并不明白这两个东东的实质,我并不是说它们用来干什么,而是它们是什么,tutorial只说它们是对象。
在用户登录这一节,写sign_in方法的时候,特别说明self.current_user这里一定要加self,如果写成current_user = user, 解释器会把它理解为一个局部变量的赋值,那么其它地方就使用不了current_user(自己的理解),所以self.current_user = user 这句实际上不是一个赋值,而是一个方法调用,是调用了current_user=(user)这个赋值方法,而最终本质是,给@current_user这个实例变量赋值,这句用以下三个注释中的任何一句代替都是等价的。
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.hash(remember_token))
# self.current_user = user
# current_user=(user)
# @current_user = user
current_user=(user)
那么,相对于current_user,cookies和session是什么呢,它们也可以在其它方法中调用(如下面平日练习代码),那么它们一定不是局部变量,但它们应该也不是实力变量,因为它们前面没有@,Tutorial里说它们是对象,那它们应该是某个类的实例,就像 @user = User.new 但它们前面没有@, 那会不会类似user = User.new
但这个实例化的对象赋给了一个局部变量,那么他应该是不能在其它方法中使用的,但如下代码所示,它们可以在其它方法中使用。后来我查了Rails API, API的解释如下,其实这个定义的方法我也不太懂,不过我理解到(不知是否正确)session其实是个方法,是个类current_user 这样的,可以赋值,可以取值, 但是session[:return_to] 这样的写法又让我迷惑了, 如果是方法的话还可以这样写么,如果是hash对象就可以这样写,但如果十个hash变量,这就是个局部的,其它方法就不能调用了(我这样理解),所以我觉得很疑惑,session和 cookies这类东西本质是什么,虽然我会用,但是理解上很模糊
session() Link
Source: hide | on GitHub
# File actionpack/lib/action_dispatch/testing/test_process.rb, line 13
def session
@request.session
#平日练习里的代码
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
session.delete(:return_to)
def store_location
session[:return_to] = request.fullpath if request.get?
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
对于 web 开发 cookie, session 是通用的,不管你是 java 还是 rails。 cookie 大家都知道他是存储在浏览器上的。而 session 可已理解为一个用户访问网站期间,服务器存储关于这个用户的信息,用户之间是隔离的。 的存储是由服务端负责的,一般都是利用 cookie 在浏览器存一个 session_id,然后每次请求根据这个 session_id 查找对应的 session。
让你混淆的原因可能是,默认 rails 的 session 存储是利用 cookie 存储 。
flash 是 rails 的特色,其他的语言或者 web 框架可能没有。flash 的生命周期介于 request 和 session 之间,可以在多次 request 传递,直到被消费为止。
分享到微博?
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:
在 SegmentFault,学习技能、解决问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。aura/session - Packagist
Provides session management functionality, including lazy session starting, session segments, next-request-only (&flash&) values, and CSRF tools.
php: &=5.3.0
Requires (Dev)
: OpenSSL generates the best secure CSRF tokens.: Mcrypt generates the next best secure CSRF tokens.: A Library For Generating Secure Random Numbers: PHP 5.x polyfill for random_bytes() and random_int() from PHP 7
BSD-2-Clause
7d2f7d41adb6b83facca
Provides session management functionality, including lazy session starting,
session segments, next-request-only ("flash") values, and CSRF tools.
Installation
This library requires PHP 5.3 we recommend using the latest available version of PHP as a matter of principle. It has no userland dependencies.
It is installable and autoloadable via Composer as .
Alternatively,
or clone this repository, then require or include its autoload.php file.
To run the unit tests at the command line, issue composer install and then vendor/bin/phpunit at the package root. This requires
to be available as composer.
This library attempts to comply with , , and . If
you notice compliance oversights, please send a patch via pull request.
To ask questions, provide feedback, or otherwise communicate with the Aura community, please join our , follow , or chat with us on #auraphp on Freenode.
Getting Started
Instantiation
The easiest way to get started is to use the SessionFactory to create a Session manager object.
$session_factory = new \Aura\Session\SessionFactory;
$session = $session_factory-&newInstance($_COOKIE);
We can then use the Session instance to create Segment objects to manage session values and flashes. (In general, we should not need to manipulate the Session manager directly -- we will work mostly with Segment objects.)
In normal PHP, we keep session values in the $_SESSION array. However, when different libraries and projects try to modify the same keys, the resulting conflicts can result in unexpected behavior. To resolve this, we use Segment objects. Each Segment addresses a named key within the $_SESSION array for deconfliction purposes.
For example, if we get a Segment
for Vendor\Package\ClassName, that Segment will contain a reference to $_SESSION['Vendor\Package\ClassName']. We can then set() and get() values on the Segment, and the values will reside in an array under that reference.
// get a _Segment_ object
$segment = $session-&getSegment('Vendor\Package\ClassName');
// try to get a va
// if it does not exist, return an alternative value
echo $segment-&get('foo'); // null
echo $segment-&get('baz', 'not set'); // 'not set'
// set some values on the segment
$segment-&set('foo', 'bar');
$segment-&set('baz', 'dib');
// the $_SESSION array is now:
// $_SESSION = array(
'Vendor\Package\ClassName' =& array(
'foo' =& 'bar',
'baz' =& 'dib',
// try again to get a value from the segment
echo $segment-&get('foo'); // 'bar'
// because the segment is a reference to $_SESSION, we can modify
// the superglobal directly and the segment values will also change
$_SESSION['Vendor\Package\ClassName']['zim'] = 'gir'
echo $segment-&get('zim'); // 'gir'
The benefit of a session segment is that we can deconflict the keys in the
$_SESSION superglobal by using class names (or some other unique name) for
the segment names. With segments, different packages can use the $_SESSION
superglobal without stepping on each other's toes.
To clear all the values on a Segment, use the clear() method.
Flash Values
Segment values persist until the session is cleared or destroyed. However, sometimes it is useful to set a value that propagates only through the next request, and is then discarded. These are called "flash" values.
Setting And Getting Flash Values
To set a flash value on a Segment, use the setFlash() method.
$segment = $session-&getSegment('Vendor\Package\ClassName');
$segment-&setFlash('message', 'Hello world!');
Then, in subsequent requests, we can read the flash value using getFlash():
$segment = $session-&getSegment('Vendor\Package\ClassName');
$message = $segment-&getFlash('message'); // 'Hello world!'
N.b. As with get(), we can provide an alternative value if the flash key does not exist. For example, getFlash('foo', 'not set') will return 'not set' if there is no 'foo' key available.
Using setFlash() makes the flash value available only in the next request, not the current one. To make the flash value available immediately as well as in the next request, use setFlashNow($key, $val).
Using getFlash() returns only the values that are available now from having been set in the previous request. To read a value that will be available in the next request, use getFlashNext($key, $alt).
Keeping and Clearing Flash Values
Sometimes we will want to keep the flash values in the current request for the next request.
We can do so on a per-segment basis by calling the Segment keepFlash() method, or we can keep all flashes for all segments by calling the Session keepFlash() method.
Similarly, we can clear flash values on a per-segment basis or a session-wide bases.
Use the clearFlash() method on the Segment to clear flashes just for that segment, or the same method on the Session to clear all flash values for all segments.
Lazy Session Starting
Merely instantiating the Session manager and getting a Segment from it does not call session_start(). Instead, session_start() occurs only in certain circumstances:
If we read from a Segment (e.g. with get()) the Session looks to see if a session cookie has already been set. If so, it will call session_start() to resume the previously-started session. If not, it knows there are no previously existing $_SESSION values, so it will not call session_start().
If we write to a Segment (e.g. with set()) the Session will always call session_start(). This will resume a previous session if it exists, or start a new one if it does not.
This means we can create each Segment at will, and session_start() will not be invoked until we actually interact with a Segment in a particular way. This helps to conserve the resources involved in starting a session.
Of course, we can force a session start or reactivation by calling the Session start() method, but that defeats the purpose of lazy-loaded sessions.
Saving, Clearing, and Destroying Sessions
N.b.: These methods apply to all session data and flashes across all segments.
To save the session data and end its use during the current request, call the commit() method on the Session manager:
$session-&commit();
N.b.: Per , "Sessions
normally shutdown automatically when PHP is finished executing a script, but
can be manually shutdown using the session_write_close() function."
The commit() method is the equivalent of session_write_close().
To clear all session data, but leave the session active during the current request, use the clear() method on the Session manager.
$session-&clear();
To clear all flash values on a segment, use the clearFlash() method:
To clear the data and terminate the session for this and future requests, thereby destroying it completely, call the destroy() method:
$session-&destroy(); // equivalent of session_destroy()
Calling destroy() will also delete the session cookie via setcookie(). If we have an alternative means by which we delete cookies, we should pass a callable as the second argument to the SessionFactory method newInstance(). The callable should take three parameters: the cookie name, path, and domain.
// assume $response is a framework response object.
// this will be used to delete the session cookie.
$delete_cookie = function ($name, $path, $domain) use ($response) {
$response-&cookies-&delete($name, $path, $domain);
$session = $session_factory-&newInstance($_COOKIE, $delete_cookie);
Session Security
Session ID Regeneration
Any time a user has a change in privilege (that is, gaining or losing access
rights within a system) be sure to regenerate the session ID:
$session-&regenerateId();
N.b.: The regenerateId() method also regenerates the CSRF token value.
Cross-Site Request Forgery
A "cross-site request forgery" is a security issue where the attacker, via
malicious JavaScript or other means, issues a request in-the-blind from a
client browser to a server where the user has already authenticated. The
request looks valid to the server, but in fact is a forgery, since the user
did not actually make the request (the malicious JavaScript did).
Defending Against CSRF
To defend against CSRF attacks, server-side logic should:
Place a token value unique to each authenticated user
Check that all incoming POST/PUT/DELETE (i.e., "unsafe") requests contain
that value.
N.b.: If our application uses GET requests to modify resources (which
incidentally is an improper use of GET), we should also check for CSRF on
GET requests from authenticated users.
For this example, the form field name will be __csrf_value. In each form
we want to protect against CSRF, we use the session CSRF token value for that
* @var Vendor\Package\User $user A user-authentication object.
* @var Aura\Session\Session $session A session management object.
&form method="post"&
&?php if ($user-&auth-&isValid()) {
$csrf_value = $session-&getCsrfToken()-&getValue();
echo '&input type="hidden" name="__csrf_value" value="'
. htmlspecialchars($csrf_value, ENT_QUOTES, 'UTF-8')
. '"&&/input&';
&!-- other form fields --&
When processing the request, check to see if the incoming CSRF token is valid
for the authenticated user:
* @var Vendor\Package\User $user A user-authentication object.
* @var Aura\Session\Session $session A session management object.
$unsafe = $_SERVER['REQUEST_METHOD'] == 'POST'
|| $_SERVER['REQUEST_METHOD'] == 'PUT'
|| $_SERVER['REQUEST_METHOD'] == 'DELETE';
if ($unsafe && $user-&auth-&isValid()) {
$csrf_value = $_POST['__csrf_value'];
$csrf_token = $session-&getCsrfToken();
if (! $csrf_token-&isValid($csrf_value)) {
echo "This looks like a cross-site request forgery.";
echo "This looks like a valid request.";
echo "CSRF attacks only affect unsafe requests by authenticated users.";
CSRF Value Generation
For a CSRF token to be useful, its random value must be cryptographically
secure. Using things like mt_rand() is insufficient. Aura.Session comes with
a Randval class that implements a RandvalInterface. It uses the
function preferentially, then
openssl, or finally mcrypt to generate a random value. If you do not
have one of these installed, you will need your own random-value
implementation of the RandvalInterface. We suggest a wrapper around
Session Lifetime
We can set the session lifetime to as long (or as short) as we like using the setCookieParams on Session object. The lifetime is in seconds. To set the session cookie lifetime to two weeks:
$session-&setCookieParams(array('lifetime' =& '1209600'));
N.b: The setCookieParams method calls
internally.

我要回帖

更多关于 php flash session 的文章

 

随机推荐