Web Programming with PHP

27 Keeping Users' Information Through Web Pages

Session support in PHP consists of a way to preserve certain data across subsequent accesses. Session is a essential concept for modern web appliactions.

Session support consists of a way to preserve certain data across subsequent accesses. A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. The session support allows you to register arbitrary numbers of variables to be preserved across requests.

When a visitor accesses your site, PHP will check whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Page 1:


<?php
  // session_start() must be called before outputing anything to the browser
  session_start();
  $_SESSION["counter"]++;
?>
<html>
...
</html>

Page 2:


<?php
  // session_start() must be called before outputing anything to the browser
  session_start(); 
?>
<html>
<body>
<p>
<?php
  echo "counter: " . $_SESSION["counter"];
?>
</p>
</body>
</html>