Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
110 views

PHP Programming Unit 5

This document discusses advanced PHP concepts including cookies, sessions, HTTP headers, and working with dates and times. Cookies are small files stored on a user's computer that are used to identify users as they navigate a website. Sessions are used to store user information across multiple pages using server-side variables. HTTP headers can be used to redirect pages, set content types, and manage caching. The document provides code examples for creating, retrieving, modifying, and deleting both cookies and sessions in PHP.

Uploaded by

Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

PHP Programming Unit 5

This document discusses advanced PHP concepts including cookies, sessions, HTTP headers, and working with dates and times. Cookies are small files stored on a user's computer that are used to identify users as they navigate a website. Sessions are used to store user information across multiple pages using server-side variables. HTTP headers can be used to redirect pages, set content types, and manage caching. The document provides code examples for creating, retrieving, modifying, and deleting both cookies and sessions in PHP.

Uploaded by

Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

PHP PROGRAMMING

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

Prepared By: Dept Of CSE, RGMCET Page 1


PHP PROGRAMMING

There are three steps involved in identifying returning users −


 Server script sends a set of cookies to the browser. For ex name, age, or identification
number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Prepared By: Dept Of CSE, RGMCET Page 2


PHP PROGRAMMING

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);
?>

Prepared By: Dept Of CSE, RGMCET Page 3


PHP PROGRAMMING

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), "/");
?>

Prepared By: Dept Of CSE, RGMCET Page 4


PHP PROGRAMMING

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?

Prepared By: Dept Of CSE, RGMCET Page 5


PHP PROGRAMMING

 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";

Prepared By: Dept Of CSE, RGMCET Page 6


PHP PROGRAMMING

?>
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);

Prepared By: Dept Of CSE, RGMCET Page 7


PHP PROGRAMMING

?>
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.

Prepared By: Dept Of CSE, RGMCET Page 8


PHP PROGRAMMING

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

string Required. Specifies the header string to send

replace Optional. Indicates whether the header should replace previous or


add a second header. Default is TRUE (will replace). FALSE
(allows multiple headers of the same type)

http_response_code Optional. Forces the HTTP response code to the specified value
(available in PHP 4.3 and higher)

Using HTTP Headers

Prepared By: Dept Of CSE, RGMCET Page 9


PHP PROGRAMMING

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>

Prepared By: Dept Of CSE, RGMCET Page 10


PHP PROGRAMMING

</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

Prepared By: Dept Of CSE, RGMCET Page 11


PHP PROGRAMMING

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))
{

Prepared By: Dept Of CSE, RGMCET Page 12


PHP PROGRAMMING

if ($file = fopen($path, 'rb'))


{
while(!feof($file) and (connection_status()==0)) {
$f .= fread($file, 1024*8);
}
fclose($file);
}
//Use the header function to output an image of .jpg.
header ("Content-type: image/jpeg");
print $f;
}
else
{
throw new exception ("Sorry, file path is not valid.");
}
}
catch (exception $e)
{

Prepared By: Dept Of CSE, RGMCET Page 13


PHP PROGRAMMING

//Create a dynamic error message.


$animage = imagecreate (500, 500);
$red = imagecolorallocate ($animage, 255, 0, 0);
$white = imagecolorallocate ($animage, 255, 255, 255);
imagefilledrectangle ($animage, 0, 0, 500, 500, $white);
imagestring ($animage,4,((500–(strlen($e->getmessage())
* imagefontwidth(4))) / 2), 5, $e->getmessage(), $red);
imagejpeg ($animage);
header ("Content-type: image/jpeg");
imagedestroy ($animage);
}
?>
Although the error handling for this particular function may be a tad beyond the scope of this
particular chapter, those who have studied Chapter 8 should have no trouble with it. Excep- tion
handling aside, what you are doing here is basically reading a file as a binary object. Then, by
utilizing the header() function, you can output it as a JPG by merely printing it. You can use this
same sort of procedure to read pretty much any file as a binary object and then output it in much

Prepared By: Dept Of CSE, RGMCET Page 14


PHP PROGRAMMING

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.

Content Type Application


application/pdf Adobe Portable Document Format (PDF)
types
application/msword Microsoft Word documents
application/excel Microsoft Excel documents
image/gif GIF images
image/png PNG images
application/octet-stream Zip files
text/plain Plain text (text files)
USING ENVIRONMENT AND CONFIGURATION VARIABLES:
PHP provides a way to use and verify the configuration settings and environment variables
relative to the server space the script is occupying.By having access to environment variables,
you can customize your scripts to work optimally on the platform that is available. By having
access to the config-uration variables of PHP, you can customize the PHP environment your
script is working in for special occurrences.

