Php-mysql Course

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'] = '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: https://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: https://coursesweb.net
The new $_SESSION["site"] value is: 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 is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
PHP Sessions

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141749)
  2. Node.js Move and Copy file (28420)
  3. MouseEvent - Events for Mouse (2909)
  4. PHPMailer (2311)
  5. Uploading images to server with Ajax (6095)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)