Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP: start session only when necessary
    text
    copied!<p>I have my own Session class, which handles session actions. I wanted to make a mechanism, that the session starts only when it is needed - if no session variables are set, system does not create it.</p> <p>So that's the code (simplified):</p> <pre><code>class Session { public function __construct() { } protected function startSession($onlyIfExists = false) { if (session_id() == '') { if ($onlyIfExists &amp;&amp; !isset($_COOKIE[session_name()])) return; @session_start(); } } public function setVar($id, $value) { $this-&gt;startSession(); $_SESSION[$id] = $value; } public function getVar($id) { $this-&gt;startSession(true); //starts session only if the session-id cookie exists (if the session was already started for this user) if (isset($_SESSION) &amp;&amp; array_key_exists($id, $_SESSION)) return $_SESSION[$id]; else return NULL; } } </code></pre> <p>And then I just always have to use this class object to get/set session variables, e.g.:</p> <pre><code>$session = new Session(); $session-&gt;getVar('test'); //does not start session at the first time $session-&gt;setVar('test', 1); //starts session; after refreshing the page the above line does start session (cookie exists) and the value=1 is returned </code></pre> <p>Is it a good solution? Do you see any potential drawbacks, vulnerabilities? Or maybe it is a standard to start session each time?</p> <p>Because in my application any session variables are created only after authorization, so I don't need session for 99.999% of users.</p> <p>Thank you in advance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload