CHAPTER 5 PHP Cookies, PHP Session, PHP Date and Time, PHP JSON
CHAPTER 5 PHP Cookies, PHP Session, PHP Date and Time, PHP JSON
CHAPTER 5 - PHP Cookies, PHP Session, PHP Date and Time, PHP JSON Parsing
PHP Cookies
In this section you will learn how to store a small amount of information within the user's browser itself using the
PHP cookies.
What is a Cookie?
A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user's computer. They
are typically used to keeping track of information such as username that the site can retrieve to personalize the
page when user visit the website next time.
Tip: Each time the browser requests a page to the server, all the data in the cookie is automatically sent to the
server within the request.
The setcookie() function is used to set a cookie in PHP. Make sure you call the setcookie() function before
any output generated by your script otherwise cookie will not set. The basic syntax of this function can be given
with:
Parameter Description
name The name of the cookie.
value The value of the cookie. Do not store sensitive information since this value is stored on the user's
computer.
expires The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The
default value is 0.
path Specify the path on the server for which the cookie will be available. If set to /, the cookie will be
available within the entire domain.
domain Specify the domain for which the cookie is available to e.g www.example.com.
secure This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection
exists.
Tip: If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the session i.e.
when the browser closes.
Here's an example that uses setcookie() function to create a cookie named username and assign the value value
John Carter to it. It also specify that the cookie will expire after 30 days ( 30 days * 24 hours * 60 min * 60
sec).
<?php
// Setting a cookie
setcookie("username", "John Carter", time()+30*24*60*60);
?>
1 of page 12
Note: All the arguments except the name are optional. You may also replace an argument with an empty string
("") in order to skip that argument, however to skip the expire argument use a zero (0) instead, since it is an
integer.
Warning: Don't store sensitive data in cookies since it could potentially be manipulated by the malicious user. To
store the sensitive data securely use sessions instead.
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It typically an associative array that
contains a list of all the cookies values sent by the browser in the current request, keyed by cookie name. The
individual cookie value can be accessed using standard array notation, for example to display the username cookie
set in the previous example, you could use the following code.
<?php
// Accessing an individual cookie value
echo $_COOKIE["username"];
?>
The PHP code in the above example produce the following output.
John Carter
It's a good practice to check whether a cookie is set or not before accessing its value. To do this you can use the
PHP isset() function, like this:
<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
?>
You can use the print_r() function like print_r($_COOKIE); to see the structure of this $_COOKIE associative
array, like you with other arrays.
Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie name and any value (such as
an empty string) however this time you need the set the expiration date in the past, as shown in the example
below:
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
Tip: You should pass exactly the same path, domain, and other arguments that you have used when you first
created the cookie in order to ensure that the correct cookie is deleted.
2 of page 12
PHP Sessions
In this section you will learn how to store certain data on the server on a temporary basis using PHP session.
What is a Session?
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.
Tip: The session IDs are randomly generated by the PHP engine which is almost impossible to guess.
Furthermore, because the session data is stored on the server, it doesn't have to be sent with every browser
request.
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
// Starting session
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.
Note: You must call the session_start() function at the beginning of the page i.e. before any output generated
by your script in the browser, much like you do while setting the cookies with setcookie() function.
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.
3 of page 12
<?php
// Starting session
session_start();
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
// Starting session
session_start();
The PHP code in the example above produce the following output.
Note: To access the session data in the same page there is no need to recreate the session since it has been already
started on the top of the page.
Destroying 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
// Starting session
session_start();
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
// Starting session
session_start();
// Destroying session
session_destroy();
?>
4 of page 12
Note: Before destroying a session with the session_destroy() function, you need to first recreate the session
environment if it is not already there using the session_start() function, so that there is something to destroy.
Every PHP session has a timeout value — a duration, measured in seconds — which determines how long a
session should remain alive in the absence of any user activity. You can adjust this timeout duration by changing
the value of session.gc_maxlifetime variable in the PHP configuration file (php.ini).
In this section you will learn how to extract or format the date and time in PHP.
The PHP date() function convert a timestamp to a more readable date and time.
The computer stores dates and times in a format called UNIX Timestamp, which measures time as a number of
seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January 1, 1970 i.e. January
1, 1970 00:00:00 GMT ).
Since this is an impractical format for humans to read, PHP converts a timestamp to a format that is readable to
humans and dates from your notation into a timestamp the computer understands. The syntax of the PHP date()
function can be given with.
date(format, timestamp)
The format parameter in the date() function is required which specifies the format of returned date and time.
However the timestamp is an optional parameter, if not included then current date and time will be used. The
following statement displays today's date:
<?php
$today = date("d/m/Y");
echo $today;
?>
Note: The PHP date() function return the current date and time according to the built-in clock of the web server
on which the script has been executed.
The format parameter of the date() function is in fact a string that can contain multiple characters allowing you
to generate a date string containing various components of the date and time, like day of the week, AM or PM,
etc. Here are some the date-related formatting characters that are commonly used in format string:
d - Represent day of the month; two digits with leading zeros (01 or 31)
D - Represent day of the week in text as an abbreviation (Mon to Sun)
m - Represent month in numbers with leading zeros (01 or 12)
M - Represent month in text, abbreviated (Jan to Dec)
y - Represent year in two digits (08 or 14)
Y - Represent year in four digits (2008 or 2014)
5 of page 12
The parts of the date can be separated by inserting other characters, like hyphens ( -), dots (.), slashes (/), or
spaces to add additional visual formatting.
<?php
echo date("d/m/Y") . "<br>";
echo date("d-m-Y") . "<br>";
echo date("d.m.Y");
?>
Tip: You can use the PHP date() function to automatically update the copyright duration on your website, like:
Copyright © 2010-<?php echo date("Y")?>.
Similarly you can use the following characters to format the time string:
The PHP code in the following example displays the date in different formats:
<?php
echo date("h:i:s") . "<br>";
echo date("F d, Y h:i:s A") . "<br>";
echo date("h:i a");
?>
The time() function is used to get the current time as a Unix timestamp (the number of seconds since the
beginning of the Unix epoch: January 1 1970 00:00:00 GMT).
<?php
// Executed at March 05, 2014 07:19:18
$timestamp = time();
echo($timestamp);
?>
1394003958
We can convert this timestamp to a human readable date through passing it to the previously introduce date()
function.
<?php
$timestamp = 1394003958;
echo(date("F d, Y h:i:s", $timestamp));
?>
6 of page 12
March 05, 2014 07:19:18
The mktime() function is used to create the timestamp based on a specific date and time. If no date and time is
provided, the timestamp for the current date and time is returned.
The following example displays the timestamp corresponding to 3:20:12 pm on May 10, 2014:
<?php
// Create the timestamp for a particular date
echo mktime(15, 20, 12, 5, 10, 2014);
?>
1399735212
Note: You can leave out as many arguments as you like, and the value corresponding to the current time will be
used instead. If you omit all the arguments, the mktime() function will return the UNIX timestamp corresponding
to the current date and time, just like time().
The mktime() function can be used to find the weekday name corresponding to a particular date. To do this,
simply use the 'l' (lowercase 'L') character with your timestamp, as in the following example, which displays the
day that falls on April 1, 2014:
<?php
// Get the weekday name of a particular date
echo date('l', mktime(0, 0, 0, 1, 4, 2014));
?>
Saturday
The mktime() function can also be used to find a particular date in future after a specific time period. As in the
following example, which displays the date which falls on after 30 month from the current date?
<?php
// Executed at March 05, 2014
$futureDate = mktime(0, 0, 0, date("m")+30, date("d"), date("Y"));
echo date("d/m/Y", $futureDate);
?>
05/09/2016
7 of page 12
Complete PHP Date Reference
Please check out the PHP Date/Time Functions reference section for a complete list of all the useful date and time
functions available in PHP.
In this section you will learn how to encode and decode JSON data in PHP.
What is JSON?
JSON stands for JavaScript Object Notation. JSON is a standard lightweight data-interchange format which is
quick and easy to parse and generate.
JSON, like XML, is a text-based format that's easy to write and easy to understand for both humans and
computers, but unlike XML, JSON data structures occupy less bandwidth than their XML versions. JSON is
based on two basic structures:
Object: This is defined as a collection of key/value pairs (i.e. key:value). Each object begins with a left
curly bracket { and ends with a right curly bracket }. Multiple key/value pairs are separated by a comma
,.
Array: This is defined as an ordered list of values. An array begins with a left bracket [ and ends with a
right bracket ]. Values are separated by a comma ,.
In JSON, keys are always strings, while the value can be a string, number, true or false, null or even an
object or an array. Strings must be enclosed in double quotes " and can contain escape characters such as \n, \t
and \. A JSON object may look like this:
{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"genre": "Fantasy Fiction",
"bestseller": true
}
}
{
"fruits": [
"Apple",
"Banana",
"Strawberry",
"Mango"
]
}
Tip: A data-interchange format is a text format which is used to interchange or exchange data between different
platforms and operating systems. JSON is the most popular and lightweight data-interchange format for web
applications.
8 of page 12
Parsing JSON with PHP
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data.
These functions are json_encode() and json_decode(), respectively. Both functions only works with UTF-8
encoded string data.
In PHP the json_encode() function is used to encode a value to JSON format. The value being encoded can be
any PHP data type except a resource, like a database or file handle. The below example demonstrates how to
encode a PHP associative array into a JSON object:
<?php
// An associative array
$marks = array("Peter"=>65, "Harry"=>80, "John"=>78, "Clark"=>90);
echo json_encode($marks);
?>
{"Peter":65,"Harry":80,"John":78,"Clark":90}
Similarly, you can encode the PHP indexed array into a JSON array, like this:
<?php
// An indexed array
$colors = array("Red", "Green", "Blue", "Orange", "Yellow");
echo json_encode($colors);
?>
["Red","Green","Blue","Orange","Yellow"]
You can also force json_encode() function to return an PHP indexed array as JSON object by using the
JSON_FORCE_OBJECT option, as shown in the example below:
<?php
// An indexed array
$colors = array("Red", "Green", "Blue", "Orange");
{"0":"Red","1":"Green","2":"Blue","3":"Orange"}
As you can see in the above examples a non-associative array can be encoded as array or object. However, an
associative array always encoded as object.
9 of page 12
Decoding JSON Data in PHP
Decoding JSON data is as simple as encoding it. You can use the PHP json_decode() function to convert the
JSON encoded string into appropriate PHP data type. The following example demonstrates how to decode or
convert a JSON object to PHP object.
<?php
// Store JSON data in a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
var_dump(json_decode($json));
?>
The output of the above example will look something like this:
object(stdClass)#1 (4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) }
By default the json_decode() function returns an object. However, you can optionally specify a second
parameter $assoc which accepts a boolean value that when set as true JSON objects are decoded into associative
arrays. It is false by default. Here's an example:
<?php
// Store JSON data in a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
var_dump(json_decode($json, true));
?>
The output of the above example will look something like this:
Now let's check out an example that will show you how to decode the JSON data and access individual elements
of the JSON object or array in PHP.
<?php
// Assign JSON encoded string to a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
10 of page 12
You can also loop through the decoded data using foreach() loop, like this:
<?php
// Assign JSON encoded string to a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
JSON objects and arrays can also be nested. A JSON object can arbitrarily contains other JSON objects, arrays,
nested arrays, arrays of JSON objects, and so on. The following example will show you how to decode a nested
JSON object and print all its values in PHP.
<?php
// Define recursive function to extract nested values
function printValues($arr) {
global $count;
global $values;
/*
Loop through array, if value is itself an array recursively call the
function else add the value found to the output items array,
and increment counter by 1 for each value found
*/
foreach($arr as $key=>$value){
if(is_array($value)){
printValues($value);
} else{
$values[] = $value;
$count++;
}
}
11 of page 12
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
"genre": "Fantasy Fiction",
"price": {
"paperback": "$10.40", "hardcover": "$20.32", "kindle": "4.11"
}
}
}';
// Decode JSON data into PHP associative array format
$arr = json_decode($json, true);
echo "<hr>";
12 of page 12