Problem for keep session after http request [SOLVED]

Hi everyone,

Can you help me please?

I want that keep my data session after other url call, i saw session slim
my routing file

$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);

/**** api for payment ****/
$app->get('/oauth2/init', function (Request $request, Response $response, array $args) {
	// Mollie
 
	$_SESSION['test'] = 'test';
	
})->setName('init');
   
$app->get('/oauth2/code', function (Request $request, Response $response, array $args) {
     echo $_SESSION['test'] ; // here it's null
	
	return ''";
})->setName('code');

I tried in index.php but don’t work for me

<?php
session_cache_limiter(false);
session_start();

Thanks.

Which version of Slim are you using? Note the doc you linked to is for the old version 2 of Slim, not the current version 3. (Although it shouldn’t matter much.) I assume you are using a client that supports sessions?

Thanks for you response,

I use slim 3.1, i’m new with slim framework :slight_smile: . what do you mean by client(library)? I want just use native php sessioni don’t understand why data session is unset after each http call. how i have to do for that please?

With a simple php script without slim if i test GET session run perfectly and data session not unset on my debian, so problem it’s with slim :frowning:
Thanks for you help.

Hi!

Please try it without session_cache_limiter(false); first.

Then add a session middleware like this:

use Slim\Http\Request;
use Slim\Http\Response;

// Session middleware
$app->add(function (Request $request, Response $response, $next) {
    session_start();
    
    return $next($request, $response);
});

Change the return value of oauth2/code:

$app->get('/oauth2/code', function (Request $request, Response $response, array $args) {
    $response->getBody()->write(session_id() . ': ' . $_SESSION['test']);

    return $response;
})->setName('code');

Then open

  1. {your-domain}/oauth2/init
  2. {your-domain}/oauth2/code

Thanks odan,

dosn’t work :frowning: it’s problem with my logical code? I post full code (probleme it’s after i use header in my authentification with $salesforce->authentification())
<?php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Slim\Middleware\Session as SESSION;

// Routes
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);

// Session middleware
$app->add(function (Request $request, Response $response, $next) {
session_start();   
return $next($request, $response);
});

/**** api for payment ****/
$app->get('/oauth2/init', function (Request $request, Response $response, array $args) {
	 $_SESSION['test'] = 'test';
	// Mollie	
	$oauth2 = new \Service\MollieOauth2();
	$db = new \Config\db();
	$mollie = new \Service\Mollie($oauth2, $db->connect());
	$payments = $mollie->get_payments();
	
	if(empty($payments)) die('no payments');
	
	$salesforce = new \Service\Salesforce($payments);	
	$_SESSION['salesforce'] = $salesforce;
	 
	$salesforce->authentification();
	return $response;
	
})->setName('init');


$app->get('/oauth2/code', function (Request $request, Response $response, array $args) {
	$response->getBody()->write(session_id() . ': ' . $_SESSION['test']);
	var_dump($_SESSION);echo '  problem session ';
	$params = $request->getQueryParams();
	$code = (!empty($params['code'] )) ? $params['code'] : '';

	if(!empty($_SESSION['salesforce']) && $code !== '')
	{
		$salesforce = $_SESSION['salesforce'];
}else{
		die('problème with authentification');
	}
	
	$salesforce->code_oauth2($code);

	
	return $response;
})->setName('code');

my function authentification i use a header i taken reference from oauth salesforce php it’s prossible problem from here

/************** authentification oauth2 with salesforce     ***************/
		public function authentification()
		{
			
			$redirect = $this->callbackOauth2Uri .'/code';
			
			//$redirect = self::LOGIN_URI . 'services/oauth2/success';
			$auth_url = self::LOGIN_URI . "/authorize?response_type=code&client_id="
				. self::CLIENT_ID . "&redirect_uri=" . urlencode($redirect);
			header('Location: ' . $auth_url);die();

		}

i get
array(0) { }

Edit: I resolve it like that with middleware:

// Session middleware
$app->add(function (Request $request, Response $response, $next) {
if(empty($_SESSION)) session_start();
session_regenerate_id(true);   
$response = $next($request, $response);
session_write_close();
return $response;
});

session_regenerate_id(true) and session_write_close() it’s impotant!

Thanks again for your time and help :slight_smile:

Ok, cool :slight_smile:

PS: You can check whether the PHP session has already been started in this way:

// Session middleware
$app->add(function (Request $request, Response $response, $next) {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    session_regenerate_id(true);    // not recommend here
    $response = $next($request, $response);
    session_write_close();

    return $response;
});

Edit: The session id must be changed (with session_regenerate_id(true);) at any transition in authentication state and only at authentication transitions.

1 Like

I’d like to ask a quick question about this thread - seems I have a similar issue, but I don’t use a closure to handle the routing in my app, I use a callable class structures/methods. I am correct to assume that the middleware would have to be added to the route definition to execute? For example :

$app->get('/', Infraweb\IndexUI::class.':home')
->setName('ui-home')
->add($middleware);

If that’s the case, how would it be invoked if there is no __invoke() function to resolve the middleware requirements? Would it need to be explicitly called similarly to this in the home() function in the example:

($obj->middleware)();

Or does this just execute somewhere in the chain of events? Before or after the class class callable method handler? Kinda confusing, no matter what I’ve done to this point (native php sessions or any of the slim session packages) the session values just vanish somewhere in the ether. I’m I doing something cement headed here? Any thoughts, ideas, constructive criticisms?

Thanx in advance…

You are not limited to defining a function for your routes. In Slim there are a few different ways to define your route action functions.

Read more: http://www.slimframework.com/docs/v3/objects/router.html#container-resolution

You are using the Class:method style for routing, which means Slim creates an instance from the class \Infraweb\IndexUI and invokes the public home() method.

If you would make use of “Single Action Controllers” by defining routes with this syntax:
$app->get('/', MyAction::class) then you need a __invoke() method within the class MyAction.

The problem with this syntax ->add($middleware) is that you don’t make use of the Slim container. I know this documented in the Slim docs, but better let the container (factory) create all application services for you. Also for performance reasons it’s better to create middleware instances only when it is really necessary:

->add(\App\Middleware\MyMiddleware::class)