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).
<?php session_start(); $_SESSION['username'] = "June"; ?> <html> <head> <TITLE>Just A Sample - ITX.WEB.ID</TITLE> </head> <body> <?php $mybook = "My Name is June"; echo "<a href='mybook.php?book=$mybook'>"; echo "Click here to see your book!"; echo "</a>"; ?> </body> </html>
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.
<?php session_start(); echo "<h2> Welcome to your Book, "; echo $_SESSION['username']; echo "! </h2> <br>"; echo "Your favorite book is "; echo $_REQUEST['book']; echo "<br>"; ?>
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.
Hal yang juga menarik:
Semua skrip dan teknik dalam artikel di itx.web.id boleh digunakan sebagaimana kehendakmu tanpa perlu mencantumkan sumber. Kamu tidak boleh mengkopi seluruh artikel, dalam Bahasa Indonesia ataupun diterjemahkan ke dalam bahasa lain.