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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1740100554, '3.147.28.73', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/web/php/snippets/session/index(84): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78