Saturday, March 27, 2010

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.

I will show different error handling methods:
  • Simple "die()" statements.
  • Custom errors and error triggers.
  • Error reporting.


Basic Error Handling: Using the die() function



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:\webfolder\test.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

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

Syntax: error_function(error_level,error_message, error_file,error_line,error_context)




Error Report levels

These error report levels are the different types of error the user-defined error handler can be used for:



Now lets create a function to handle errors:



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.


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.

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. For instances:



############################################################
The Output:

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. For instances:



############################################################
The Output:

Notice
: Value must be 1 or below in C:\webfolder\test.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.
The following 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:



############################################################
The Output:

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



############################################################
The Output:

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



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?

############################################################
someone@example.com%0ACc:person2@example.com %0ABcc:person3@example.com,person3@example.com, anotherperson4@example.com,person5@example.com %0ABTo:person6@example.com
##########
##################################################

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:





In the code above we use PHP filters to validate input:
  • The FILTER_SANITIZE_EMAIL filter removes all illegal e-mail characters from a string.
  • The FILTER_VALIDATE_EMAIL filter validates value as an e-mail address.

PHP - Sending E-mails


PHP mail() Function


Syntax:
mail(to,subject,message,headers,parameters)



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


PHP Simple E-mail

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



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.
*NOTE: This is the simplest way to send e-mail, but it is not secure. In the next chapter of this tutorial you can read more about vulnerabilities in e-mail scripts, and how to validate user input to make it more secure.

Sunday, March 21, 2010

PHP - Sessions

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

Starting a PHP Session

*NOTE:
The session_start() function must appear BEFORE the html tag:



Storing a Session Variable


############################################################
The 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:



Destroying a Session

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:


Or you can also COMPLETELY destroy the session by calling the session_destroy() function:


*NOTE:
session_destroy() will reset your session and you will lose all your stored session data.

PHP - Cookies

----------------------------------------------------------------------------------------------------------------------------------
Often used to identify a user.
----------
------------------------------------------------------------------------------------------------------------------------

What is a Cookie??

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.


Create a Cookie

The setcookie() function is used to set a cookie.

*NOTE:
The setcookie() function must appear BEFORE the tag.

setcookie(name, value, expire, path, domain);

Example 1:

In the example below, we will create a cookie named "user" and assign the value "Abdul Razzaq" 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).

Example 2:

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.


In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).


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:


In the following example we use the isset() function to find out if a cookie has been set:



How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past. For instances:



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

PHP - File Upload

----------------------------------------------------------------------------------------------------------------------------------
With PHP, it is possible to upload files to the server.
----------
------------------------------------------------------------------------------------------------------------------------

Create an Upload-File Form

The following HTML form is the example for uploading files:



Notice the following about the HTML form above:
  • The enctype attribute of the tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded.
  • The type="file" attribute of the input 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


By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:
  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload
This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.


Restrictions on Upload

In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 50 kb:


*NOTE: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg.


Saving the Uploaded File

The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server.

The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location:


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


The file may be opened in one of the following modes:


*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:



Closing a File

The fclose() function is used to close an open file:



Check End-of-file (EOF)

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. For instances:



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. For instances: