The PHP date() function is used to format a time or a date.
The PHP Date() Function
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
Parameter
Description
format
Required. Specifies
the format of the timestamp
timestamp
Optional. Specifies a timestamp. Default is the current
date and time (as a timestamp)
PHP Date - What is a Timestamp?
A timestamp is the number of seconds since January 1, 1970 at 00:00:00 GMT.
This is also known as the Unix Timestamp.
PHP Date - Format the Date
The first parameter in the date() function specifies how to format the
date/time. It uses letters to represent date and time formats. Here are some of
the letters that can be used:
d - The day of the month (01-31)
m - The current month, as a number (01-12)
Y - The current year in four digits
An overview of all the letters that can be used in the format parameter, can
be found in our PHP Date reference.
Other characters, like"/", ".", or "-" can also be inserted between the
letters to add additional formatting:
The output of the code above could be something like this:
2006/07/11
2006.07.11
2006-07-11
PHP Date - Adding a Timestamp
The second parameter in the date() function specifies a timestamp. This
parameter is optional. If you do not supply a timestamp, the
current time will be used.
In our next example we will use the mktime() function to create a timestamp for tomorrow.
The mktime() function returns the Unix timestamp for a specified date.
Syntax
mktime(hour,minute,second,month,day,year,is_dst)
To go
one day in the future we simply add one to the day argument of mktime():
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>
The output of the code above could be something like this:
Tomorrow is 2006/07/12
PHP Include File
Server Side Includes (SSI) are used to create functions, headers,
footers, or elements that will be reused on multiple pages.
Server Side Includes
You can insert the content of a file into a PHP file before the server
executes it, with the include() or require() function. The two functions are
identical in every way, except how they handle errors. The include() function
generates a warning (but the script will continue execution) while the require()
function generates a fatal error (and the script execution will stop after the
error).
These two functions are used to
create functions, headers, footers, or elements that can be reused on multiple
pages.
This can save the developer a considerable amount of time. This means that
you can create a standard header or menu file that you want all your web pages
to include. When the header needs to be updated, you can only
update this one include file, or when you add a new page to your site, you can simply change the
menu file (instead of updating the links on all web pages).
The include() Function
The include() function takes all the text in a specified file and copies it
into the file that uses the include function.
Example 1
Assume that you have a standard header file, called "header.php". To include
the header file in a page, use the include() function, like this:
Welcome to my home page
Some text
Example 2
Now, let's assume we have a standard menu file that should be used on all
pages (include files usually have a ".php"
extension). Look at the "menu.php" file below:
And, of course, we would have to do the same thing for "about.php" and "contact.php".
By using include files, you simply have to update the text in the "menu.php"
file if you decide to rename or change the order of the links or add another web page to the site.
The require() Function
The require() function is identical to include(), except that it handles
errors differently.
The include() function generates a warning (but the script will continue
execution) while the require() function generates a fatal error (and the script
execution will stop after the error).
If you include a file with the include() function and an error occurs, you
might get an error message like the one below.
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:homewebsitetest.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:php5pear')
in C:homewebsitetest.php on line 5
The echo statement was not executed because the script execution stopped
after the fatal error.
It is recommended to use the require() function instead of include(), because
scripts should not continue executing if files are missing or misnamed.
PHP File Handling
The fopen() function is used to open files in PHP.
Opening a File
The 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:
<?php
$file=fopen("welcome.txt","r");
?>
The file may be opened in one of the following modes:
Modes
Description
r
Read only. Starts at the beginning of the file
r+
Read/Write. Starts at the beginning of the file
w
Write only. Opens and clears the contents of file; or creates a new file
if it doesn't exist
w+
Read/Write. Opens and clears the contents of file; or creates a new file
if it doesn't exist
a
Append. Opens and writes to the end of the file or creates a new file if
it doesn't exist
a+
Read/Append. Preserves file content by writing to the end of the file
x
Write only. Creates a new file. Returns FALSE and an error if file
already exists
x+
Read/Write. Creates a new file. Returns FALSE and an error if file
already exists
Note: If the fopen() function is unable to open the
specified file, it returns 0 (false).
Example
The following example generates a message if the fopen() function is unable
to open the specified file:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
Note: You cannot read from files opened in w, a, and x mode!
if (feof($file)) echo "End of file";
Reading a File Line by Line
The fgets() function is used to read a single line from a file.
Note: After a call to this function the file pointer has moved to the next
line.
Example
The example below reads a file line by line, until the end of
file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). " ";
}
fclose($file);
?>
Reading a File Character by Character
The fgetc() function is used to read a single character from a file.
Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of
file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
PHP File Upload
With PHP, it is possible to upload files to the server.
Create an Upload-File Form
To allow users to upload files from a form can be very useful.
Look at the following HTML form for uploading files:
enctype="multipart/form-data">
Notice the following about the HTML form above:
The enctype attribute of the
The type="file" attribute of the tag specifies that the input should
be processed as a file. For example, when viewed in a browser, there will be
a browse-button next to the input field
Note: Allowing users to upload files is a big security risk. Only permit
trusted users
to perform file uploads.
Create The Upload Script
The "upload_file.php" file contains the code for uploading a file:
The script above checks if the file already exists, if it does not, it copies the file to the specified folder.
Note: This example saves the file to a new folder called "upload"
PHP Cookies
A cookie is often used to identify a user.
What is a Cookie?
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.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the tag.
Syntax
setcookie(name, value, expire, path, domain);
Example
In the example below, we will create a cookie named "user" and assign the
value "Alex Porter" to it. We also specify that the cookie should expire after
one hour:
Note: The value of the cookie is automatically URLencoded when
sending the cookie, and automatically decoded when received (to prevent
URLencoding, use setrawcookie() instead).
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to
retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "user" and
display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
In the following example we use the isset() function to find out if a cookie
has been set:
When deleting a cookie you should assure that the expiration date is in the
past.
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
What if a Browser Does NOT Support Cookies?
If your application deals with browsers that do not support cookies, you will
have to use other methods to pass information from one page to another in your
application. One method is to pass the data through forms (forms and user input are described
earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user clicks on
the "Submit" button:
Retrieve the values in the "welcome.php" file like this:
Welcome .
You are years old.
PHP Sessions
A PHP session variable is used to store information about, or
change settings for a user session. Session variables hold information about one
single user, and are available to all pages in one application.
PHP Session Variables
When you are working 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 and what you do
because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information
on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and
will be deleted after
the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each
visitor and store variables based on this UID. The UID is either stored in a
cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must
first start up the session.
Note: The session_start() function must appear BEFORE the tag:
The code above will register the user's session with the server, allow you to
start saving user information, and assign a UID
for that user's session.
Storing a Session Variable
The correct way to store and retrieve session variables is to use the
PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset()
function checks if the "views" variable has already been set. If "views" has
been set, we
can increment our counter. If "views" doesn't exist, we create a "views"
variable,
and set it to 1:
If you wish to delete some session data, you can use the unset() or the
session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all
your stored session data.
PHP Sending E-mails
PHP allows you to send e-mails directly from a script.
The PHP mail() Function
The PHP mail() function is used to send emails from inside a script.
Syntax
mail(to,subject,message,headers,parameters)
Parameter
Description
to
Required. Specifies
the receiver / receivers of the email
subject
Required. Specifies
the subject of the email. Note: This parameter cannot contain any newline
characters
message
Required. Defines the message to be sent. Each line should
be separated with a LF (n). Lines should not exceed 70 characters
headers
Optional. Specifies additional headers, like From, Cc, and
Bcc. The additional headers should be separated with a CRLF (rn)
parameters
Optional. Specifies an additional parameter to the sendmail program
Note: For the mail functions to be available, PHP requires an installed
and working email system. The program to be used is defined by the configuration
settings in the php.ini file. Read more in our PHP
Mail reference.
PHP Simple E-Mail
The simplest way to send an email with PHP is to send a text email.
In the example below we first declare the variables ($to, $subject, $message,
$from, $headers), then we use the variables in the mail() function to send an e-mail:
<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
PHP Mail Form
With PHP, you can create a feedback-form on your website. The example below
sends a text message to a specified e-mail address:
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "
";
}
?>
This is how the example above works:
First, check if the email input field is filled out
If it is not set (like when the page is
first visited); output the HTML form
If it is set (after the form is filled out);
send the email from the form
When submit is pressed after the form is filled out, the page reloads,
sees that the email input is set, and sends the email
PHP Mail Reference
For more information about the PHP mail() function, visit our
PHP Mail Reference.
PHP Secure E-mails
There is a weakness in the PHP e-mail script in the previous
chapter.
PHP E-mail Injections
First, look at the PHP code from the previous chapter:
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "
";
}
?>
The problem with the code above is that unauthorized users can insert data into the
mail headers via the input form.
What happens if the user adds the following text to the email input field in
the form?
The mail() function puts the text above into the mail headers as usual, and now the
header has an extra Cc:, Bcc:, and To: field. When the user clicks the submit
button, the e-mail will be sent to all of the addresses above!
PHP Stopping E-mail Injections
The best way to stop e-mail injections is to validate the input.
The code below is the same as in the previous chapter, but now we have added an input validator
that checks the email field in the form:
<?php
function spamcheck($field)
{
//eregi() performs a case insensitive regular expression match
if(eregi("to:",$field) || eregi("cc:",$field))
{
return TRUE;
}
else
{
return FALSE;
}
}
//if "email" is filled out, send email
if (isset($_REQUEST['email']))
{
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==TRUE)
{
echo "Invalid input";
}
else
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
}
else
//if "email" is not filled out, display the form
{
echo "
";
}
?>
PHP Error Handling
The default error handling in PHP is very simple. An error message with filename, line
number and a message describing the error is sent to the browser.
PHP Error Handling
When creating scripts and web applications, error handling is an important
part. If your code lacks error checking code, your program may look very
unprofessional and you may be open to security risks.
This tutorial contains some
of the most common error checking methods in PHP.
We will show different error handling methods:
Simple "die()" statements
Custom errors and error triggers
Error reporting
Basic Error Handling: Using the die() function
The first example shows a simple script that opens a text file:
<?php
$file=fopen("welcome.txt","r");
?>
If the file does not exist you might get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:webfoldertest.php on line 2
To avoid that the user gets an error message like the one above, we test if
the file exist before we try to access it:
Now if the file does not exist you get an error like this:
File not found
The code above is more efficient than the earlier code, because it
uses a simple error handling mechanism to stop the script after the error.
However, simply stopping the script is not always the right way to go. Let's take a
look at alternative PHP functions for handling errors.
Creating a Custom Error Handler
Creating a custom error handler is quite simple. We simply create a special
function that can be called when an error occurs in PHP.
This function must be able to handle a minimum of two parameters (error
level and error message) but can accept up to five parameters (optionally: file,
line-number, and the error context):
The code above is a simple error handling function. When it is triggered, it
gets the error level and an error message. It then outputs the error level and
message and terminates the script.
Now that we have created an error handling function we need to decide when it
should be triggered.
Set Error Handler
The default error handler for PHP is the built in error handler. We are
going to make the function above the default error handler for the duration of
the script.
It is possible to change the error handler to apply for only some errors,
that way the script can handle different errors in different ways. However, in
this example we are going to use our custom error handler for all errors:
set_error_handler("customError");
Since we want our custom function to handle all errors, the set_error_handler()
only needed one parameter, a second parameter could be added to specify an error
level.
Example
Testing the error handler by trying to output variable that does not exist:
<?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr";
}
The output of the code above should be something like this:
Custom error: [8] Undefined variable: test
Trigger an Error
In a script where users can input data it is useful to trigger errors when an
illegal input occurs. In PHP, this is done by the trigger_error() function.
Example
In this example an error occurs if the "test" variable is bigger than "1":
<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>
The output of the code above should be something like this:
Notice: Value must be 1 or below
in C:webfoldertest.php on line 6
An error can be triggered anywhere you wish in a script, and by adding a
second parameter, you can specify what error level is triggered.
Possible error types:
E_USER_ERROR - Fatal user-generated run-time error. Errors that can not
be recovered from. Execution of the script is halted
E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of
the script is not halted
E_USER_NOTICE - Default. User-generated run-time notice. The script
found something that might be an error, but could also happen when running a
script normally
Example
In this example an E_USER_WARNING occurs if the "test" variable is bigger
than "1". If an E_USER_WARNING occurs we will use our custom error handler
and end the script:
<?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr ";
echo "Ending Script";
die();
}
//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
The output of the code above should be something like this:
Error: [512] Value must be 1 or below
Ending Script
Now that we have learned to create our own errors and how to trigger them,
lets take a look at error logging.
Error Logging
By default, PHP sends an error log to the servers logging system or a file,
depending on how the error_log configuration is set in the php.ini file. By
using the error_log() function you can send error logs to a specified file or a
remote destination.
Sending errors messages to yourself by e-mail can be a good way of getting
notified of specific errors.
Send an Error Message by E-Mail
In the example below we will send an e-mail with an error message and end the
script, if a specific error occurs:
<?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr ";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");
}
//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
The output of the code above should be something like this:
Error: [512] Value must be 1 or below
Webmaster has been notified
And the mail received from the code above looks like this:
Error: [512] Value must be 1 or below
This should not be used with all errors. Regular errors should be logged on
the server using the default PHP logging system.
PHP Exception Handling
Exceptions are used to change the normal flow of a script if a
specified error occurs
What is an Exception
With PHP 5 came a new object oriented way of dealing with errors.
Exception handling is used to change the normal flow of the code execution if
a specified error (exceptional) condition occurs. This condition is called an
exception.
This is what normally happens when an exception is triggered:
The current code state is saved
The code execution will switch to a predefined (custom) exception
handler function
Depending on the situation, the handler may then resume the execution
from the saved code state, terminate the script execution or continue the
script from a different location in the code
We will show different error handling methods:
Basic use of Exceptions
Creating a custom exception handler
Multiple exceptions
Re-throwing an exception
Setting a top level exception handler
Note: Exceptions should only be used with error conditions, and should not be used
to jump to another place in the code at a specified point.
Basic Use of Exceptions
When an exception is thrown, the code following it will not be executed, and
PHP will try to find the matching "catch" block.
If an exception is not caught, a fatal error will be issued with an "Uncaught
Exception" message.
Lets try to throw an exception without catching it:
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
The code above will get an error like this:
Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:webfoldertest.php:6
Stack trace: #0 C:webfoldertest.php(12):
checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6
Try, throw and catch
To avoid the error from the example above, we need to create the proper code
to handle an exception.
Proper exception code should include:
Try - A function using an exception should be in a "try" block. If the
exception does not trigger, the code will continue as normal. However if the
exception triggers, an exception is "thrown"
Throw - This is how you trigger an exception. Each "throw" must have at
least one "catch"
Catch - A "catch" block retrieves an exception and creates an object
containing the exception information
Lets try to trigger an exception with valid code:
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
The code above throws an exception and catches it:
The checkNum() function is created. It checks if a number is greater
than 1. If it is, an exception is thrown
The checkNum() function is called in a "try" block
The exception within the checkNum() function is thrown
The "catch" block retrives the exception and creates an object ($e)
containing the exception information
The error message from the exception is echoed by calling $e->getMessage()
from the exception object
However, one way to get around the "every throw must have a catch" rule is to
set a top level exception handler to errors that slip trough.
Creating a Custom Exception Class
Creating a custom exception handler is quite simple. We simply create a special
class with functions that can be called when an exception occurs in PHP. The
class must be an extension of the exception class.
The custom exception class inherits the properties from PHP's
exception class and you can add custom functions to it.
Lets create an exception class:
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': '.$this->getMessage().' is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example...com";
try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
}
The new class is a copy of the old exception class with an addition of the
errorMessage() function. Since it is a copy of the old class, and it inherits
the properties and methods from the old class, we can use the exception class
methods like getLine() and getFile() and getMessage().
Example explained:
The code above throws an exception and catches it with a custom exception
class:
The customException() class is created as an extension of the old
exception class. This way it inherits all methods and properties from the
old exception class
The errorMessage() function is created. This function returns an error
message if an e-mail address is invalid
The $email variable is set to a string that is not a valid e-mail
address
The "try" block is executed and an exception is thrown since
the e-mail address is invalid
The "catch" block catches the exception and displays the error message
Multiple Exceptions
It is possible for a script to use multiple exceptions to check for multiple
conditions.
It is possible to use several if..else blocks, a switch, or nest multiple
exceptions. These exceptions can use different exception classes and return
different error messages:
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': '.$this->getMessage().' is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example.com";
try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
throw new Exception("$email is an example e-mail");
}
}
The code above tests two conditions and throws an exception if any of the
conditions are not met:
The customException() class is created as an extension of the old
exception class. This way it inherits all methods and properties from the
old exception class
The errorMessage() function is created. This function returns an error
message if an e-mail address is invalid
The $email variable is set to a string that is a valid e-mail
address, but contains the string "example"
The "try" block is executed and an exception is not thrown on
the first condition
The second condition triggers an exception since the e-mail contains the
string "example"
The "catch" block catches the exception and displays the
correct error message
If there was no customException catch, only the base exception catch, the
exception would be handled there
Re-throwing Exceptions
Sometimes, when an exception is thrown, you may wish to handle it
differently than the standard way. It is possible to throw an exception a second
time within a "catch" block.
A script should hide system errors from users. System errors may be important
for the coder, but is of no intrest to the user. To make things easier for the
user you can re-throw the exception with a user friendly message:
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.';
return $errorMsg;
}
}
$email = "someone@example.com";
try
{
try
{
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
//throw exception if email is not valid
throw new Exception($email);
}
}
catch(Exception $e)
{
//re-throw exception
throw new customException($email);
}
}