Search notes:

PHP code snippets: managing sessions

start_session() checks if a cookie named PHPSESSID is present. If not, this cookie is created.
The php engine associates this cookie with an associative array, named $_SESSION which can be used to store values across sessions. These values are not sent between the webserver and the web browser.

Simple example

<?php

//
// https://stackoverflow.com/a/13742117/180275 : Move session_start() to the top
//
   session_start([
      'cookie_lifetime' => 10 // seconds
   ]);


?>
<!DOCTYPE html>
<html>
<head>
  <title>Session Test</title>
</head>
<body>

  <?php


  if(isset($_SESSION['counter'])) {
    $_SESSION['counter'] ++;
  }
  else {
    $_SESSION['counter'] = 1;
  }

  echo "counter: " . $_SESSION['counter'];

  ?>

  Link to itself: <a href='_SESSION.html'>_SESSION.html</a>

  <br>Also try reloading with F5.


</body>
</html>
Github repository about-php, path: /session/simple.html

See also

Other PHP snippets.

Index