<p>The Yii2 components behave a bit like singletons, you shouldn't create new ones manually. Instead, accessing them over the <code>Craft::$app</code> property is preferred, as you indicated. This should work:</p>
<pre class="lang-php prettyprint-override"><code>$session = Craft::$app-&gt;getSession();
$session-&gt;set(&quot;a&quot;, &quot;b&quot;);
</code></pre>
<p>How are you checking if the session value got set? It's likely you're just looking in the wrong place, the default session component is file-based now if I recall correctly. You can check if a session variable exists and/or what value it holds like this:</p>
<pre class="lang-php prettyprint-override"><code>Craft::dd($session-&gt;has('a'));
Craft::dd($session-&gt;get('a'));
</code></pre>

CC BY-SA 4.0
2021-11-24T16:50:41.587Z
That's exactly what I needed ! 
Thank you very much, it works !
Sylvain Tremblay
CC BY-SA 4.0
2021-11-24T16:41:07.317Z
2021-11-24T16:41:07.317Z
MoritzLost
<p>I'm from custom php world but It looks like I can't just set a session variable in plain php.
I'm playing around</p>
<pre><code>use craft\web\Session;
...
$session = new Session();
$session-&gt;open();
$session-&gt;set(&quot;a&quot;, 'b');
</code></pre>
<p>or other choice, Craft::$app-&gt;getSession()-&gt;set(&quot;a&quot;, &quot;b&quot;);</p>
<p>But i don't see it working, I don't see my storage session added in any way.</p>
<p>What am I doing wrong ?</p>

<session>
Set Session variable inside php controller
# Set Session variable inside php controller

(Asked by: username_0 on 2021-11-24)

I'm from custom php world but It looks like I can't just set a session variable in plain php.
I'm playing around
use craft\web\Session;
...
$session = new Session();
$session->open();
$session->set("a", 'b');

or other choice, Craft::$app->getSession()->set("a", "b");
But i don't see it working, I don't see my storage session added in any way.
What am I doing wrong ?

**Tags:** session

---

## 1 answers

### Answer by username_1 on 2021-11-24. Score: 1 | Accepted answer

The Yii2 components behave a bit like singletons, you shouldn't create new ones manually. Instead, accessing them over the Craft::$app property is preferred, as you indicated. This should work:
$session = Craft::$app->getSession();
$session->set("a", "b");

How are you checking if the session value got set? It's likely you're just looking in the wrong place, the default session component is file-based now if I recall correctly. You can check if a session variable exists and/or what value it holds like this:
Craft::dd($session->has('a'));
Craft::dd($session->get('a'));

> **Comments:**
> **username_0**: That's exactly what I needed !  Thank you very much, it works !  

---

