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 HTML5 tag is indicated to be used as container for menu with navigation links in Web site?
<section> <nav> <article>
<nav><ul>
 <li><a href="http://coursesweb.net/css/" title="CSS Course">CSS Course</a></li>
 <li><a href="http://www.marplo.net/jocuri/" title="Flash Games">Flash Games</a></li>
</ul></nav>
Which CSS property shifts an item horizontally to the left or right of where it was?
text-align clear float
.some_class {
  width: 30%;
  float: left;
}
Click on the Math object method which returns x, rounded downwards to the nearest integer.
Math.ceil(x) Math.abs(x) Math.floor(x)
var num = 12.34567;
num = Math.floor(num);
alert(num);       // 12
Indicate the PHP function which returns the number of characters in string.
mb_strlen() count() stristr()
$str = "string with utf-8 chars åèö";
$nrchr = mb_strlen($str);
echo $nrchr;        // 30
PHP Sessions

Last accessed pages

  1. jQuery background position (5238)
  2. elmPosiz - Get position, size and visibility in viewport of HTML element (1572)
  3. Select in MySQL, Output results in HTML Table (19320)
  4. PHP XML DOM (1952)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (137508)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (197)
  2. Read Excel file data in PHP - PhpExcelReader (72)
  3. The Four Agreements (64)
  4. PHP Unzipper - Extract Zip, Rar Archives (63)
  5. Get and Modify content of an Iframe (49)
Chat
Chat or leave a message for the other users
Full screenInchide