Case Studies : Passing variables between pages in PHP with PHP Session.
Needs : Webserver package, already installed .
For the case this time, assume that you will make the application logged on to the page – next page after the user is logged in, you want to continue to greet the user. Of course, you must store the variable name of the user right? Basically, there are four ways to do this, namely:
1. Pass the variable in the URL.
2. Through Session.
3. Via Cookie and,
4. With HTML Form.
This tutorial will discuss about the point to one and two of the four ways above, ie pass the variable through a combination of URL and Session.
1. Type the following script (named script1.php).
$_SESSION[‘username’] = "June";
<TITLE>Just A Sample – ITX.WEB.ID</TITLE>
$mybook = "My Name is June";
echo "<a href=’mybook.php?book=$mybook’>";
echo "Click here to see your book!";
Note that in the script above, we assign a username variable manually (assumption: that the user has been logged and the username is saved in the session). So, how to store value in session is with the following syntax:
$_SESSION['username'] = "June";
Meanwhile, variable book will be passed through the URL. Its syntax is as follows:
mybook.php? book = $mybook , with variable mybook has been assigned previously.
Once executed, the script above will output the following :
Click here to see your book!
2. Type the following script (save it as mybook.php). The following script is the script from the script output link 1 above. This script will read a variable that has dilewat through URL and Session.
echo "<h2> Welcome to your Book, ";
echo "! </h2> <br>";
echo "Your favorite book is ";
Note the section above. From script1.php, we know that we have missed 2 variables, namely variable book and variable username , with each – each value is My Name is June for variable book , and June for the variable username.
Then I read the second variable is:
1. Reading the variable book (which is passed via the URL):
$_REQUEST ['book'] .
2. Reading the variable username (which is passed via Session):
$_SESSION ['username'] .
Click the link generated script1.php, then you will be redirected to the script page 2 (mybook.php), with a view like the picture below.
Haaaapy Coding 😀