PHP Programming Unit 5
PHP Programming Unit 5
UNIT V
PHP ADVANCED CONCEPTS- USING COOKIES, USING HTTP HEADERS, USING
SESSIONS, USING ENVIRONMENT AND CONFIGURATION VARIABLES.
WORKING WITH DATE AND TIME-DISPLAYING HUMAN-READABLE DATES AND
TIMES, FINDING THE DATE FOR A WEEKDAY, GETTING THE DAY AND WEEK OF
THE YEAR, DETERMINING WHETHER A GIVEN YEAR IS A LEAP YEAR, OBTAINING
THE DIFFERENCE BETWEEN TWO DATES, DETERMINING THE NUMBER OF DAYS
IN THE CURRENT MONTH, DETERMINING THE NUMBER OF DAYS IN ANY GIVEN
MONTH.
COOKIES: A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page with a browser, it
will send the cookie too. With PHP, you can both create and retrieve cookie values.
OR
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
OR
Cookies are text files stored on the client computer and they are kept of use tracking purpose
Syntax ssetcookie ( string name [, string value [, int expire [, string path [, string
domain [, bool secure]]]]] )
Parameter Description
name The name to set the cookie variable to and hence
the name to access it with
value The value of the current cookie
expire When a cookie will expire (in the form of a Unix
timestamp)
path The directory where the cookie will be available for
use
domain The domain at which the cookie will be available
secure Whether a cookie can be read on a non-SSL enable
script
setcookie($cookie_name, $cookie_value, time() + (86400 * 30));
<?php
setcookie("username", "John Carter", time()+30*24*60*60);
?>
Retrieve a Cookie: We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set or not:
<?php
echo $_COOKIE["username"];
?>
<?php
if(isset($_COOKIE["username"]))
echo "Hi " . $_COOKIE["username"];
else
echo "Welcome Guest!";
?>
Modify a Cookie Value: To modify a cookie, just set (again) the cookie using the setcookie()
function:
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
Deleting Cookie with PHP: 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
setcookie("username", "", time()-3600);
?>
A session is a way to store information (in variables) to be used across multiple pages.Unlike a
cookie, the information is not stored on the users computer.
What is a PHP Session?
When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.Session variables solve
this problem by storing user information to be used across multiple pages (e.g. username,
favorite color, etc). By default, session variables last until the user closes the browser.So; Session
variables hold information about one single user, and are available to all pages in one
application.
Why and when to use Sessions?
You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
You want to pass values from one page to another.
You want the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to
passing them in the URL
You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
Creating a Session: A session is started with the session_start() function.
<?php
session_start();
?>
Creating php session variables:Session variables are set with the PHP global variable:
$_SESSION.
<?php
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
?>
Get PHP Session Variable Values
Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
Another way to show all the session variable values for a user session is to run the following
code:
<?php
print_r($_SESSION);
?>
O/P: Array ( [favcolor] => green [favanimal] => cat )
Modify a PHP Session Variable
To change a session variable, just overwrite it:
<?php
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
O/P: Array ( [favcolor] => yellow [favanimal] => cat )
Destroy a PHP Session
To remove all global session variables and destroy the session,
use session_unset() and session_destroy():
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo"session are unset";
?>
O/P: session are unset
PHP header() Function
The header() function sends a raw HTTP header to a client.
It is important to notice that header() must be called before any actual output is sent (In PHP 4
and later, you can use output buffering to solve this problem):
<html>
<?php
header('Location: http://www.example.com/');
?>
Syntax: header(string,replace,http_response_code)
Parameter Description
http_response_code Optional. Forces the HTTP response code to the specified value
(available in PHP 4.3 and higher)
The most important aspect to remember about headers is that they can be called only before any
output has been written to the web page. If you attempt to call a header after output has been sent
to the page, you will generate an error; hence, your script will fail on you.
You can use them to control everything, including setting the current page location, finding
out what file format is being displayed, and managing all aspects of the browser cache. The
header() function’s prototype is as follows:
void header ( string string [, bool replace [, int http_response_code]] )
Redirecting to a Different Location
One of the more common uses for HTTP headers is redirecting a script. By using headers
inside processing scripts, you can force the browser to return to any page you want. We prefer to
use headers to control exception handling within process scripts. The following script
makes sure that all input coming from a form is not blank.
<html>
<body>
<form action="sample12_5.php" method="post">
Name: <input type="text" name="yourname" ><br />
<input type="submit" value="Submit" >
</form>
</body>
</html>
The form in the previous block of code will then call the processing statement as follows:
<?php
//You will assume that this scripts main focus is to validate against a blank entry.
if (trim ($_POST['yourname']) == "")
{
header ("Location: sample12_5.html");
exit;
}
echo $_POST['yourname'];
?>
The header() function is rather nice in that it will redirect you automatically to the appropri-ate
file (providing it exists) without a single hiccup in the processing. You will simply find yourself
at the appropriate page. You can even use the header() function with the Location parameter to
send you to a page not currently on the server on which the script is located.
Sending Content Types Other Than HTML
Naturally, sometimes you will want to use the header() function to output a type of file format
that may not be an actual web page. Thankfully, the header function is more than versatile
enough to take care of this issue. To make the most out of this function, you can effectively
output other file types by simply declaring the content type you want to output.This functionality
can be handy in circumstances where you want to deploy a document to a user or perhaps even
output a dynamic image. You can use the following script to output a
JPG image to the user.
<html>
<body>
<img src="sample12_6.php" alt="" title="" style="border: none;" />
</body>
</html>
<?php
$path = "images/winter.jpg";
try
{
if (is_file ($path))
{
the same way, provided you use the proper content type (more widely known as a MIME type).
Table lists a few of the popular MIME types you may be interested in using as output.
A common use of the environment variables in PHP is for dynamic imaging. By using PHP’s
environment variables to determine the current operating system,you can make your code
slightly more portable.
Using configuration variables in PHP is for particularly with file upload scripts.
The PHP installation leaves only enough processing time to upload files that are generally 2MB
or smaller in size. By manipulating the PHP configuration files temporarily, you can increase the
limit enough to allow a script to process much larger files.
Reading Environment and Configuration Variables
PHP 5 makes reading environment and configuration variables easy. The $_ENV superglobal is
used for reading a system’s environment variables and has an argument set that is based upon the
current environment that is available to it. Because of its flexibility,there is no real set argument
list, as it is generated based on the current server environment.You can use the phpinfo()
function to determine the current environment variables, and you can retrieve them using the
getenv() function, which needs to be supplied a valid environ-ment variable name.
Reading configuration variables, on the other hand, takes place through two functions,ini_get()
and ini_get_all(). The function ini_get() will retrieve the value of a specified configuration
variable, and the function ini_get_all() will retrieve an array filled with the entire selection of
configuration variables that are available.
configuration variable for the script’s duration. Once the script finishes executing, the
configuration variable will return to its original state. The prototype for ini_set() is as follows:
string ini_set ( string varname, string newvalue )
<?php
//Setting an environment variable in php is as easy as assigning it.
echo $_ENV['COMPUTERNAME'] . "<br />"; // Echoes BABINZ-CODEZ.
$_ENV['COMPUTERNAME'] = "Hello World!";
echo $_ENV['COMPUTERNAME'] . "<br />"; //Echoes the new COMPUTERNAME.
//Of course the change is relevant only for the current script.
//Setting a configuration variable is the same in that it is in effect only for the duration of the
script.
echo ini_get ('post_max_size'); //Echoes 8MB.
//Then you set it to 200M for the duration of the script.
ini_set('post_max_size','200M');
//Any files that are to be uploaded in this script will be OK up to 200M.
?>
checkdate() Validates set of Gregorian year, month, and day values (for example,
2005, 3, 17).
date_sunrise() Returns time of sunrise for a given day and location (new in PHP 5).
date_sunset() Returns time of sunset for a given day and location (new in PHP 5).
date() Formats a local date/time, given a Unix timestamp (for example,
1111035030000 ) and a formatting string.
getdate() Given a Unix timestamp, returns an associative array containing date and
time information (defaults to current time).
gettimeofday() Returns an associative array containing information about the current
system time.
gmdate() Formats a GMT/UTC date/time. Uses the same formatting characters as
the date() function.
gmmktime() Converts a set of GMT date/time values into a Unix timestamp (analogous
to mktime()).
gmstrftime() Formats a GMT/UTC date/time according to locale settings
idate() Formats a local time/date value as an integer.
localtime() Given a Unix timestamp, returns an array of date/time values..
Day
d Day of the month, with leading zeros (two digits).
j Day of the month (no leading zeros).
S Ordinal suffix for the day of the month, two characters (st, nd, th); most
commonly used in combination with j.
l (lowercase L) Full name of the day of the week (Monday, Tuesday, and so on).
D A textual representation of a day, three letters (Mon, Tue, and so on).
w Numeric representation of the day of the week (0 = Sunday, 6 = Saturday).
Year
y Two-digit year.
Y Four-digit year.
Hour
h Hour in 12-hour format, with leading zero (two digits).
g Hour in 12-hour format (no leading zero).
H Hour in 24-hour format, with leading zero (two digits).
Minute
i Minute, with leading zero (two digits).
j Minute (no leading zero).
Second
s Second, with leading zero (two digits).
Z Integer representation of the difference in seconds between local time and
GMT/UTC (for example, 36000 for GMT+1000 and –18000 for GMT–
0500).
2005-03-14T19:38:08+10:00).
r RFC-2822 format WWW, DD MMM YYYY HH:MM:SS ±HHMM, for
example, Mon,14 Mar 2005 19:38:08 +1000).
U Seconds since the Unix epoch. Calling date('U') with no timestamp
argument produces the same output as the time() function.
'c',
'l, F jS, Y, g:i A',
'H:i:s D d M y',
);
foreach($formats as $format)
echo "<p><b>$format</b>: " . date($format, $time) . "</p>\n";
?>
Output:
U: 1110643578
r: Sun, 13 Mar 2005 02:06:18 +1000
c: 2005-03-13T02:06:18+10:00
l, F jS, Y, g:i A: Sunday, March 13th, 2005, 2:06 AM
H:i:s D d M y: 02:06:18 Sun 13 Mar 05
For example, suppose that your firm’s sales employees are supposed to turn in their monthly
sales reports on the first Tuesday of each month. The following example shows how you can
determine the date of the first Tuesday in the month following the current one.
Example2:
<?php
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo 'Today is ' . date('d M Y') . '.<br />\n';
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';
?>
Output:
Today is 15 Mar 2005.
The first Tuesday of next month is 05 Apr 2005.
Explanation:
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
The inner call to date() returns an integer corresponding to the current month, to which
you add 1. You then use this as part of the argument to another date() call, which returns the
string 2005-4-01.
$nextmonth_ts = strtotime($nextmonth);:
This stores the timestamp equivalent to 2005-4-01 in $nextmonth_ts.
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';:
Finally, you feed the $firsttue_ts timestamp to date() and output the result in dd-MM-
yyyy format.
Example3:
<?php
echo 'Today is ' . date('d M Y') . '.';
for($i = 1; $i <= 12; $i++)
{
$nextmonth = date('Y-' . (date('n') + $i) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo '\n<br />The first Tuesday in ' . date('F', $firsttue_ts)
. ' is ' . date('d M Y', $firsttue_ts) . '.';
}
?>
Output:
Today is 15 Mar 2005.
The first Tuesday of April is 05 Apr 2005.
The first Tuesday of May is 03 May 2005.
The first Tuesday of June is 07 Jun 2005.
The first Tuesday of July is 05 Jul 2005.
The first Tuesday of August is 02 Aug 2005.
The first Tuesday of September is 06 Sep 2005.
The first Tuesday of October is 04 Oct 2005.
The first Tuesday of November is 01 Nov 2005.
The first Tuesday of December is 06 Dec 2005.
The first Tuesday of January is 03 Jan 2006.
The first Tuesday of February is 07 Feb 2006.
The first Tuesday of March is 07 Mar 2006.
NOTE: The numbering of the days of the year as derived using date('z') begins with 0, which
means you will likely need to add 1 to the result before displaying it.
Getting the number of the week in the year is also quite simple: all that is required is to pass
an uppercase was a formatting character to date().
Example5:
<?php
$mydates = array('2005-01-01', '2005-01-03', '2005-05-22', '2005-05-23',
'2005-12-31');
foreach($mydates as $mydate)
echo date("D d M Y: \w\e\e\k W", strtotime($mydate)) . "<br />\n";
?>
Output:
Sat 01 Jan 2005: week 53
Mon 03 Jan 2005: week 1
Sun 22 May 2005: week 20
Example6:
<?php
NOTE: A final note regarding leap years: you should remember that years ending in 00 are leap
years only if the first two digits of the year taken as a two-digit number are evenly divisible by 4.
This means that although 2000 was a leap year (20 % 4 = 0), 1900 and 2100 are not (19 % 4 = 3;
21 % 4 = 1).
As you have already had the chance to see, altering a date by a given interval is not difficult.
Getting the difference between two dates is a bit more complicated.
Example7:
<?php
$date1 = '14 Jun 2002';
$date2 = '05 Feb 2006';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$min = ($ts2 - $ts1)/60;
$hour =$min/60;
$day = $hour/24;
printf("<p>The difference between %s and %s is %d seconds.<p>\n",$date1, $date2, $ts2
- $ts1);
printf("<p>The difference between %s and %s is %d minutes.<p>\n",$date1, $date2
,$min);
printf("<p>The difference between %s and %s is %d hours.<p>\n",$date1, $date2,
$hour);
printf("<p>The difference between %s and %s is %d days.<p>\n",$date1, $date2, $day);
?>
Output:
The difference between 14 Jun 2002 and 05 Feb 2006 is 115084800 seconds.
The difference between 14 Jun 2002 and 05 Feb 2006 is 1918140 minutes.
The difference between 14 Jun 2002 and 05 Feb 2006 is 31969 hours.
The difference between 14 Jun 2002 and 05 Feb 2006 is 1332 days.
Example8:
<?php
echo 'Number of days for the month of '.date('M'). ' is :' .date('t')."\n";
?>
Output:
Number of days for the month of Sep is: 30
Example9:
<?php
echo cal_days_in_month(CAL_GREGORIAN, 10, 2014);
echo date('t',strtotime('2014/10/01'));
?>
Output:
31
31
strptime() Given a date/time string generated with strftime() and the formatting string
used to generate it, returns a Unix timestamp (new in PHP 5.1).
strtotime() Converts an English textual date/time description into a Unix timestamp.
time() Returns the current system date and time as a Unix timestamp.
Formatting Characters for the date() Function
Character Description
Month
F Full name of the month (January, February, and so on).
M Three-letter abbreviation for the month (Jan, Feb, and so on).
m Numeric representation for the month, with leading zero (two digits).
n Numeric representation for the month (no leading zero).
Day
d Day of the month, with leading zeros (two digits).
j Day of the month (no leading zeros).
S Ordinal suffix for the day of the month, two characters (st, nd, th); most
commonly used in combination with j.
l (lowercase L) Full name of the day of the week (Monday, Tuesday, and so on).
Year
y Two-digit year.
Y Four-digit year.
Hour
h Hour in 12-hour format, with leading zero (two digits).
g Hour in 12-hour format (no leading zero).
H Hour in 24-hour format, with leading zero (two digits).
G Hour in 24-hour format (no leading zero).
a am/pm (lowercase).
A AM/PM (uppercase).
O (uppercase o) String representation of the difference in hours between local time and
GMT/UTC (for example, +1000, –0500).
Minute
Second
s Second, with leading zero (two digits).
Z Integer representation of the difference in seconds between local time and
GMT/UTC (for example, 36000 for GMT+1000 and –18000 for GMT–
0500).
To obtain a timestamp for the current system date and time, it is necessary only to call the
time() function, as shown here:
<?php
echo time();
?>
In a web browser, this produces output such as the following:
1110638611
For obtaining a human-readable date and time, PHP provides the date() function. When
called with a single argument (a formatting string), this function returns a string
representation of the current date and/or time. The optional second argument is a
timestamp.
Example1:
<?php
$time = time();
$formats = array(
'U',
'r',
'c',
how you can determine the date of the first Tuesday in the month following the current
one.
Example2:
<?php
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo 'Today is ' . date('d M Y') . '.<br />\n';
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';
?>
Output:
Today is 15 Mar 2005.
The first Tuesday of next month is 05 Apr 2005.
Explanation:
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
The inner call to date() returns an integer corresponding to the current month, to which you add
1. You then use this as part of the argument to another date() call, which returns the string 2005-
4-01.
$nextmonth_ts = strtotime($nextmonth);:
This stores the timestamp equivalent to 2005-4-01 in $nextmonth_ts.
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';:
Finally, you feed the $firsttue_ts timestamp to date() and output the result in dd-MM-yyyy
format.
Example3:
<?php
echo 'Today is ' . date('d M Y') . '.';
for($i = 1; $i <= 12; $i++)
{
$nextmonth = date('Y-' . (date('n') + $i) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo '\n<br />The first Tuesday in ' . date('F', $firsttue_ts)
. ' is ' . date('d M Y', $firsttue_ts) . '.';
}
?>
Output:
Today is 15 Mar 2005.
The first Tuesday of April is 05 Apr 2005.
The first Tuesday of May is 03 May 2005.
$ts = strtotime($mydate);
echo 'Day ' . date('d M Y: z', $ts) . "<br />\n";
}
?>
Output:
01 Jan 2005: Day 0
30 Jun 2005: Day 180
31 Dec 2005: Day 364
NOTE: The numbering of the days of the year as derived using date('z') begins with 0, which
means you will likely need to add 1 to the result before displaying it.
Getting the number of the week in the year is also quite simple: all that is required is to
pass an uppercase was a formatting character to date().
Example5:
<?php
$mydates = array('2005-01-01', '2005-01-03', '2005-05-22', '2005-05-23',
'2005-12-31');
foreach($mydates as $mydate)
echo date("D d M Y: \w\e\e\k W", strtotime($mydate)) . "<br />\n";
?>
Output:
Sat 01 Jan 2005: week 53
Mon 03 Jan 2005: week 1
Sun 22 May 2005: week 20
Mon 23 May 2005: week 21
Sat 31 Dec 2005: week 52
Determining Whether a Given Year Is a Leap Year
The date() function employs another one-letter argument; it uses L to determine if a given
year is a leap year.
When L is used, date() returns 1 if the year in question is a leap year and 0 if it is not.
Rather than make repeated calls to date() and strtotime(), you can wrap this in a simple
function that takes the year to be tested as an argument, as shown in the following
example.
Example6:
<?php
// takes a 2- or 4-digit year,
// returns 1 or 0
function is_leap_year($year)
{
$ts = strtotime("$year-01-01");
return date('L', $ts);
}
// test the function for a set of 11 consecutive years
for($i = 2000; $i <= 2010; $i++)
{
$output = "$i is ";
If( !is_leap_year($i) )
$output .= "not ";
$output .= "a leap year.<br />\n";
echo $output;
}
?>
How It Works
The result of the test loop is as follows:
2000 is a leap year.
2001 is not a leap year.
2002 is not a leap year.
2003 is not a leap year.
2004 is a leap year.
2005 is not a leap year.
2006 is not a leap year.
2007 is not a leap year.
2008 is a leap year.
2009 is not a leap year.
2010 is not a leap year.
NOTE: A final note regarding leap years: you should remember that years ending in 00 are leap
years only if the first two digits of the year taken as a two-digit number are evenly divisible by 4.
This means that although 2000 was a leap year (20 % 4 = 0), 1900 and 2100 are not (19 % 4 = 3;
21 % 4 = 1).
Obtaining the Difference between Two Dates
As you have already had the chance to see, altering a date by a given interval is not
difficult.
Getting the difference between two dates is a bit more complicated.
Example7:
<?php
$date1 = '14 Jun 2002';
$date2 = '05 Feb 2006';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$min = ($ts2 - $ts1)/60;
$hour =$min/60;
$day = $hour/24;
printf("<p>The difference between %s and %s is %d seconds.<p>\n",$date1, $date2, $ts2
- $ts1);
printf("<p>The difference between %s and %s is %d minutes.<p>\n",$date1, $date2 ,$min);
printf("<p>The difference between %s and %s is %d hours.<p>\n",$date1, $date2, $hour);
printf("<p>The difference between %s and %s is %d days.<p>\n",$date1, $date2, $day);
?>
Output:
The difference between 14 Jun 2002 and 05 Feb 2006 is 115084800 seconds.
The difference between 14 Jun 2002 and 05 Feb 2006 is 1918140 minutes.
The difference between 14 Jun 2002 and 05 Feb 2006 is 31969 hours.
The difference between 14 Jun 2002 and 05 Feb 2006 is 1332 days.
Determining the number of days in the current month
We are using date(‘t’) function for finding number of days in a month.
For finding number of days in current months we use both date(‘t’) and date(‘M’)
functions.
Example8:
<?php
echo 'Number of days for the month of '.date('M'). ' is :' .date('t')."\n";
?>
Output:
Number of days for the month of Sep is: 30
Determining the number of days in any given month
The cal_days_in_month() function returns the number of days in a month for a specified
year and calendar.
Syntax is
int cal_days_in_month ( int $calendar , int $month , int $year )
Example9:
<?php
echo cal_days_in_month(CAL_GREGORIAN, 10, 2014);
echo date('t',strtotime('2014/10/01'));
?>
Output:
31
31
Convert the month number to month name.
Example:
<?php
echo 'Write your code here';
$month_num = 9;
$dateObj = DateTime::createFromFormat('!m', $month_num);
$month_name = $dateObj->format('F');
echo $month_name."\n";
?>
Output:
September
Count the number of days between current day and birthday.
<?php
$target_days = mktime(0,0,0,12,31,2018);// modify the birth day 12/31/2013
$today = time();
$diff_days = ($target_days - $today);
$days = (int)($diff_days/86400);
print "Days till next birthday: $days days!"."\n";
?>