PHP

Activating Sessions

session_start()

Using session management always requires resources and, therefore, costs performance. Therefore, sessions have to be activated. Because cookies might be part of the package, this has to be done before any HTML content is sent to the client. This can be accomplished in two ways:

  • Activate sessions globally with the php.ini directive session.auto_start = 1.

  • Activate sessions on a per-script basis with the function session_start().

From a performance point-of-view, the latter option is the best one.

session_start function syntax

bool session_start ( void )

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie and returns TRUE if a session was successfully started, otherwise FALSE.

Activating Sessions Example

<?php
  session_start();
  echo 'Sessions activated.';
?>

Session Variables Example

//page1.php
session_start();
$_SESSION['name'] = 'test user';

Now print it on second page

//page2.php
session_start();
echo $_SESSION['name']; //will print: test user

by BrainBellupdated
Advertisement: