Sessions are another method of making data available from a page to another of a Web site.
When a visitor accesses a web site, the server assigns it an unique ID (called session id or SID). This is either stored in a cookie (with a name of PHPSESSID) on the user computer or is propagated in the URL (if the browser don't accept cookies).
Based on this SID, it is created an unique file with the session data on the server, in a folder location as set by the session.save_path in "php.ini" file.
When a session is initiate, the server stores session values in the superglobal $_SESSION variable, which can be accessed by other pages as long as the session remains active. Normally, a session remains active until the browser is closed.

Setting session variables

Each page that will use sessions must begin by calling the session_start() function. This command should be called only once in each page, before the PHP script generates any output or uses $_SESSION variables, so the best position is at the beginning of the php file.
The correct way to set and store a session variable is to add it to the $_SESSION superglobal array, in the same way you would assign an ordinary variable.
  - Example:
<?php
session_start();        // start the session

// store session data
$_SESSION['site'] = 'coursesweb.net';
?>

<html>
...
$_SESSION['site'] can now be used in any page that calls session_start().

Accessing session variables

Once a session has been started and $_SESSION variable has been registered, you can access and use it in the same way you access an array element, in any page that calls the session_start() function.
To change the value of a $_SESSION variable, just assign another value to it.

Let's see an example. We create two php files, "a.php" and "b.php". In the first file we create a session variable and an HTML link to open the second file. In this file (b.php) we access the session variable created in "a.php", output its value and modify it.
First, create a php file (named "a.php") in the server directory, and add the fallowing code:
<?php
// a.php file

session_start();        // start the session

// store session data
$_SESSION['site'] = 'coursesweb.net';
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>a.php</title>
</head>
<body>
This is the "a.php" page<br />

<?php
echo 'Here is defined the session $_SESSION["site"], its value is: '. $_SESSION['site'];
?>

<br /><br />
Link <a href="b.php">to b.php</a>
</body>
</html>
In the same folder, create the "b.php" file with the fallowing code:
<?php
// b.php file

session_start();
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>b.php</title>
</head>
<body>
This is b.php page <br />

<?php
echo 'The value of the $_SESSION["site"] is: '. $_SESSION['site'];

// changes the value of $_SESSION['site'] and output it
$_SESSION['site'] = 'www.marplo.net';
echo '<br /> The new $_SESSION["site"] value is: '.$_SESSION['site'];
?>

</body>
</html>
When you open the "a.php" page, will display the fallowing result:
This is the "a.php" page
Here is defined the session $_SESSION["site"], its value is: http://coursesweb.net

Link to b.php
If you click on the "to b.php", will open that page, displaying the fallowing result:
This is b.php page
The value of the $_SESSION["site"] is: http://coursesweb.net
The new $_SESSION["site"] value is: www.marplo.net

• When your PHP script includes other php files that use sessions, it may happen to have multiple session_start(); this will generate a notice error "Notice: A session had already been started". To avoid this, you can check if the "session_start()" was already started, before calling it, by using the session_id(). This function returns the session id for the current session or the empty string ("") if there is no current session.
  - Example:
<?php
if(session_id()=="") {
  session_start();
}
?>

Deleting / Destroying session variables

To delete an individual session variable, you can use the unset() function (which works with any variable in PHP):
unset($_SESSION['name']);
To delete every session variable, reset the entire $_SESSION array:
$_SESSION = array();
To remove all of the data associated with the current session from the server, use session_destroy():
session_destroy();
  - Example:
<?php
session_start();

unset($_SESSION['name']);           // delete the $_SESSION['name']

session_destroy();                  // remove all current session data
?>

Handling Session

If you want to get the ID of the current session, you can use the session_id() function.
  - Example:
<?php
session_start();

echo '<br /> The ID of the current session is: '. session_id();
?>
This code will output something similar to:
The ID of the current session is: viau40ap7af7ssa5ka3bofjn82

The session_id() function accepts a parameter. With this parameter we can set a SID for the current session. In this case you need to call session_id() before the session_start() function.
  - Example:
<?php
session_id('123abc');
session_start();

echo '<br /> The ID of the current session is: '. session_id();
?>
This code will output:
The ID of the current session is: 123abc

If you add data security in sessions (as login password), is better to encrypt them before adding in session. You can use the fallowing PHP function.

  - Example:
<?php
session_start();

$data = 'php-mysql';

// encrypt $data and store it in a session
$hash_data = sha1($data);
$_SESSION['pass'] = $hash_data;

$pass = 'php-mysql';            // this could be a password sent by a user

// check if we have a valid $pass
if ($_SESSION['pass']==sha1($pass)) {
  echo 'Correct pass, its encrypted value is: '. $_SESSION['pass'];
}
else {
  echo 'Incorrect pass';
}
?>
This example use the sha1() function to add some encrypted data ($hash_data) in a session, than check if the value of another variable ($pass - which could be a password sent by a user) is the same with the one added in session.
The code above will output:
Correct pass, its encrypted value is: 27eaed9db59a74396ae6010a3a38cdc87f982c4f

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag create a highlighted bolded text?
<q> <strong> <em>
<p>Address: <strong>http://CoursesWeb.net/</strong> - Tutorials.</p>
Which of these CSS codes displays the text bolded?
text-size: 18px; font-style: italic; font-weight: 800;
#id {
  font-weight: 800;
}
What JavaScript function can be used to call another function multiple times, to a specified time interval?
setInterval() setTimeout() push()
function someFunction() { alert("CoursesWeb.net"); }
setInterval("someFunction()", 2000);
Click on the correctly defined variable in PHP.
var vname = 8; $vname = 8; $vname == 8;
$vname = 8;
echo $vname;
PHP Sessions

Last accessed pages

  1. Zuma Games (8602)
  2. PuzzleImg - Script to Create Image Puzzle Game (987)
  3. Mystic India Pop (2581)
  4. Escape Games (3243)
  5. Match Around The World (170)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (47785)
  2. Read Excel file data in PHP - PhpExcelReader (35922)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (35547)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (32047)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (29322)