Prepared By: Dept Of CSE, RGMCET Page 15


PHP PROGRAMMING

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.

Prepared By: Dept Of CSE, RGMCET Page 16


PHP PROGRAMMING

Example shows how to retrieve both environment and configuration variables.


<?php
//Here is an example of retrieving an environmental variable or two.
echo $_ENV['ProgramFiles'] . "<br />"; //Outputs C:\Program Files.
echo $_ENV['COMPUTERNAME'] . "<br />"; //Outputs BABINZ-CODEZ.
echo getenv("COMPUTERNAME") . "<br />"; //Also Outputs
//Now, let's look at reading configuration variables.
echo ini_get ("post_max_size") . "<br />"; //Outputs 8MB.
//And you can output the entire listing with this function.
print_r (ini_get_all());
?>
Setting Environment and Configuration Variables
Setting environment and configuration variables is just as easy as it is to get them. While
working with environment variables, you must need to assign a new value to the $_ENV
superglobal to process a temporary change. The change will be in effect for the script’s dura-
tion. The same applies for configuration variables but with a different approach. To set a
configuration variable, you have to use the PHP function ini_set(), which will allow you to set a

Prepared By: Dept Of CSE, RGMCET Page 17


PHP PROGRAMMING

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.
?>

DATE & TIME FUNCTIONS


Function Description

Prepared By: Dept Of CSE, RGMCET Page 18


PHP PROGRAMMING

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..

Prepared By: Dept Of CSE, RGMCET Page 19


PHP PROGRAMMING

microtime() Returns a string representation of the current Unix timestamp with


microseconds.
mktime() Converts a set of local date/time values into a Unix timestamp.
strftime() Given a timestamp and a formatting string, returns a representation of a
local date/time according to locale settings.
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).

Prepared By: Dept Of CSE, RGMCET Page 20


PHP PROGRAMMING

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).

Prepared By: Dept Of CSE, RGMCET Page 21


PHP PROGRAMMING

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
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).

Complete Date and Time


c ISO-8601 format (YYYY-MM-DDTHH:MM:SS±HHMM, for example,

Prepared By: Dept Of CSE, RGMCET Page 22


PHP PROGRAMMING

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.

Prepared By: Dept Of CSE, RGMCET Page 23


PHP PROGRAMMING

Displaying Human-Readable Dates and Times


 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',

Prepared By: Dept Of CSE, RGMCET Page 24


PHP PROGRAMMING

'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

Finding the Date for a Weekday


 By combining date() and strtotime(), it is possible get the day for any desired weekday in a
given month.

Prepared By: Dept Of CSE, RGMCET Page 25


PHP PROGRAMMING

 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');

Prepared By: Dept Of CSE, RGMCET Page 26


PHP PROGRAMMING

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.

$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);:


Using the timestamp just obtained as the second argument to strtotime(), you get a new
timestamp, $firsttue_ts. Since the first argument to strttime() is simply the string Tuesday, the
function looks for the first date following the date corresponding to $nextmonth_ts that falls on a
Tuesday. The timestamp corresponding to this date is stored as $firsttue_ts.

echo 'Today is ' . date('d M Y') . '.<br />\n';:


To provide a basis for comparison, you output the current date in dd-MM-yyyy format.

echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';:

Prepared By: Dept Of CSE, RGMCET Page 27


PHP PROGRAMMING

Finally, you feed the $firsttue_ts timestamp to date() and output the result in dd-MM-
yyyy format.

Prepared By: Dept Of CSE, RGMCET Page 28


PHP PROGRAMMING

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) . '.';
}
?>

Prepared By: Dept Of CSE, RGMCET Page 29


PHP PROGRAMMING

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.

Prepared By: Dept Of CSE, RGMCET Page 30


PHP PROGRAMMING

Getting the Day and Week of the Year


 Obtaining the day of the year is fairly simple; you need use only a lowercase z in the first
