Passing Variable in PHP Session

Introduction

A session is basically a temporary set of variables that exists only until the browser has shut down. Examples of session information include a session ID and whether or not an authorized person has logged in to the site. This information is temporarily stored in your PHP programs. Every session is assigned a unique session ID, that keeps all current information together. Your session ID can either be passed through the URL or through the use of a cookie. Although it is preferable for security reasons to pass the session ID through a cookie so that it is hidden from the human eye, if cookies are not enabled then the alternative is to use the URL. This setting is determined in your php.ini file, whethr you would like to force the user to pass variables through a cookie.

Then all you need to do to begin a session in PHP is call the function session_start(). You however need to first decide what information will be stored in your session. Anything that has been stored in a database can be retrieved and stored temporarily along with your session information. Usually, it is information such as user name and login information, but it can also be preferences that have been set at some point by the user. A session identifier will also be stored in the session array of variables.

Passing the Visitor's Username

Suppose you want to pass your visitor's username, and whether or not he or she has authentically logged in to the site between the first page and the second page.

Example

Save the followng file as "session.php":

<?php

session_start();

$_SESSION['username']= 'vinod';

$_SESSION['authuser']= 1;

?>

<html>

<head><title></title>

</head>

<body>

<?php

$my = urlencode('MCN solution');

echo "<a href=\"session2.php?name=$my\">";

echo 'click here to see my company nam';

echo '</a>'

?>

</body>

</html>

Next,

Save the followng file as "session2.php":

<?php

session_start();

if($_SESSION['authuser']!= 1)

{

echo 'sorry but don\'t have permission to view this page!';

exit();

}

?>

<html>

<head><title></title>

</head>

<body>

<?php

echo 'Welcome to MCN solution ';

echo $_SESSION['username'];

echo '!<br>';

echo 'My company is ';

echo $_GET['name'];

echo '!<br>';

$loca = 'Noida';

echo 'My company lacation is ';

echo $loca;

echo '</a>'

?>

</body>

</html>

Output

session1.jpg

session2.jpg

Here are a few important things to note about this procedure:

  • The session variable has the syntax $_session['varname']. If you don't then the variable will contain an empty value, you may receive a warning message.

  • You must use the function session_start() before you send the output to the browser and before you use any session variables.

     

 

Up Next
    Ebook Download
    View all
    Learn
    View all