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 in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
PHP Sessions

Last accessed pages

  1. CSS Content (425)
  2. Animated Tooltip with HTML and CSS (284)
  3. MySQLDumper - Backup MySQL Database (1782)
  4. querySelector and querySelectorAll (30136)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142540)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (543)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)