State Management in PHP
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.
PHP Cookies
Cookie is a small piece of information stored as a file in the user's
browser by the web server. Once created, cookie is sent to the web
server as header information with every HTTP request.
You can use cookie to save any data but it should not
exceed 1K(1024 bytes) in size.
Before we move on to how to create, update and delete a cookies,
let's learn a few realworld use of cookies.
Realworld Use of Cookies
1. To store user information like when he/she visited, what pages
were visited on the website etc, so that next time the user
visits your website you can provide a better user experience.
2. To store basic website specific information to know this is not
the first visit of user.
3. You can use cookies to store number of visits or view counter.
I hope this gives you an idea about how you can utilize cookies in
your web application.
Types of Cookies
There are two types of cookies, they are:
• Session Cookie: This type of cookies are temporary and are expire as soon as the session
ends or the browser is closed.
• Persistent Cookie: To make a cookie persistent we must provide it with an expiration
time. Then the cookie will only expire after the given expiration time, until then it will be a
valid cookie.
Creating a Cookie in PHP
In PHP we can create/set a cookie using the setcookie() function.
Below we have the syntax for the function,
setcookie(name, value, expire, path, domain,
secure)
Copy
The first argument which defines the name of the cookie is
mandatory, rest all are optional arguments. Let's understand what
are the available arguments that we can supply to
the setcookie() function to set a cookie.
Argument What is it for?
Used to specify the name of the cookie. It is a mandatory
name
argument. Name of the cookie must be a string.
Used to store any value in the cookie. It is generally saved as a
value pair with name. For example, name is userid and value is 7007,
the userid for any user.
Used to set the expiration time for a cookie. if you do not
expire provide any value, the cookie will be treated as a session cookie
and will expire when the browser is closed.
Used to set a web URL in the cookie. If set, the cookie will be
path accessible only from that URL. To make a cookie accessible
through a domain, set '/' as cookie path.
The domain of your web application. It can be used to limit
access of cookie for sub-domains. For example, if you set the
domain
domain value as wwww.studytonight.com, then the cookie
will be inaccessible from blog.studytonight.com
If you set this to 1, then the cookie will be available and sent
secure
only over HTTPS connection.
So if we want to create a cookie to store the name of the user who
visited your website, and set an expiration time of a week, then we
can do it like this,
<?php
setcookie("username", "iamabhishek", time()+60*60*24*7);
?>
To access a stored cookie we use the $_COOKIE global variable, and
can use the isset() methos to check whether the cookie is set or not.
Let's have a complete example where we will set a cookie and then
retrieve it to show its value in the HTML page.
<?php
// set the cookie
setcookie("username", "iamabhishek", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
echo "cookie not set!";
?>
</body>
</html>
So by providing the name of the cookie inside the square brakets
with the global variable $_COOKIE[] we can access the cookie.
NOTE: setcookie() function should be placed before the starting
HTML tag(<html>).
Updating Cookie in PHP
To update/modify a cookie, simply set it again. For example, if we
want to update the username stored in the cookie created above,
we can do it using setcookie() method again,
<?php
// updating the cookie
setcookie("username", "iamNOTabhishek", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
echo "Cookie set with value: ".$_COOKIE["username"];
else
echo "cookie not set!";
?>
</body>
</html>
We just update the value of username cookie
from iamabhishek to iamNOTabhishek.
Delete a Cookie in PHP
To delete/remove a cookie, we need to expire the cookie, which can
be done by updating the cookie using the setcookie() function with
expiration date in past.
<?php
// updating the cookie
setcookie("username", "iamNOTabhishek", time() - 3600);
?>
<html>
<body>
<?php
echo "cookie username is deleted!";
?>
</body>
</html>
And with this, we now know how to create a cookie, how to update
it and how to delete it when we no longer need it. Next up,
Sessions!
PHP Sessions for State Management
To store information accessible accross web pages, we use sessions. Session is not
stored on the user browser like Cookies, hence it is a more secure option.
As we know HTTP is a stateless protocol, if a user visits a webpage and perform some
action, there is no way to remember what he did when the user navigates to the next
webpage.
Let's take a practical example, when you log into your facebook account, by
providing your email address and password, until and unless you logout, the web
application remembers who you are and display what your friends are posting and
liking on your News Feed, you can update your profile, send someone message, join
a group etc, this is accomplished by Session.
When a user logs into their account on any web application, a session is created for
them, and in the session their username or userid or some other unique identifier is
stored, which is then used on the consecutive webpages to show information specific
to that user. On logout, the session is destroyed.
Session is not limited by any size limit, you can store any information in the session,
irrespective of its size.
Before we move on to how to start, update and end a session in PHP, let's learn a few
realworld use of session.
Realworld Use of Session
1. Web applications which require a user to login, use session to store user information,
so that on every webpage related information can be displayed to the user.
2. In eCommerce websotes, shopping cart is geberally saved as part of session.
I hope this gives you an idea about how you can utilize session in your web
application.
Start a Session in PHP
In PHP we can start a session by using the session_start() function. And data is stored
in the session using session variable, which can be assigned different values using
global variable $_SESSION
In simpler words, using the function session_start() we initialize the session, in which
we can store information using the session variable $_SESSION.
Let's take an example, below we have a webpage with Php file
named first_page.php
<?php
// start the session
session_start();
// set the session variable
$_SESSION["username"] = "iamabhishek";
$_SESSION["userid"] = "1";
?>
<html>
<body>
<?php
echo "Session variable is set.";
?>
<a href="second_page.php">Go to Second Page</a>
</body>
</html>
Copy
NOTE: The function session_start() should be the first statement of the page, before
any HTML tag.
Getting PHP Session Variable Values
In the code above, we have started a session and set two session variables. Above
webpage will also have a link to navigate to Second page second_page.php.
Below is the code for second_page.php, in which we fetch values from the session
variable which are set in the first_page.php.
<?php
// start the session
session_start();
// get the session variable values
$username = $_SESSION["username"];
$userid = $_SESSION["userid"];
?>
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>
</body>
</html>
Copy
Username is: iamabhishek
User id is: 1
You must be thinking, why we used session_start() here although we did not set any
new values in the session variable.
session_start() function is used to initialize a new session and to fetch the ongoing
session(if already started), and then, using the $_SESSION global variable, we can either
set new values into the session or get the saved values.
If there are too many values stored in the session, and you don't know which one do
you want to get, you can use the below code to print all the current session variable
data.
<?php
// start the session
session_start();
?>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Copy
Array (
[username] => iamabhishek,
[userid] => 1
Update Session Variable in PHP
To update any value stored in the session variable, start the session by
calling session_start() function and then simply overwrite the vakue to update session
variable.
<?php
// start the session
session_start();
// update the session variable values
$_SESSION["userid"] = "1111";
?>
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>
</body>
</html>
Copy
Username is: iamabhishek
User id is: 1111
We just updated the value of userid in the session variable from 1 to 1111.
Destroy a Session in PHP
To clean the session variable or to remove all the stored values from the session
variable we can use the function session_unset() and to detroy the session, we
use session_destroy() function.
<?php
// start the session
session_start();
?>
<html>
<body>
<?php
// clean the session variable
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
We use these functions on pages like logout or checkout in case of an eCommerce
website to clean the session variable off the user specific data and to eventually
destroy the current session.
Hidden Form Fields: Hidden form fields can be used to maintain
session. With the help of them we can pass the data from one page to another.
Define a hidden field:
<input type="hidden" id="custId" name="custId" value="3487">
Definition and Usage
The <input type="hidden"> defines a hidden input 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.
Once the hidden form field is passed from one page to another you
can access that with the help of $_GET,$_POST or $_REQUEST and
maintain the session.
Query String: Query string is nothing but data passes as a part
of the url. It is in the form of name value pair and can be accessed with the help of
$_GET,$_POST or $_REQUEST variables. You can append query string in the url with
the help of & symbol.
Ex. http://www.xyz.com/index.php&custid=12;