PHP's date functions are powerful, flexible,
and surprisingly easy to use. This section guides you through the
functions, explaining the concept of a Unix timestamp, which is at the
heart of most of the functions.
Server Side Includes
You can insert the content of one file into another file before the server executes it. include
and require functions are used include others functions, headers, footers, or elements that will
be reused on multiple pages.
This can save the developer a considerable amount of time. If all of the pages on your site have a similar
header, you can include a single file containing the header into your pages. When the header needs updating,
you only update the one page, which is included in all of the pages that use the header.
Example
The following example includes a header and footer that should be used on all pages:
| 03 |
<title>SSI Example</title> |
| 06 |
<?php require "header.php"; ?> |
| 09 |
<?php include "footer.php"; ?> |
Date & Time
PHP's date functions are powerful, flexible, and surprisingly easy to use. This section guides you through the
functions, explaining the concept of a Unix timestamp, which is at the heart of most of the functions, and
shows you how easy it is to master these often-misused functions.
Displaying the current date and time with the date function
date is the most used function that returns the current date and time and allows you to format as
you wish.
| 1 |
date("formatting_options"); |
There are a whole range of possible formatting options. You can add your own characters inside the format
string too. Here's a list of all the formatting characters:
| format character |
Description |
Example returned values |
| Day |
--- |
--- |
| d |
Day of the month, 2 digits with leading zeros |
01 to 31 |
| D |
A textual representation of a day, three letters |
Mon through Sun |
| j |
Day of the month without leading zeros |
1 to 31 |
| l (lowercase 'L') |
A full textual representation of the day of the week |
Sunday through Saturday |
| N |
ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) |
1 (for Monday) through 7 (for Sunday) |
| S |
English ordinal suffix for the day of the month, 2 characters |
st, nd, rd or th. Works well with j |
| w |
Numeric representation of the day of the week |
0 (for Sunday) through 6 (for Saturday) |
| z |
The day of the year (starting from 0) |
0 through 365 |
| Week |
--- |
--- |
| W |
ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) |
Example: 42 (the 42nd week in the year) |
| Month |
--- |
--- |
| F |
A full textual representation of a month, such as January or March |
January through December |
| m |
Numeric representation of a month, with leading zeros |
01 through 12 |
| M |
A short textual representation of a month, three letters |
Jan through Dec |
| n |
Numeric representation of a month, without leading zeros |
1 through 12 |
| t |
Number of days in the given month |
28 through 31 |
| Year |
--- |
--- |
| L |
Whether it's a leap year |
1 if it is a leap year, 0 otherwise. |
| o |
ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) |
Examples: 1999 or 2003 |
| Y |
A full numeric representation of a year, 4 digits |
Examples: 1999 or 2003 |
| y |
A two digit representation of a year |
Examples: 99 or 03 |
| Time |
--- |
--- |
| a |
Lowercase Ante meridiem and Post meridiem |
am or pm |
| A |
Uppercase Ante meridiem and Post meridiem |
AM or PM |
| B |
Swatch Internet time |
000 through 999 |
| g |
12-hour format of an hour without leading zeros |
1 through 12 |
| G |
24-hour format of an hour without leading zeros |
0 through 23 |
| h |
12-hour format of an hour with leading zeros |
01 through 12 |
| H |
24-hour format of an hour with leading zeros |
00 through 23 |
| i |
Minutes with leading zeros |
00 to 59 |
| s |
Seconds, with leading zeros |
00 through 59 |
| u |
Milliseconds (added in PHP 5.2.2) |
Example: 54321 |
| Timezone |
--- |
--- |
| e |
Timezone identifier (added in PHP 5.1.0) |
Examples: UTC, GMT, Atlantic/Azores |
| I (capital i) |
Whether or not the date is in daylight saving time |
1 if Daylight Saving Time, 0 otherwise. |
| O |
Difference to Greenwich time (GMT) in hours |
Example: +0200 |
| P |
Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) |
Example: +02:00 |
| T |
Timezone abbreviation |
Examples: EST, MDT ... |
| Z |
Timezone
offset in seconds. The offset for timezones west of UTC is always
negative, and for those east of UTC is always positive. |
-43200 through 50400 |
| Full Date/Time |
--- |
--- |
| c |
ISO 8601 date (added in PHP 5) |
2004-02-12T15:19:21+00:00 |
| r |
RFC 2822 formatted date |
Example: Thu, 21 Dec 2000 16:01:07 +0200 |
| U |
Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) |
See also time() |
Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a
date/time function will generate a E_NOTICE if the timezone isn't valid,
and/or a E_STRICT message if using the system settings or the TZ environment variable.
Examples
| |
// returns the day (01-31), month (3 letters), and year(4 digits) |
| 2 |
date("d-M-Y"); // displays: 31-Mar-2010 |
The '-' character are my formatting strings. I could have used anything else too:
| 1 |
date("d^^^M^^^Y"); // displays: 31^^^Mar^^^2010 |
| 2 |
date("D dS M, Y h:i a"); // displays: Wed 31st Mar, 2010 06:05 am |
Read through the list above, you'll find most possibilities have been thought of, and if all you're trying to
do is format the date and/or time, you'll have no problems.
date function is not only tied to displaying the local date/time on the server. You can also pass
it a timestamp (often called a Unix timestamp), which is the number of seconds since
January 1, 1970 (starting with 1 second after midnight). By default the date function takes the
current timestamp, but you can pass any timestamp you want, for example:
| 1 |
date("l M dS, Y, H:i:s", 5678); // displays: Thursday Jan 01st, 1970, 01:34:38 |
Be careful though with trying to use one of the reserved format strings as your own format string. If you tried
to do something like:
| 1 |
echo date("The time is H:i"); |
you'd get something like the unexpected result of UTC06UTC 310503UTC 0501 06:05.
Of the first word, The, the 'T' returns the timezone setting of the machine running PHP
(UTC in my case), 'h' returns the hour, and 'e' returns the timezone
identifier. But from there it's all downhill. In order to get the correct display, you'll need to escape the
characters with a backslash, as follows:
| 1 |
echo date("\T\h\e \\t\i\m\e \i\s H:i"); |
which displays what we'd originally hoped for The time is 06:05.
Just for good measure we had to escape the 't' twice, since \t is the special character for a tab.
Not the easiest to read at all!
There is also a related gmdate function, which is identical to the date function
except that the time returned is Greenwich Mean Time (GMT).
Cookies
Cookies in PHP are not difficult to implement, and there are only two commands that need to be used with them.
PHP makes it easy to set and read cookies and provides all the features needed to give their details.
Setting a basic cookie
The PHP function for setting cookies is called setcookie.
The most basic information for a cookie is his name and his value. The name of the cookie must be something
which you can refer to it later as. You don't need to worry about it clashing with other sites as cookie names
are domain specific, but you should try and use a descriptive and unique name for your cookies.
For this first example, assume that you have used PHP to load the user's name into the variable
$name and want to greet the user in the future by their name. You would need to create a cookie
which stores their name as follows:
| 1 |
setcookie("nameOfUser", $name); |
This creates the most basic of cookies, storing the user's name in a cookie called nameOfUser. By
setting cookies like this, you don't set any specific options, so by default the cookie will be available to
the domain in which it was set (e.g. example.com) and will be deleted when the user
closes their browser.
Reading cookie values
PHP makes it extremely simple to read the value of a cookie. In PHP, reading form values are achieved using
$_GET and $_POST. PHP has a similar global variable for cookies:
| 1 |
$_COOKIE["cookie_name"]; |
This variable contains the value of the cookie with name CookieName. So on your website, if you want to
display the name of the user, you could simply use the following:
| 1 |
echo "Hello, " . $_COOKIE["nameOfUser"] . "! Welcome back!"; |
Of course, the user may not already have the cookie, so you should use the PHP function isset.
This returns true if a variable has been set and false if not. Using this, your site
could do the following:
| 1 |
if (isset($_COOKIE["nameOfUser"])) { |
| 2 |
echo "Hello, " . $_COOKIE["nameOfUser"] . "! Welcome back!"; |
| 4 |
setcookie("nameOfUser", $name); |
Cookie settings
Although the code I have given you allows you to set a simple cookie on the user's computer, it isn't very
powerful. Mainly because it's lost when the browser is closed. One of the most powerful features of cookies
is the ability to set an expire date. The cookie will remain on the user's computer until it expires, then it
will automatically delete itself.
| 2 |
setcookie("nameOfUser", $name, time() + 3600); |
This code takes the current time (time function), then adds 3600 seconds to it, and uses this
value to set as the expire time for the cookie. Basically this means that the cookie will remain on the user's
computer for an hour (it expires 3600 seconds from the current time).
There are three other options which can be used when setting cookies:
- The path
-
This refers to where in the domain you are able to access the cookie in future. By default this is the
current directory (so if you set the cookie in the page
http://www.example.com/subfolder/setcookie.php, it would only be available to
scripts in the subfolder directory and below). You can set this to any part of
your site, which can be useful in some situations.
- The domain
-
By default, a cookie is only available in the domain you set it in, for example if you set the cookie on
example.com you can only ever access it from example.com
(even subdomains like mail.example.com can't access it). The most common need to
change this setting is to allow the cookie to be viewed across all subdomains on a site. This can be done
by setting the domain to .example.com (with both '.'s). By doing this anything
.example.com is accepted (like mail.example.com).
- Security
-
If this is turned on, the cookie will only ever be surrendered to the site over a secure connection - HTTPS.
| 1 |
// Cookie with all settings set |
| 2 |
setcookie("nameOfUser", $name, time() + 3600, "/", ".example.com", 1); |
The cookie set here, is called nameOfUser and again stores the value $name.
It will expire an hour from the current time.
It's available in all directories of the site (/ is the root directory).
It's available across any subdomain of the site example.com as
.example.com has been given as the domain.
The final 1 means that this is a secure cookie and can only be transmitted over a secure
connection. This would be 0 for a standard (non-secure) cookie.
Deleting cookies
There are occasions on which you may wish to delete a cookie from a user's computer. This could be if, for
example, you want to log the user out of a system. Deleting a cookie is quite simple to do, all you have to do
is to set the expiry time in the past. By doing this, the cookie will be automatically deleted as soon as it
is created, and will remove any data that already exists there.
| 2 |
setcookie("nameOfUser", "", time() - 3600); |
Sessions
Whenever you want to create a website that allows you to store and display information about a user, determine
which user groups a person belongs to, use permissions on your website or you just want to do something cool,
sessions are vital to each of these features.
You may be thinking right now, well that's nice, but I can do this with cookies! This may come to you as a
surprise, but cookies are about 30% unreliable right now and it's getting worse every day. More and more web
browsers are starting to come with security and privacy settings and people browsing the net these days are
starting to frown upon cookies because they store information on their local computer that they do not want
stored there. PHP has a great set of functions that can achieve the same results of cookies and more without
storing information on the user's computer. Sessions store the information on the web server in a location that
you chose in special files. These files are connected to the user's web browser via the server and a special
id called Session ID. This is nearly 99% flawless in operation and it is virtually
invisible to the user.
Avoiding errors
The first thing about sessions is that you MUST call the session_start function
before anything is output to the web browser. This is absolutely important because you will get some ugly
errors.
| 1 |
echo "Look at this nasty error below:<br>"; |
As you can see, that is one unattractive error to be displayed on your website. Why did it happen? It happened
because I called echo before I called the session_start function. If I had swapped
the lines around I would not have this error.
Starting your session and assigning variables
Let's say that we had an input form from a page that asks the user their name. This form will post to a PHP
script that will get the post information and register it as a session variable that we can use throughout our
website until the user leaves the site or until we unregister that variable.
| 1 |
<form action="register.php" method="post"> |
| 2 |
<p>Enter your Name: <input type="text" name="name"/></p> |
| 3 |
<p><input type="submit" value="Submit"/></p> |
As you can see there is absolutely nothing cosmic about that form. It is only an HTML page
form.html that will post to a script register.php:
| 05 |
// Get the user's input from the form |
| 06 |
$name = $_POST["name"]; |
| 08 |
// Register session key with the value |
| 09 |
$_SESSION["name"] = $name; |
| 10 |
// Could have done $_SESSION["name"] = $_POST["name"]; directly |
| 12 |
// Display the session information: |
| 14 |
<h1>Step 2 - Register session</h1> |
| 16 |
<p>Welcome <em><?php echo $_SESSION["name"]; ?></em>!</p> |
| 17 |
<p>Let's see what happens on the <a href="testSession.php">next page</a>.</p> |
The important elements in the above codeblock are $_SESSION["name"] and that's about it. The rest
is just standard HTML and PHP. If everything worked properly and you typed Bob in the form on the
first page, you'll get the following output:
We've accomplished the following tasks:
- starting a session;
- posting a form to a PHP script;
- registering a session variable with a value;
- and displaying that session value in the browser.
Keeping the session across multiple pages
One reason why we register sessions is to avoid reading cookies and querying databases for information about
the user on each page we need that information on.
The first thing you MUST do on each page you want to access a session variable is to start the
session. That may not sound right to you because you may be thinking We already started the session on the
last page, that's true, but we need to keep the connection going between our session because they do
not have persistent connections like a database does.
Here's the next script called testSession.php. You may have noticed it in the code
examples above.
| 05 |
<h1>Step 3 - Test Session</h1> |
| 07 |
<p>Hey <em><?php echo $_SESSION["name"]; ?></em>. Everything is still working!</p> |
| 08 |
<p>Pick an option:</p> |
| 10 |
<li><a href="delete.php">Delete</a> the session variable now!</li> |
| 11 |
<li><a href="destroy.php">Destroy</a> the session!</li> |
The first few chunks are pretty self explanatory by now if you have been following this tutorial closely.
We started the session, called the session variable and echoed:
Hey Bob. Everything is still working!
Pick an option:
Now you can see how the session variables can be used on multiple pages.
There is also a couple of hyperlinks to two more scripts, delete.php and
destroy.php.
Unregistering session variables
With sessions we have the ability to simply remove a single session variable without dumping our entire session
and rebuilding it. We can simply do this by assigning a blank value or false to the session key we
want to get rid of.
| 05 |
$_SESSION["name"] = false; // same as $_SESSION["name"] = ""; or $_SESSION["name"] = null; |
| 07 |
echo "<h1>Unregister session variable</h1>"; |
| 08 |
if ($_SESSION["name"]) { |
| 09 |
echo "<p>The session is still registered.</p>"; |
| 11 |
echo "<p>Ok! The session is no longer registered!</p>"; |
| 12 |
echo "<p><a href=\"form.html\">Go back to the beginning!</a></p>"; |
Destroying a session
Anytime you have a login feature you should have a logout feature as well. That's where the function
session_destroy comes in handy. session_destroy will completely clear any trace of
the session.
If you are using the $_SESSION superglobal array like we are in this tutorial, you must clear the
array values first, then run session_destroy.
| 05 |
// destroy the session |
| 09 |
echo "<h1>Destroy the session</h1>"; |
| 10 |
if ($_SESSION["name"]) { |
| 11 |
echo "<p>The session is still active.</p>"; |
| 13 |
echo "<p>Ok! The session is no longer active!</p>"; |
| 14 |
echo "<p><a href=\"form.html\">Go back to the beginning!</a></p>"; |
Now that we've covered the basics of session handling such as start a session, register a variable, assign a
value to the variable, unregister the session variable and destroy the session, let's go ahead and use this
knowledge implementing a session hit counter to display how many pages the user has clicked on during their
visit to our site.
Session examples
Page Hit Counter
What we're about to do is start your session, register a variable called count and assign a value
of 1 to it on the first page increment.php. Then, we're going to
increment the counter as we go through the website.
| 05 |
if (!$_SESSION["count"]) { |
| 06 |
$_SESSION["count"] = 1; |
| 12 |
<p>You have visited <?php echo $_SESSION["count"]; ?> pages so far!</p> |
| 13 |
<p><a href="increment.php">Increment</a> your counter!</p> |
| 14 |
<p><a href="reset.php">Reset</a> your counter!</p> |
If the session variable count has no value or is equal to 0, set it to a value of
1, otherwise increment it each time this code is called.
$_SESSION['count']++; is simply saying add 1 to the current value of
count.
Next, we've given the user a page reset.php to reset their counter. This is nearly
the same code as above, except we aren't doing the error checking because we just want to reset the counter
to 1 when the user access that page.
| 05 |
$_SESSION["count"] = 1; |
| 08 |
<p>You have visited <?php echo $_SESSION["count"]; ?> pages so far!</p> |
| 09 |
<p><a href="increment.php">Increment</a> your counter!</p> |
| 10 |
<p><a href="reset.php">Reset</a> your counter!</p> |
Listing your session variables and values
This script is very useful to view which information is actually being stored in your user's sessions.
| 3 |
echo "<p>Sessions list:</p>"; |
The script is pretty straight forward and will give you all the information you need to know about what is in
your session's scope. If you have a $_SESSION["name"] variable with the value John, a
possible output can be:
Sessions list:
Array
(
[name] => John
)
Viewing your Session ID
The function session_id allows you to display the current Session ID or use it
however you need.
| 3 |
echo "<p>Your <strong>Session ID</strong> is <code>" . session_id() . "</code></p>"; |
Your Session ID is 167jDFYp3sTAAAASey0qL6
File handling in PHP
Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for
creating, uploading, and editing files.
File open
fopen function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened and the second parameter
specifies in which mode the file should be opened in.
| 2 |
$file = fopen("file.txt", "r"); |
List of possible modes for fopen:
| mode |
Description |
| 'r' |
Open for reading only; place the file pointer at the |
| 'r+' |
Open for reading and writing; place the file pointer at the beginning of the file. |
| 'w' |
Open for writing only; place the file pointer at the beginning of the file and truncate the file to
zero length. If the file does not exist, attempt to create it.
|
| 'w+' |
Open for reading and writing; place the file pointer at the beginning of the file and truncate the
file to zero length. If the file does not exist, attempt to create it.
|
| 'a' |
Open for writing only; place the file pointer at the end of the file. If the file does not exist,
attempt to create it.
|
| 'a+' |
Open for reading and writing; place the file pointer at the end of the file. If the file does not
exist, attempt to create it.
|
| 'x' |
Create and open for writing only; place the file pointer at the beginning of the file. If the file
already exists, the fopen call will fail by returning FALSE and generating
an error of level E_WARNING. If the file does not exist, attempt to create it. This
is equivalent to specifying O_EXCL | O_CREAT flags for the underlying
open system call.
|
| 'x+' |
Create and open for reading and writing; place the file pointer at the beginning of the file. If
the file already exists, the fopen call will fail by returning FALSE and
generating an error of level E_WARNING. If the file does not exist, attempt to create
it. This is equivalent to specifying O_EXCL | O_CREAT flags for the
underlying open system call.
|
If the fopen function is unable to open the specified file, it returns 0
(false).
| 2 |
if (!($file = fopen("file.txt", "r"))) { |
| 3 |
exit("Unable to open file!"); |
File close
fclose function is used to close a file.
End of file
feof function is used to determine if the end of file is true.
You cannot read from files opened in w, a, and x mode!
Read a character
fgetc function is used to read a single character from a file.
The file pointer move to the next character each time this function is called.
| 02 |
if (!($file = fopen("file.txt", "r"))) { |
| 03 |
exit("Unable to open file!"); |
| 06 |
while (!feof($file)) { |
File delete
When you view the contents of a directory you can see all the files that exist in that directory because the
system displays a list of filenames. You can think of these filenames as links that the system has created to
link a directory with those listed files.
If you unlink a file, you are effectively causing the system to forget about it or delete it!
Before you can delete a file, you must make sure that the file isn't open in your application. Use
fclose function to close down a file.
To delete the file file.txt simply run a PHP script that is located in the same
directory. unlink function just needs to know the name of the file to start working its
destructive magic.
File upload
A very useful aspect of PHP
|