PHP Form Handling
PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.
<html>
<body>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.
To display the submitted data you could simply echo all the variables.
<html>
<body>
</body>
</html>
Output
Welcome John
Your email address is [email protected]
GET METHOD
<html>
<body>
WELCOME.PHP
<html>
<body>
</body>
</html>
* required field
Name: *
E-mail: *
Website:
Comment:
Your Input:
Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea.
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
When the form is submitted, the form data is sent with method="post".
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.
Error reporting
The first example shows a simple script that opens a text file:
<?php
$file=fopen("mytestfile.txt","r");
?>
If the file does not exist you might get an error like this:
Now if the file does not exist you get an error like this:
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.
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):
Syntax
error_function(error_level,error_message,
error_file,error_line,error_context)
Parameter Description
Required. Specifies the error report level for the user-defined error. Must be
error_level
a value number. See table below for possible error report levels
error_message Required. Specifies the error message for the user-defined error
error_line Optional. Specifies the line number in which the error occurred
These error report levels are the different types of error the user-defined error handler can be
used for:
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.
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
<?php
//error handler function
function customError($errno, $errstr) {
echo"<b>Error:</b> [$errno] $errstr";
}
//trigger error
echo($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");
}
?>
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.
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"<b>Error:</b> [$errno] $errstr<br>";
echo"Ending Script";
die();
}
//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Error Logging
By default, PHP sends an error log to the server's 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 error messages to yourself by e-mail can be a good way of getting notified of specific
errors.
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"<b>Error:</b> [$errno] $errstr<br>";
echo"Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"[email protected]","From: [email protected]");
}
//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
And the mail received from the code above looks like this:
This should not be used with all errors. Regular errors should be logged on the server using the
default PHP logging system.
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:
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
Multiple exceptions
Re-throwing an exception
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.
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
thrownew Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
To avoid the error from the example above, we need to create the proper code to handle an
exception.
1. 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"
2. throw - This is how you trigger an exception. Each "throw" must have at least one
"catch"
3. catch - A "catch" block retrieves an exception and creates an object containing the
exception information
4. <?php
//create function with an exception
function checkNum($number) {
if($number>1) {
thrownew Exception("Value must be 1 or below");
}
return true;
}
//catch exception
catch(Exception $e) {
echo'Message: ' .$e->getMessage();
}
?>
The code above will get an error like this:
Message: Value must be 1 or below
However, one way to get around the "every throw must have a catch" rule is to set a top level
exception handler to handle errors that slip through.
To create a custom exception handler you must 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.
<?php
class customException extends Exception {
publicfunction errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "[email protected]";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
thrownew 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:
1. 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
2. The errorMessage() function is created. This function returns an error message if an e-
mail address is invalid
3. The $email variable is set to a string that is not a valid e-mail address
4. The "try" block is executed and an exception is thrown since the e-mail address is invalid
5. 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 {
publicfunction errorMessage(){
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "[email protected]";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
thrownew customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE) {
thrownew Exception("$email is an example e-mail");
}
}
catch (customException $e) {
echo $e->errorMessage();
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Example explained:
The code above tests two conditions and throws an exception if any of the conditions are not
met:
1. 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
2. The errorMessage() function is created. This function returns an error message if an e-
mail address is invalid
3. The $email variable is set to a string that is a valid e-mail address, but contains the string
"example"
4. The "try" block is executed and an exception is not thrown on the first condition
5. The second condition triggers an exception since the e-mail contains the string
"example"
6. The "catch" block catches the exception and displays the correct error message
If the exception thrown was of the class custom Exception and there were no custom Exception
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
are of no interest 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 {
publicfunction errorMessage() {
//error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.';
return $errorMsg;
}
}
$email = "[email protected]";
try {
try {
//check for "example" in mail address
if(strpos($email, "example") !== FALSE) {
//throw exception if email is not valid
thrownew Exception($email);
}
}
catch(Exception $e) {
//re-throw exception
thrownew customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage();
}
?>
Example explained:
The code above tests if the email-address contains the string "example" in it, if it does, the
exception is re-thrown:
1. 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
2. The errorMessage() function is created. This function returns an error message if an e-
mail address is invalid
3. The $email variable is set to a string that is a valid e-mail address, but contains the string
"example"
4. The "try" block contains another "try" block to make it possible to re-throw the
exception
5. The exception is triggered since the e-mail contains the string "example"
If the exception is not caught in its current "try" block, it will search for a catch block on "higher
levels".
<?php
function myException($exception){
echo"<b>Exception:</b>" . $exception->getMessage();
}
set_exception_handler('myException');
thrownew Exception('Uncaught Exception occurred');
?>
In the code above there was no "catch" block. Instead, the top level exception handler triggered.
This function should be used to catch uncaught exceptions.
Rules for exceptions
Code may be surrounded in a try block, to help catch potential exceptions
Each try block or "throw" must have at least one corresponding catch block
Exceptions can be thrown (or re-thrown) in a catch block within a try block