UNIT – III: Chapter 5 - State management
5.1 Using query string(URL rewriting)
5.2 Using Hidden field
5.3 Using cookies
5.4 Using session
Introduction to State Management:
HTTP is a stateless protocol which means every user request is processed independently and it has nothing to do
with the requests processed before it. Hence there is no way to store or send any user specific details using HTTP
protocol.
But in modern applications, user accounts are created and user specific information is shown to different users, for
which we need to have knowledge about who the user (or what he/she wants to see etc.) is on every webpage.
PHP provides for two different techniques for state management of your web application, they are:
1. Server Side State Management
2. Client Side Server Management
Server Side State Management
In server side state management, we store user specific information required to identify the user on the server and
this information is available on every webpage.
In PHP we have Sessions for server side state management. PHP session variable is used to store user session
information like username, userid etc. and the same can be retrieved by accessing the session variable on any
webpage of the web application until the session variable is destroyed.
Client Side State Management
In client side state management, the user specific information is stored at the client side i.e. in the bowser. Again,
this information is available on all the webpages of the web application.
In PHP we have Cookies for client side state management. Cookies are saved in the browser with some data and
expiry date (till when the cookie is valid).
One drawback of using cookie for state management is the user can easily access the cookie stored in their browser
and can even delete it.
5.1 Using query string (URL rewriting): [306]
Most of the Web applications you use today have a need to store data between browser requests. For example, a
shopping cart needs to remember which items you have added to your cart. A forum application needs to remember
your identity whenever you post a message in the forum.
In other words, there is a need to preserve the current state of a user’s interaction with an application from one
request to the next. Query strings are a quick, convenient way to pass small amounts of data between browser
requests. Common uses of query strings include remembering a user’s entered keywords when using a search
function, identifying which topic within a forum to display to the user, and specifying which post within a blog to
display.
Query string data is very easy for the user to alter, because it’s visible and editable within the browser’s
address bar. Therefore, query strings should be used only in situations where sending incorrect data won’t
compromise security. For example, don’t use query strings for storing things such as user IDs. When the form data
is sent to the server, it is appended to the end of the URL as follows:
http://localhost/myscript.php?firstName=Fred & lastName=Bishop & ...
The browser adds a query (?) character to the end of the URL, then follows it with each of the form fields as
“name=value” pairs, with each pair separated by an ampersand (&). The query string is the part of the URL after
the? character.
Query strings not limited to form data. Because a query string is simply a string of characters stored in a URL, you
can manually create a URL containing a query string in your PHP script, then include the URL as a link within the
displayed page or in an email, for example. PHP even provides some built - in functions to make the process easier.
Here’s a simple example that creates two variables, $firstName and $age, then creates a link in the displayed page
that contains a query string to store the variable values:
<html>
<body>
<?php
$firstName = "John";
$age = "34";
$queryString = "firstName=$firstName&age=$age";
echo '<p><a href="moreinfo.php?' . $queryString . '" > Find out more info on this person </a> </p >';
?>
</body>
</html>
This code generates the following markup:
< p > < a href= “moreinfo.php?firstName=John&age=34”> Find out more info on this person < /a > < /p >
If the user then clicks this link, moreinfo.php is run, and the query string data ( firstName=John & age=34 ) is
passed to the moreinfo.php script. Data has been transmitted from one script execution to the next.
The ampersand ( & ) character needs to be encoded as & amp; inside XHTML markup.
One thing to watch out for is the type of characters that you insert into the field names and values in your query
string.
The specifications for a query string allows only the following characters to be used within field names and values:
letters, numbers, and the symbols - , , . (period), ! , ~ , * , ‘ (single quote), ( , and ) .
So what do you do if you need to transmit other characters, such as spaces, curly braces, or? characters? The answer
is that you should use URL encoding. This is a scheme that encodes any reserved characters as hexadecimal
numbers preceded by a percent ( % ) symbol, with the exception of space characters, which are encoded as plus ( + )
signs.
PHP gives you a function called urlencode() that can encode any string using URL encoding. Simply pass it a string
to encode, and it returns the encoded string. So you can use urlencode() to encode any data that may contain
reserved characters.
Here’s an example:
<html>
<body>
<?php
$firstName = "John";
$homePage = "http://www.shahucollege.com/";
$favoriteSport = "Ice Hockey";
$queryString = "firstName=" . urlencode($firstName) . " & amp;homePage=" .urlencode( $homePage ) . "
&favoriteSport=" . urlencode( $favoriteSport );
echo '<p><a href="moreinfo.php?'.$queryString .'"> Click to more information </a></p>';
?>
</body>
</html>
This code snippet outputs the following markup:
<p><a href=”moreinfo.php?firstName=John%20&%20amp;homePage=http%3A%2F%2Fwww.shahucollege.com%2F%20
&favoriteSport=Ice+Hockey” ” > Find out more info on this person < /a > < /p >
Accessing Data in Query Strings
As you’ve probably guessed by now, to access the field names and values in a query string you simply read
them from the $_GET superglobal array, just as if you were handling a form sent with the get method:
$firstName = $_GET[“firstName”];
$homePage = $_GET[“homePage”];
So it’s easy to write a simple version of the moreinfo.php script referenced in the previous example:
< ?php
$firstName = $_GET[“firstName”];
$homePage = $_GET[“homePage”];
$favoriteSport = $_GET[“favoriteSport”];
echo “ < dl > ”;
echo “ < dt > First name: < /dt > < dd > $firstName < /dd > ”;
echo “ < dt > Home page: < /dt > < dd > $homePage < /dd > ”;
echo “ < dt > Favorite sport: < /dt > < dd > $favoriteSport < /dd > ”;
echo “ < /dl > ”;
? >
5.2 Using Hidden field:
A hidden field let web developers include data that cannot be seen or modified by users when a form is submitted.
A hidden field often stores what database record that needs to be updated when the form is submitted.
While the value is not displayed to the user in the page's content, it is visible (and can be edited) using any browser's
developer tools or "View Source" functionality. Do not use hidden inputs as a form of security!
The numbers browser that fully supports the hidden element are chrome, internet browser, safari, firefox, opera etc.
The <input type="hidden"> defines a hidden input field.
<html>
<body>
<h1>Using hidden input field:</h1>
<form action="/customerid.php">
First name: <input type="text" name="fname"><br>
<input type="hidden" id="custId" name="custId" value="501">
<input type="submit" value="Submit">
</form>
<p>Notice that the hidden input field is not shown to the user, but the data is sent when the form is submitted.</p>
</body>
</html>
5.3 Using cookies:
A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer. They are
typically used to keeping track of information such as a username that the site can retrieve to personalize the page
when the user visits the website next time. A cookie can only be read from the domain that it has been issued from.
Simply a cookie is a message given to a Web browser by a Web server. The browser stores the message in a small
text file that the server embeds on the user's computer. Each time the same computer requests a page with a browser,
the cookie is sent back to the server too.
There are a wide variety of things you can do with cookies. They are used to store information about user, visited
pages, poll results and etc. The main purpose of cookies is to identify users and possibly prepare customized Web
pages for them.
Normally cookies are used only to store small amounts of data. Websites can read the values from the cookies and
use the information as desired. In addition to the information it stores, each cookie has a set of attributes that helps
ensure the browser sends the correct cookie when a request to a server is made.
Even though cookies are not harmful some people do not permit cookies due to concerns about their privacy. In this
case you have to use Sessions.
Creating a Cookie:
PHP cookies can be set using the setcookie() function. The syntax is as follows:
setcookie(name[, value[, expire[, path[, domain[, security]]]]])
[name] The cookie name. The name of each cookie sent is stored in the superglobal array $_COOKIE.
[value] The cookie value. It is associated with the cookie name. [expire] The time after which the cookie
should expire in seconds.
[path] Specifies the exact path on the domain that can use the cookies.
[domain] The domain that the cookie is available. If not domain is specified, the default value is the value
of the domain in which cookie was created.
[security] Specifies whether the cookie will be sent via HTTPS. A value of 1 specifies that the cookie is
sent over a secure connection but it doesn't mean that the cookie is secure. It's just a text file like every
other cookie. A value of 0 denotes a standard HTTP transmission.
In the example below, we will create a cookie named "myCookie" and assign the value "FirstCookie" to it. We also
specify that the cookie should expire after one hour and that the cookie is available for all pages within a Tutorials
directory.
<?php
setcookie("myCookie", " FirstCookie ", time()+3600, "/tutorials");
?>
There's one important item to mention about using cookies. Because of the way cookies work within HTTP, it's
important that you send all cookies before any output from your script. This requires that you place calls to this
function before any output, including tags as well as any whitespace. If you don't, PHP will give you a warning and
your cookies will not be sent.
Retrieving a Cookie Data:
Now the cookie is set and we need to retrieve the information. As mentioned above the name of each cookie sent by
your server accessed with the superglobal array $_COOKIE. In the example below we retrieve the value of the
cookie and print out its value on the screen.
<?php
echo "The cookie value is ".$_COOKIE['myCookie'];
?>
This would show up on the page as: "myCookie value is FirstCookie".
Deleting a Cookie:
By default, the cookies are set to be deleted when the browser is closed. We can override that default by setting a
time for the cookie's expiration but there may be occasions when you need to delete a cookie before the user closes
his browser, and before its expiration time arrives. To do so, you should assure that the expiration date is in the past.
The example below demonstrates how to do it (setting expiration time 1 minute ago):
<?php
setcookie("myCookie", "", time()-60);
?>
Example:
htmlform.html
<html>
<body>
<form action="dispinfo.php" method="post">
<label> Enter Student Name:</label>
<input type="text" name="sname"></br>
<label> Enter Roll No:</label>
<input type="text" name="srno"></br>
<label> Enter Class:</label>
<input type="text" name="sclass"></br>
<label> Enter Semester:</label>
<input type="text" name="sem"></br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Displaying Information and Setting Cookie:
dispinfo.php
<?php
$sname=$_POST["sname"];
$srno=$_POST["srno"];
$sclass=$_POST["sclass"];
$sem=$_POST["sem"];
echo "Student Name:".$sname."</br>";
echo "Student Roll No:".$srno."</br>";
echo "Student Class:".$sclass."</br>";
echo "Student Semester:".$sem."</br>";
setcookie("studcookie",$_POST["sname"]." ".$_POST["srno"]." ".$_POST["sclass"]."
".$_POST["sem"],time()+3600);
echo "cookies set Successfully! ";
?>
Accessing Cookie Data:
<html><body>
<?php
#accessing cookie values and removing cookie
echo "The cookie value is : ".$_COOKIE['studcookie']."</br>";
echo "Cookie accessed successfully</br>";
?>
<a href="/srss/clear.php">Click Here to delete cookie</a>
</body></html>
Deleting or removing cookie:
<?php
setcookie("studcookie","",time()+3600);
echo "Cookie Deleted Successfully!";
?>
5.4 Using session:[340]
Although you can store data using cookies but it has some security issues. Since cookies are stored on user's
computer it is possible for an attacker to easily modify a cookie content to insert potentially harmful data in your
application that might break your application.
Also every time the browser requests a URL to the server, all the cookie data for a website is automatically sent to
the server within the request. It means if you have stored 5 cookies on user's system, each having 4KB in size, the
browser needs to upload 20KB of data each time the user views a page, which can affect your site's performance.
You can solve both of these issues by using the PHP session. A PHP session stores data on the server rather than
user's computer. In a session based environment, every user is identified through a unique number called session
identifier or SID. This unique session ID is used to link each user with their own information on the server like
emails, posts, etc.
Starting a PHP Session:
Before you can store any information in session variables, you must first start up the session. To begin a new
session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID
for the user.
The PHP code in the example below simply starts a new session.
<?php
session_start();
?>
The session_start() function first checks to see if a session already exists by looking for the presence of a session ID.
If it finds one, i.e. if the session is already started, it sets up the session variables and if doesn't, it starts a new
session by creating a new session ID.
The session_start() function must call at the beginning of the page i.e. before any output generated by your script in
the browser.
Storing and Accessing Session Data:
You can store all your session data as key-value pairs in the $_SESSION[] superglobal array. The stored data can be
accessed during lifetime of a session. Consider the following script, which creates a new session and registers two
session variables.
<?php
session_start();
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";
?>
To access the session data we set on our previous example from any other page on the same web domain — simply
recreate the session by calling session_start() and then pass the corresponding key to the $_SESSION associative
array.
<?php
session_start();
// Accessing session data
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];
?>
Destroying or Removing a Session:
If you want to remove certain session data, simply unset the corresponding key of the $_SESSION associative array,
as shown in the following example:
<?php
session_start();
// Removing session data
if(isset($_SESSION["lastname"])){
unset($_SESSION["lastname"]);
}
?>
However, to destroy a session completely, simply call the session_destroy() function. This function does not need
any argument and a single call destroys all the session data.
<?php
session_start();
// Destroying session
session_destroy();
?>
Every PHP session has a timeout value. Timeout value is a duration, measured in seconds, which determines how
long a session should remain alive in the absence of any user activity.
Example:
<?php
session_start();
if(isset($_SESSION["count"])) {
$accesses = $_SESSION["count"] + 1;
} else {
$accesses = 1;
}
$_SESSION["count"] = $accesses;
// session_destroy();
?>
<html>
<head>
<title>Access counter</title>
</head>
<body>
<h1>Access counter</h1>
<p>You have accessed this page <?php echo $accesses; ?> times today.</p>
<p>[<a href="session.php">Reload</a>]</p>
</body>
</html>
==0==
No comments:
Post a Comment