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 have to update one file, which is included in all the pages that will use that header.
The following example includes a header and a footer from an external file:
<html>
<head>
<title>SSI Example</title>
</head>
<body>
<?php require "header.php"; ?>
<p>Some text...</p>
<p>More text...</p>
<?php include "footer.php"; ?>
</body>
</html>
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.
date functiondate is a function that returns the current date and time and allows you to format it as you wish.
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 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() |
// returns the day (01-31), month (3 letters) and year(4 digits)
date("d-M-Y"); // displays: 26-Feb-2012
The '-' character are my formatting strings. I could have used anything else too:
date("d^^^M^^^Y"); // displays: 26^^^Feb^^^2012
date("D dS M, Y h:i a"); // displays: Sun 26th Feb, 2012 04:46 am
Read the list above and you'll find that 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.
The date function is not only tied to displaying the local date/time on the server. You can also
pass it a timestamp (often called 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:
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:
echo date("The time is H:i");
you'd get something like the unexpected result of UTC04UTC 294602UTC 4640 04:46.
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.
You can easily fix it escaping the characters with a backslash, as follows:
echo date("\T\h\e \\t\i\m\e \i\s H:i");
which displays what we'd originally hoped for The time is 04:46.
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!
A cookie, also known as a web cookie, browser cookie and HTTP cookie, is a piece of text stored by a user's web
browser. A cookie can be used for authentication, storing site preferences, shopping cart contents, the
identifier for a server-based session, or anything else that can be accomplished through storing text data.
PHP makes it easy to set and read cookies and provides all the features needed to give their details.
The PHP function for setting cookies is setcookie.
The most basic information for a cookie are his name and value. The name of the cookie must be something by which you can refer to it later. You don't need to worry about it clashing with other sites as cookie names are domain specific, but you should always try to 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:
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.
PHP makes it extremely simple to read the value of a cookie.
Reading form values are achieved using the global variables $_GET and $_POST and
has a similar global variable for cookies:
$_COOKIE["cookie_name"];
This variable contains the value of the cookie with name "cookie_name". So on your website, if you want to display the name of the user, you could simply use the following:
echo 'Hello, ' . $_COOKIE["nameOfUser"] . '! Welcome back!';
Of course, the user may not yet have the cookie, so you should use the PHP function isset.
This function returns true if a variable has been set and false if not. Using this,
your site could do the following:
if (isset($_COOKIE["nameOfUser"])) {
echo 'Hello, ' . $_COOKIE["nameOfUser"] . '! Welcome back!';
} else {
setcookie("nameOfUser", $name);
}
Although the code above 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.
// Set an expire date
setcookie("nameOfUser", $name, time() + 3600);
This code takes the current time (time function), then adds 3600 seconds to it, and uses the
retuned value 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 that can be used when setting cookies:
subfolder directory and subdirectories). You can
set this to any part of your site, which can be useful in some situations.
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 with
.example.com will be accepted (e.g. mail.example.com).
Take, for instance, the following settings:
// Cookie with all settings set
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 since .example.com has
been used 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.
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.
// Delete cookie
setcookie("nameOfUser", "", time() - 3600);
Whenever you want to create a website that allows you to store and display information about a user, determine which user's group a person belongs to, use permissions on your website or you just want to do something cool, sessions are vital.
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 computers 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.
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.
echo "Look at this nasty error below:<br/>"; session_start();
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.
session_start(); echo "Now it works!";
Let's say that we had an input form from a page that asks the user his 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.
<form action="register.php" method="post">
<p>Enter your Name: <input type="text" name="name"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
As you can see there is absolutely nothing cosmic about that form. It is only a HTML page
form.html that will post to the PHP script register.php:
<?php
// start the session
session_start();
// Get the user's input from the form
$name = $_POST["name"];
// Register session key with the value
$_SESSION["name"] = $name; // Even simpler: do $_SESSION["name"] = $_POST["name"];
// Display the session information:
?>
<h1>Step 2 - Register session</h1>
<p>Welcome <em><?php echo $_SESSION["name"]; ?></em>!</p>
<p>Let's see what happens on the <a href="testSession.php">next page</a>.</p>
The important element in the above codeblock is the use of the global variable $_SESSION["name"]
and that's about it. The rest is just standard HTML and PHP.
If everything worked properly and you typed Bob on the form on the first page, you'll get the
following output:
Welcome Bob!
Let's see what happens on the next page.
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.
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 since 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.
<?php
// start the session
session_start();
?>
<h1>Step 3 - Test Session</h1>
<p>Hey <em><?php echo $_SESSION["name"]; ?></em>. Everything is still working!</p>
<p>Pick an option:</p>
<ul>
<li><a href="delete.php">Delete</a> the session variable now!</li>
<li><a href="destroy.php">Destroy</a> the session!</li>
</ul>
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.
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.
<?php
// start the session
session_start();
$_SESSION["name"] = false; // same as $_SESSION["name"] = ""; or $_SESSION["name"] = null;
echo "<h1>Unregister session variable</h1>";
if ($_SESSION["name"]) {
echo "<p>The session is still registered.</p>";
} else {
echo "<p>Ok! The session is no longer registered!</p>";
echo "<p><a href=\"form.html\">Go back to the beginning!</a></p>";
}
?>
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.
<?php
// start the session
session_start();
// destroy the session
$_SESSION = array();
session_destroy();
echo "<h1>Destroy the session</h1>";
if ($_SESSION["name"]) {
echo "<p>The session is still active.</p>";
} else {
echo "<p>Ok! The session is no longer active!</p>";
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.
What we're about to do is start our 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.
<?php
// start the session
session_start();
if (!$_SESSION["count"]) {
$_SESSION["count"] = 1;
} else {
$_SESSION["count"]++;
}
?>
<p>You have visited <?php echo $_SESSION["count"]; ?> pages so far!</p>
<p><a href="increment.php">Increment</a> your counter!</p>
<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 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.
<?php
// start the session
session_start();
$_SESSION["count"] = 1;
?>
<p>You have visited <?php echo $_SESSION["count"]; ?> pages so far!</p>
<p><a href="increment.php">Increment</a> your counter!</p>
<p><a href="reset.php">Reset</a> your counter!</p>
This script is very useful to view which information is actually being stored in your user's sessions.
<?php
session_start();
echo "<p>Sessions list:</p>";
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
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
)
The function session_id allows you to display the current Session ID or use it
however you need.
<?php
session_start();
echo "<p>Your <strong>Session ID</strong> is '<code>" . session_id() . "</code>'.</p>";
?>
Your Session ID is 'il5277WKtGjAAAATW3+2Vk'.
Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading and editing files.
fopen function is used to open files in PHP.
The first parameter of this function contains the path of the file to be opened and the second parameter specifies in which mode the file should be opened in.
<?php
$file = fopen("file.txt", "r");
?>
<?php
if (!($file = fopen("file.txt", "r"))) {
exit("Unable to open file!");
}
?>
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.
|
fclose function is used to close a file.
<?php
fclose($file);
?>
feof function is used to determine if the end of file is true.
<?php
if (feof($file)) {
echo "End of file!";
}
?>
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.
<?php
if (!($file = fopen("file.txt", "r"))) {
exit("Unable to open file!");
}
while (!feof($file)) {
$x = fgetc($file);
echo $x;
}
fclose($file);
?>
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 URLs 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 the PHP script below. The unlink
function just needs to know the name of the file to start working its destructive magic.
<?php
unlink("file.txt");
?>
A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.
Before you can use PHP to manage your uploads, you must first build a HTML form
(uploadForm.html) that lets the user select a file to upload.
<form action="uploader.php" method="post" enctype="multipart/form-data">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="100000"/>
Choose a file to upload: <input type="file" name="uploadedFile"/>
</p>
<p><input type="submit" value="Upload file"/></p>
</form>
Here is a brief description of the important parts of the above code:
| Element | Description |
|---|---|
| <form action="uploader.php" method="post" enctype="multipart/form-data"> |
|
| <input type="hidden" name="MAX_FILE_SIZE" value="100000"/> |
Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will need a solid backup solution in PHP. We have set the max file size to 100KB in this example. |
| <input type="file" name="uploadedFile"/> |
Field containing file data.uploadedFile Will be the name by which we will access the file data in our PHP script.
|
When the user clicks the submit button, the data will be posted to the server and the user will be
redirected to uploader.php. This PHP file is going to do all the work.
When the uploader.php file is reached, the uploaded file exists in a temporary
storage on the server. If the file is not moved to a different location it will be destroyed!
To save our precious file we are going to need to make use of the $_FILES associative array.
The $_FILES array is where PHP stores all the information about files. There are two elements of
this array that we will need to understand:
| Property | Description |
|---|---|
| $_FILES["uploadedFile"]["name"] | The name property contains the original path of the user uploaded file. |
| $_FILES["uploadedFile"]["tmp_name"] |
The tmp_name property contains the path to the temporary file that resides on the
server. The file should exist on the server in a temporary directory with a temporary name.
|
Now we can finally start to write a basic PHP upload manager script! Here is how we would get the temporary file name, choose a permanent name, and choose a place to store the file:
// Where the file is going to be placed $targetPath = "uploads/"; // Add the original filename to our target path $target_path = $target_path . basename($_FILES["uploadedFile"]["name"]); $_FILES["uploadedFile"]["tmp_name"]; // This is how we will get the temporary file
Now all we have to do is call the move_uploaded_file function and let PHP do its magic. The
move_uploaded_file function needs to know:
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES["uploadedFile"]["name"]);
if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_path)) {
echo "The file " . basename($_FILES["uploadedFile"]["name"]) . " has been uploaded!";
} else {
echo "There was an error uploading the file, please try again!";
}