argument to the date() function.
Example4:
<?php
$mydates = array('2005-01-01', '2005-06-30', '2005-12-31');
foreach($mydates as $mydate)
{
$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

Prepared By: Dept Of CSE, RGMCET Page 31


PHP PROGRAMMING

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

Prepared By: Dept Of CSE, RGMCET Page 32


PHP PROGRAMMING

Mon 23 May 2005: week 21


Sat 31 Dec 2005: week 52

Prepared By: Dept Of CSE, RGMCET Page 33


PHP PROGRAMMING

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

Prepared By: Dept Of CSE, RGMCET Page 34


PHP PROGRAMMING

// 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

Prepared By: Dept Of CSE, RGMCET Page 35


PHP PROGRAMMING

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).

Prepared By: Dept Of CSE, RGMCET Page 36


PHP PROGRAMMING

Obtaining the Difference between Two Dates

Prepared By: Dept Of CSE, RGMCET Page 37


PHP PROGRAMMING

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);

Prepared By: Dept Of CSE, RGMCET Page 38


PHP PROGRAMMING

?>
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

Prepared By: Dept Of CSE, RGMCET Page 39


PHP PROGRAMMING

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

Prepared By: Dept Of CSE, RGMCET Page 40


PHP PROGRAMMING

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

Prepared By: Dept Of CSE, RGMCET Page 41


PHP PROGRAMMING

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";
?>

Prepared By: Dept Of CSE, RGMCET Page 42


PHP PROGRAMMING

DATE & TIME FUNCTIONS


Function Description
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).

Prepared By: Dept Of CSE, RGMCET Page 43


PHP PROGRAMMING

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..
microtime() Returns a string representation of the current Unix timestamp with
microseconds.
mktime() Converts a set of local date/time values into a Unix timestamp.
strftime() Given a timestamp and a formatting string, returns a representation of a
local date/time according to locale settings.

Prepared By: Dept Of CSE, RGMCET Page 44


PHP PROGRAMMING

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).

Prepared By: Dept Of CSE, RGMCET Page 45


PHP PROGRAMMING

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).
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

Prepared By: Dept Of CSE, RGMCET Page 46


PHP PROGRAMMING

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).

Complete Date and Time


c ISO-8601 format (YYYY-MM-DDTHH:MM:SS±HHMM, for example,
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.

Displaying Human-Readable Dates and Times

Prepared By: Dept Of CSE, RGMCET Page 47


PHP PROGRAMMING

 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',

Prepared By: Dept Of CSE, RGMCET Page 48


PHP PROGRAMMING

'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
Finding the Date for a Weekday
 By combining date() and strtotime(), it is possible get the day for any desired weekday in
a given month.
 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

Prepared By: Dept Of CSE, RGMCET Page 49


PHP PROGRAMMING

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');

Prepared By: Dept Of CSE, RGMCET Page 50


PHP PROGRAMMING

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.

$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);:


Using the timestamp just obtained as the second argument to strtotime(), you get a new
timestamp, $firsttue_ts. Since the first argument to strttime() is simply the string Tuesday, the
function looks for the first date following the date corresponding to $nextmonth_ts that falls on a
Tuesday. The timestamp corresponding to this date is stored as $firsttue_ts.

echo 'Today is ' . date('d M Y') . '.<br />\n';:


To provide a basis for comparison, you output the current date in dd-MM-yyyy format.

echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';:

Prepared By: Dept Of CSE, RGMCET Page 51


PHP PROGRAMMING

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.

Prepared By: Dept Of CSE, RGMCET Page 52


PHP PROGRAMMING

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.
Getting the Day and Week of the Year
 Obtaining the day of the year is fairly simple; you need use only a lowercase z in the first
argument to the date() function.
Example4:
<?php
$mydates = array('2005-01-01', '2005-06-30', '2005-12-31');
foreach($mydates as $mydate)
{

Prepared By: Dept Of CSE, RGMCET Page 53


PHP PROGRAMMING

$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');

Prepared By: Dept Of CSE, RGMCET Page 54


PHP PROGRAMMING

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:

Prepared By: Dept Of CSE, RGMCET Page 55


PHP PROGRAMMING

<?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;
}
?>

Prepared By: Dept Of CSE, RGMCET Page 56


PHP PROGRAMMING

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

Prepared By: Dept Of CSE, RGMCET Page 57


PHP PROGRAMMING

 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);
?>

Prepared By: Dept Of CSE, RGMCET Page 58


PHP PROGRAMMING

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

Prepared By: Dept Of CSE, RGMCET Page 59


PHP PROGRAMMING

 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);

Prepared By: Dept Of CSE, RGMCET Page 60


PHP PROGRAMMING

$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";
?>

Prepared By: Dept Of CSE, RGMCET Page 61

You might also like