# Problem for keep session after http request \[SOLVED\]

**URL:** <https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724>\
**Category:** Questions\
**Created:** [October 12, 2018, 2:41pm UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724 "2018-10-12T14:41:40Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![kevin2](https://avatars.discourse-cdn.com/v4/letter/k/bcef8e/32.png) [@kevin2](https://discourse.slimframework.com/u/kevin2)\
**Post date:** [October 12, 2018, 2:41pm UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724/1 "2018-10-12T14:41:40Z")

</div>

Hi everyone,

Can you help me please?

I want that keep my data session after other url call, i saw [session slim](https://www.slimframework.com/docs/v2/sessions/native.html)  
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

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

```

Thanks.

---

<div class="post-metadata">

**Author:** ![tflight](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/tflight/32/1205_2.png) [@tflight](https://discourse.slimframework.com/u/tflight)\
**Post date:** [October 12, 2018, 8:14pm UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724/2 "2018-10-12T20:14:35Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![kevin2](https://avatars.discourse-cdn.com/v4/letter/k/bcef8e/32.png) [@kevin2](https://discourse.slimframework.com/u/kevin2)\
**Post date:** [October 13, 2018, 7:16pm UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724/3 "2018-10-13T19:16:49Z")

</div>

Thanks for you response,

I use slim 3.1, i’m new with slim framework 🙂 . 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 ☹  
Thanks for you help.

---

<div class="post-metadata">

**Author:** ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)\
**Post date:** [October 14, 2018, 9:20am UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724/4 "2018-10-14T09:20:22Z")

</div>

Hi!

Please try it without `session_cache_limiter(false);` first.

Then add a session middleware like this:

```php
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`:

```auto
$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

---

<div class="post-metadata">

**Author:** ![kevin2](https://avatars.discourse-cdn.com/v4/letter/k/bcef8e/32.png) [@kevin2](https://discourse.slimframework.com/u/kevin2)\
**Post date:** [October 14, 2018, 10:49am UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724/5 "2018-10-14T10:49:37Z")

</div>

Thanks odan,

dosn’t work ☹ 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](https://github.com/rdehler/php-oauth-salesforce) 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 🙂

---

<div class="post-metadata">

**Author:** ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)\
**Post date:** [October 15, 2018, 10:15am UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724/6 "2018-10-15T10:15:35Z")

</div>

Ok, cool 🙂

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

```php
// 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.

---

<div class="post-metadata">

**Author:** ![doktor1360](https://avatars.discourse-cdn.com/v4/letter/d/8e7dd6/32.png) [@doktor1360](https://discourse.slimframework.com/u/doktor1360)\
**Post date:** [March 10, 2019, 12:14am UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724/7 "2019-03-10T00:14:26Z")

</div>

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…

---

<div class="post-metadata">

**Author:** ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)\
**Post date:** [March 10, 2019, 10:51am UTC](https://discourse.slimframework.com/t/problem-for-keep-session-after-http-request-solved/2724/8 "2019-03-10T10:51:50Z")

</div>

> 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: [Router - Slim Framework](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](http://www.slimframework.com/docs/v3/concepts/middleware.html#Route%20middleware), 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)`
