简体   繁体   English

保持苗条的会话

[英]Persisting Sessions in Slim

I'm working on a web app using Slim, but I'm facing an issue with setting and persisting sessions. 我正在使用Slim开发Web应用程序,但是在设置和保持会话期间遇到了问题。

Here is my index.php . 这是我的index.php I am trying to set a csrfToken key in the $_SESSION array, so that every request that is made through the app checks if the user has a csrfToken key, if not it will create one. 我试图在$_SESSION数组中设置一个csrfToken密钥,以便通过应用程序发出的每个请求都检查用户是否具有csrfToken密钥,如果没有,它将创建一个。

I'm just confused as to why it isn't persisting because on the next request it's gone. 我只是困惑为什么它不持久,因为在下一个请求中它已经消失了。 session_start is being called, it's being called automatically by '\\Slim\\Middleware\\SessionCookie'. session_start被调用,它被'\\ Slim \\ Middleware \\ SessionCookie'自动调用。

Any ideas why this wouldn't be working? 有什么想法为什么这行不通吗? And would it be better to place this into middleware or use a hook? 最好将其放入中间件或使用挂钩吗?

use duncan3dc\Laravel\Blade;
use duncan3dc\Helpers\Env;

# TODO: Bootstrap the app. Move this to a seperate file. Dev only.
R::setup('mysql:host=localhost;dbname=somedb','user','pass');

$app = new \Slim\Slim(array(
  'mode' => 'development',
  'templates.path' => './views',
  'cookies.encrypt' => true,
  'cookies.secret_key' => 'mylongsecretkey',
  'cookies.cipher' => MCRYPT_RIJNDAEL_256,
  'cookies.cipher_mode' => MCRYPT_MODE_CBC
));

$app->add(new \Slim\Middleware\SessionCookie(array(
  'expires' => '10 minutes',
  'path' => '/',
  'domain' => 'site.com',
  'secure' => false, # Contact client to discuss using SSL
  'httponly' => false,
  'name' => '_sus',
  'secret' => 'mylongsecretkey', # Do I need this twice?
  'cipher' => MCRYPT_RIJNDAEL_256,
  'cipher_mode' => MCRYPT_MODE_CBC
)));

# Not persisting ...
if(!isset($_SESSION['csrfToken']))
    $_SESSION['csrfToken'] = hash("sha512",mt_rand(0,mt_getrandmax()));

# TODO: Bootstrap these.
require 'routes/index.php';
require 'routes/dashboard.php';
require 'routes/signup.php';
require 'routes/contactus.php';
require 'routes/privacypolicy.php';
require 'routes/testimonials.php';
require 'routes/login.php';

$app->run();

I figured out how to do it after reading more into hooks . 在深入了解hooks之后,我想出了解决方法。

$app->hook('slim.before.router', function() use ($app){
    if(!isset($_SESSION['csrfToken']))
        $_SESSION['csrfToken'] = hash("sha512",mt_rand(0,mt_getrandmax()));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM