Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
14 views21 pages

Chapter 2-Handling User Input

Chapter Two discusses handling user input in PHP, focusing on methods like GET and POST for sending data to servers, along with their advantages and disadvantages. It also covers sending emails using the PHP mail() function, creating and processing contact forms, and the importance of sanitizing and validating user inputs to enhance security. The chapter provides practical examples and code snippets for implementing these concepts in web applications.

Uploaded by

Nati Yacob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views21 pages

Chapter 2-Handling User Input

Chapter Two discusses handling user input in PHP, focusing on methods like GET and POST for sending data to servers, along with their advantages and disadvantages. It also covers sending emails using the PHP mail() function, creating and processing contact forms, and the importance of sanitizing and validating user inputs to enhance security. The chapter provides practical examples and code snippets for implementing these concepts in web applications.

Uploaded by

Nati Yacob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Yibeltal T.

CHAPTER TWO: HANDLING USER INPUT

This chapter covers the following concepts, including:

 PHP GET and POST


 PHP Send Email
 PHP Form Handling
 PHP Form Validation
 PHP Regular Expressions
 PHP Filters
 PHP Error Handling

PHP GET and POST

Methods of Sending Information to Server

A web browser communicates with the server typically using one of the two HTTP (Hypertext Transfer
Protocol) methods — GET and POST. Both methods pass the information differently and have different
advantages and disadvantages, as described below.

The GET Method

In GET method the data is sent as URL parameters that are usually strings of name and value pairs
separated by ampersands (&). In general, a URL with GET data will look like this:

http://www.example.com/action.php?name=john&age=24

The bold parts in the URL are the GET parameters and the italic parts are the value of those parameters.
More than one parameter=value can be embedded in the URL by concatenating with ampersands (&).
One can only send simple text data via GET method.

Advantages and Disadvantages of Using the GET Method

 Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the
page with specific query string values.
 The GET method is not suitable for passing sensitive information such as the username and
password, because these are fully visible in the URL query string as well as potentially stored in
the client browser's memory as a visited page.
 Because the GET method assigns data to a server environment variable, the length of the URL is
limited. So, there is a limitation for the total data to be sent.

PHP provides the superglobal variable $_GET to access all the information sent either through the URL or
submitted through an HTML form using the method="get".

<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP GET method</title>
</head>
<body>
<?php

1
if(isset($_GET["name"])){
echo "<p>Hi, " . $_GET["name"] . "</p>";
}
?>
<form method="get" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>

The POST Method

In POST method the data is sent to the server as a package in a separate communication with the
processing script. Data sent through POST method will not visible in the URL.

Advantages and Disadvantages of Using the POST Method

 It is more secure than GET because user-entered information is never visible in the URL query
string or in the server logs.
 There is a much larger limit on the amount of data that can be passed and one can send text data
as well as binary data (uploading a file) using POST.
 Since the data sent by the POST method is not visible in the URL, so it is not possible to
bookmark the page with specific query.

Like $_GET, PHP provide another superglobal variable $_POST to access all the information sent via post
method or submitted through an HTML form using the method="post".

<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP POST method</title>
</head>
<body>
<?php
if(isset($_POST["name"])){
echo "<p>Hi, " . $_POST["name"] . "</p>";
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>

The $_REQUEST Variable

PHP provides another superglobal variable $_REQUEST that contains the values of both the $_GET and
$_POST variables as well as the values of the $_COOKIE superglobal variable.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP $_REQUEST variable</title>
</head>
<body>
<?php
if(isset($_REQUEST["name"])){
echo "<p>Hi, " . $_REQUEST["name"] . "</p>";

2
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>

Note: The superglobal variables $_GET, $_POST and $_REQUEST are built-in variables that are always
available in all scopes throughout a script.

PHP Send Emails

In this section you will learn how to send simple text or HTML emails directly from the script using the
PHP mail() function. Sending email messages are very common for a web application, for example,
sending welcome email when a user create an account on your website, sending newsletters to your
registered users, or getting user feedback or comment through website's contact form, and so on.

You can use the PHP built-in mail() function for creating and sending email messages to one or more
recipients dynamically from your PHP application either in a plain-text form or formatted HTML. The
basic syntax of this function can be given with:

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

The following table summarizes the parameters of this function.

Parameter Description
Required — The following parameters are required
to The recipient's email address.
subject Subject of the email to be sent. This parameter i.e. the subject line cannot contain any newline
character (\n).
message Defines the message to be sent. Each line should be separated with a line feed-LF (\n). Lines
should not exceed 70 characters.
Optional — The following parameters are optional
headers This is typically used to add extra headers such as "From", "Cc", "Bcc". The additional headers
should be separated with a carriage return plus a line feed-CRLF (\r\n).
parameters Used to pass additional parameters.

Sending Plain Text Emails

The simplest way to send an email with PHP is to send a text email. In the example below we first declare
the variables — recipient's email address, subject line and message body — then we pass these variables
to the mail() function to send the email.

<?php
$to = '[email protected]';
$subject = 'Marriage Proposal';
$message = 'Hi Jane, will you marry me?';
$from = '[email protected]';
// Sending email
if(mail($to, $subject, $message)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
3
Sending HTML Formatted Emails

When you send a text message using PHP, all the content will be treated as simple text. We're going to
improve that output, and make the email into a HTML-formatted email.

To send an HTML email, the process will be the same. However, this time we need to provide additional
headers as well as an HTML formatted message.

<?php
$to = '[email protected]';
$subject = 'Marriage Proposal';
$from = '[email protected]';

// To send HTML mail, the Content-type header must be set


$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Create email headers


$headers .= 'From: '.$from."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();

// Compose a simple HTML email message


$message = '<html><body>';
$message .= '<h1 style="color:#f40;">Hi Jane!</h1>';
$message .= '<p style="color:#080;font-size:18px;">Will you marry me?</p>';
$message .= '</body></html>';

// Sending email
if(mail($to, $subject, $message, $headers)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>

Note: However, the PHP mail() function is a part of the PHP core but you need to set up a mail server
on your machine to make it really work.

In the next two sections (PHP Form Handling and PHP Form Validation) you will learn how to
implement an interactive contact form on your website to receive the user's comment and feedback
through emails using this PHP send mail feature.

PHP Form Handling

In this section you'll learn how to collect user inputs submitted through a form using the PHP superglobal
variables $_GET, $_POST and $_REQUEST.

Creating a Simple Contact Form

In this section we are going to create a simple HMTL contact form that allows users to enter their
comment and feedback then displays it to the browser using PHP.

Open up your favorite code editor and create a new PHP file. Now type the following code and save this
file as "contact-form.php" in the root directory of your project.

<!DOCTYPE html>
<html lang="en">
<head>
4
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="process-form.php" method="post">
<p>
<label for="inputName">Name:<sup>*</sup></label>
<input type="text" name="name" id="inputName">
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text" name="email" id="inputEmail">
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text" name="subject" id="inputSubject">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message" id="inputComment" rows="5" cols="30"></textarea>
</p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

Explanation of code

Notice that there are two attributes within the opening <form> tag:

 The action attribute references a PHP file "process-form.php" that receives the data entered into
the form when user submit it by pressing the submit button.
 The method attribute tells the browser to send the form data through POST method.

Rest of the elements inside the form are basic form controls to receive user inputs.

Capturing Form Data with PHP

To access the value of a particular form field, you can use the following superglobal variables. These
variables are available in all scopes throughout a script.

Superglobal Description
$_GET Contains a list of all the field names and values sent by a form using the get method (i.e.
via the URL parameters).
$_POST Contains a list of all the field names and values sent by a form using the post method (data
will not visible in the URL).
$_REQUEST Contains the values of both the $_GET and $_POST variables as well as the values of the
$_COOKIE superglobal variable.

When a user submit the above contact form through clicking the submit button, the form data is sent to
the "process-form.php" file on the server for processing. It simply captures the information submitted by
the user and displays it to browser.

The PHP code of "process-form.php" file will look something like this:

5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h1>Thank You</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_POST["name"]?></li>
<li><em>Email:</em> <?php echo $_POST["email"]?></li>
<li><em>Subject:</em> <?php echo $_POST["subject"]?></li>
<li><em>Message:</em> <?php echo $_POST["message"]?></li>
</ol>
</body>
</html>

The PHP code above is quite simple. Since the form data is sent through the post method, you can retrieve
the value of a particular form field by passing its name to the $_POST superglobal array, and displays each
field value using echo() statement.

In real world you cannot trust the user inputs; you must implement some sort of validation to filter the
user inputs before using them. In the next chapter you will learn how sanitize and validate this contact
form data and send it through the email using PHP.

PHP Form Validation

In this section you'll learn how to sanitize and validate form data using PHP filters.

Sanitizing and Validating Form Data

As you have seen in the previous section, the process of capturing and displaying the submitted form data
is quite simple. In this section you will learn how to implement a simple contact form on your website
that allows the user to send their comment and feedback through email. We will use the same PHP
mail() function to send the emails.

We are also going to implement some basic security feature like sanitization and validation of the user's
input so that user can not insert potentially harmful data that compromise the website security or might
break the application.

The following is our all-in-one PHP script which does the following things:

 It will ask the users to enter his comments about the website.
 The same script displays the contact form and process the submitted form data.
 The script sanitizes and validates the user inputs. If any required field (marked with *) is missing or
validation failed due to incorrect inputs the script redisplays the form with an error message for
corresponding form field.
 The script remembers which fields the user has already filled in, and prefills those fields when the form
redisplayed due to validation error.
 If the data submitted by the user are acceptable and everything goes well it will send an email to the
website administrator and display a success message to the user.

Type the following code in "contact.php" file and save in your project root directory:

<?php
// Functions to filter user inputs
6
function filterName($field){
// Sanitize user name
$field = filter_var(trim($field), FILTER_SANITIZE_STRING);

// Validate user name


if(filter_var($field, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
return $field;
} else{
return FALSE;
}
}
function filterEmail($field){
// Sanitize e-mail address
$field = filter_var(trim($field), FILTER_SANITIZE_EMAIL);

// Validate e-mail address


if(filter_var($field, FILTER_VALIDATE_EMAIL)){
return $field;
} else{
return FALSE;
}
}
function filterString($field){
// Sanitize string
$field = filter_var(trim($field), FILTER_SANITIZE_STRING);
if(!empty($field)){
return $field;
} else{
return FALSE;
}
}

// Define variables and initialize with empty values


$nameErr = $emailErr = $messageErr = "";
$name = $email = $subject = $message = "";

// Processing form data when form is submitted


if($_SERVER["REQUEST_METHOD"] == "POST"){

// Validate user name


if(empty($_POST["name"])){
$nameErr = "Please enter your name.";
} else{
$name = filterName($_POST["name"]);
if($name == FALSE){
$nameErr = "Please enter a valid name.";
}
}

// Validate email address


if(empty($_POST["email"])){
$emailErr = "Please enter your email address.";
} else{
$email = filterEmail($_POST["email"]);
if($email == FALSE){
$emailErr = "Please enter a valid email address.";
}
}

// Validate message subject


if(empty($_POST["subject"])){
$subject = "";
} else{
$subject = filterString($_POST["subject"]);
}

7
// Validate user comment
if(empty($_POST["message"])){
$messageErr = "Please enter your comment.";
} else{
$message = filterString($_POST["message"]);
if($message == FALSE){
$messageErr = "Please enter a valid comment.";
}
}

// Check input errors before sending email


if(empty($nameErr) && empty($emailErr) && empty($messageErr)){
// Recipient email address
$to = '[email protected]';

// Create email headers


$headers = 'From: '. $email . "\r\n" .
'Reply-To: '. $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();

// Sending email
if(mail($to, $subject, $message, $headers)){
echo '<p class="success">Your message has been sent successfully!</p>';
} else{
echo '<p class="error">Unable to send email. Please try again!</p>';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
<style type="text/css">
.error{ color: red; }
.success{ color: green; }
</style>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="contact.php" method="post">
<p>
<label for="inputName">Name:<sup>*</sup></label>
<input type="text" name="name" id="inputName" value="<?php echo $name; ?
>">
<span class="error"><?php echo $nameErr; ?></span>
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text" name="email" id="inputEmail" value="<?php echo
$email; ?>">
<span class="error"><?php echo $emailErr; ?></span>
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text" name="subject" id="inputSubject" value="<?php echo
$subject; ?>">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message" id="inputComment" rows="5" cols="30"><?php echo
$message; ?></textarea>
<span class="error"><?php echo $messageErr; ?></span>
</p>
<input type="submit" value="Send">

8
<input type="reset" value="Reset">
</form>
</body>
</html>

Explanation of code

You might think what that code was all about. OK, let's get straight into it.

 The filterName() function (line no-03) validate input value as person's name. A valid name can only
contain alphabetical characters (a-z, A-Z).
 The filterEmail() function (line no-14) validate input value as email address.
 The filterString() function (line no-25) only sanitize the input value by stripping HTML tags and
special characters. It doesn't validate the input value against anything.
 The attribute action="contact.php" (line no-111) inside the <form> tag specifies that the same
contact.php file display the form as well as process the form data.
 The PHP code inside the value attribute of <input> and <textarea> e.g. <?php echo $name; ?>
display prefilled value when form is redisplayed upon validation error.
 The PHP code inside the .error class e.g. <span class="error"><?php echo $nameErr;
?></span> display error for corresponding field.

Rest the thing we have already covered in previous chapters. To learn more about sanitize and validate
filters, please check out the PHP Filter reference.

Note: You need to setup a mail server on your machine for the PHP mail() function to work. If you just
want to implement the form validation you can replace the mail part (line no. 81 to 94) with your own
custom code.

PHP Regular Expressions

In this section you will learn how regular expressions work, as well as how to use them to perform pattern
matching in an efficient way in PHP.

What is Regular Expression?

Regular Expressions, commonly known as "regex" or "RegExp", are a specially formatted text strings
used to find patterns in text. Regular expressions are one of the most powerful tools available today for
effective and efficient text processing and manipulations. For example, it can be used to verify whether
the format of data i.e. name, email, phone number, etc. entered by the user was correct or not, find or
replace matching string within text content, and so on.

PHP (version 5.3 and above) supports Perl style regular expressions via its preg_ family of functions.
Why Perl style regular expressions? Because Perl (Practical Extraction and Report Language) was the
first mainstream programming language that provided integrated support for regular expressions and it is
well known for its strong support of regular expressions and its extraordinary text processing and
manipulation capabilities.

Let's begin with a brief overview of the commonly used PHP's built-in pattern-matching functions before
delving deep into the world of regular expressions.

Function What it Does


preg_match() Perform a regular expression match.
preg_match_all() Perform a global regular expression match.
preg_replace() Perform a regular expression search and replace.
9
preg_grep() Returns the elements of the input array that matched the pattern.
preg_split() Splits up a string into substrings using a regular expression.
preg_quote() Quote regular expression characters found within a string.

Note: The PHP preg_match() function stops searching after it finds the first match, whereas the
preg_match_all() function continues searching until the end of the string and find all possible matches
instead of stopping at the first match.

Regular Expression Syntax

Regular expression syntax includes the use of special characters (do not confuse with the HTML special
characters). The characters that are given special meaning within a regular expression, are: . * ? + [ ] ( )
{ } ^ $ | \. You will need to backslash these characters whenever you want to use them literally. For
example, if you want to match ".", you'd have to write \.. All other characters automatically assume their
literal meanings.

The following sections describe the various options available for formulating patterns:

Character Classes

Square brackets surrounding a pattern of characters are called a character class e.g. [abc]. A character
class always matches a single character out of a list of specified characters that means the expression
[abc] matches only a, b or c character.

Negated character classes can also be defined that match any character except those contained within the
brackets. A negated character class is defined by placing a caret ( ^) symbol immediately after the opening
bracket, like this [^abc].

You can also define a range of characters by using the hyphen (-) character inside a character class, like
[0-9]. Let's look at some examples of character classes:

RegExp What it Does


[abc] Matches any one of the characters a, b, or c.
[^abc] Matches any one character other than a, b, or c.
[a-z] Matches any one character from lowercase a to lowercase z.
[A-Z] Matches any one character from uppercase a to uppercase z.
[a-Z] Matches any one character from lowercase a to uppercase Z.
[0-9] Matches a single digit between 0 and 9.
[a-z0-9] Matches a single character between a and z or between 0 and 9.

The following example will show you how to find whether a pattern exists in a string or not using the
regular expression and PHP preg_match() function:

<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
if(preg_match($pattern, $text)){
echo "Match found!";
} else{
echo "Match not found.";
}
?>

Similarly, you can use the preg_match_all() function to find all matches within a string:
10
<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>

Tip: Regular expressions aren't exclusive to PHP. Languages such as Java, Perl, Python, etc. use the same
notation for finding patterns in text.

Predefined Character Classes

Some character classes such as digits, letters, and whitespaces are used so frequently that there are
shortcut names for them. The following table lists those predefined character classes:

Shortcu What it Does


t
. Matches any single character except newline \n.
\d matches any digit character. Same as [0-9]
\D Matches any non-digit character. Same as [^0-9]
\s Matches any whitespace character (space, tab, newline or carriage return character). Same as [ \t\n\
r]
\S Matches any non-whitespace character. Same as [^ \t\n\r]
\w Matches any word character (definned as a to z, A to Z,0 to 9, and the underscore). Same as [a-zA-
Z_0-9]
\W Matches any non-word character. Same as [^a-zA-Z_0-9]

The following example will show you how to find and replace space with a hyphen character in a string
using regular expression and PHP preg_replace() function:

<?php
$pattern = "/\s/";
$replacement = "-";
$text = "Earth revolves around\nthe\tSun";
// Replace spaces, newlines and tabs
echo preg_replace($pattern, $replacement, $text);
echo "<br>";
// Replace only spaces
echo str_replace(" ", "-", $text);
?>

Repetition Quantifiers

In the previous section we've learnt how to match a single character in a variety of fashions. But what if
you want to match on more than one character? For example, let's say you want to find out words
containing one or more instances of the letter p, or words containing at least two p's, and so on. This is
where quantifiers come into play. With quantifiers you can specify how many times a character in a
regular expression should match.

The following table lists the various ways to quantify a particular pattern:

RegExp What it Does


p+ Matches one or more occurrences of the letter p.
p* Matches zero or more occurrences of the letter p.
p? Matches zero or one occurrences of the letter p.
p{2} Matches exactly two occurrences of the letter p.

11
p{2,3} Matches at least two occurrences of the letter p, but not more than three occurrences of the letter p.
p{2,} Matches two or more occurrences of the letter p.
p{,3} Matches at most three occurrences of the letter p

The regular expression in the following example will splits the string at comma, sequence of commas,
whitespace, or combination thereof using the PHP preg_split() function:

<?php
$pattern = "/[\s,]+/";
$text = "My favourite colors are red, green and blue";
$parts = preg_split($pattern, $text);

// Loop through parts array and display substrings


foreach($parts as $part){
echo $part . "<br>";
}
?>

Position Anchors

There are certain situations where you want to match at the beginning or end of a line, word, or string. To
do this you can use anchors. Two common anchors are caret (^) which represent the start of the string,
and the dollar ($) sign which represent the end of the string.

RegEx What it Does


p
^p Matches the letter p at the beginning of a line.
p$ Matches the letter p at the end of a line.

The regular expression in the following example will display only those names from the names array
which start with the letter "J" using the PHP preg_grep() function:

Example

<?php
$pattern = "/^J/";
$names = array("Jhon Carter", "Clark Kent", "John Rambo");
$matches = preg_grep($pattern, $names);
// Loop through matches array and display matched names
foreach($matches as $match){
echo $match . "<br>";}
?>

Pattern Modifiers

A pattern modifier allows you to control the way a pattern match is handled. Pattern modifiers are placed
directly after the regular expression, for example, if you want to search for a pattern in a case-insensitive
manner, you can use the i modifier, like this: /pattern/i. The following table lists some of the most
commonly used pattern modifiers.

Modifier What it Does


i Makes the match case-insensitive manner.
m Changes the behavior of ^ and $ to match against a newline boundary (i.e. start or end of each line
within a multiline string), instead of a string boundary.
g Perform a global match i.e. finds all occurrences.
o Evaluates the expression only once.

12
s Changes the behavior of . (dot) to match all characters, including newlines.
x Allows you to use whitespace and comments within a regular expression for clarity.

The following example will show you how to perform a global case-insensitive search using the i
modifier and the PHP preg_match_all() function.

<?php
$pattern = "/color/i";
$text = "Color red is more visible than color blue in daylight.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>

Similarly, the following example shows how to match at the beginning of every line in a multi-line string
using ^ anchor and m modifier with PHP preg_match_all() function.

<?php
$pattern = "/^color/im";
$text = "Color red is more visible than \ncolor blue in daylight.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>

Word Boundaries

A word boundary character ( \b) helps you search for the words that begins and/or ends with a pattern.
For example, the regexp /\bcar/ matches the words beginning with the pattern car, and would match
cart, carrot, or cartoon, but would not match oscar.

Similarly, the regexp /car\b/ matches the words ending with the pattern car, and would match scar,
oscar, or supercar, but would not match cart. Likewise, the /\bcar\b/ matches the words beginning and
ending with the pattern car, and would match only the word car. The following example will highlight the
words beginning with car in bold:

<?php
$pattern = '/\bcar\w*/';
$replacement = '<b>$0</b>';
$text = 'Words begining with car: cart, carrot, cartoon. Words ending with car: scar,
oscar, supercar.';
echo preg_replace($pattern, $replacement, $text);
?>

We hope you have understood the basics of regular expression. To learn how to validate form data using
regular expression, please check out on PHP Form Validation.

PHP Filters

You will learn how to sanitize and validate user inputs in PHP.

Validating and Sanitizing Data with Filters

Sanitizing and validating user input is one of the most common tasks in a web application. To make this
task easier PHP provides native filter extension that you can use to sanitize or validate data such as e-mail
addresses, URLs, IP addresses, etc.

13
To validate data using filter extension you need to use the PHP's filter_var() function. The basic
syntax of this function can be given with:

filter_var(variable, filter, options)

This function takes three parameters out of which the last two are optional. The first parameter is the
value to be filtered, the second parameter is the ID of the filter to apply, and the third parameter is the
array of options related to filter. Let's see how it works.

Sanitize a String

The following example will sanitize a string by removing all HTML tags from it:

<?php
// Sample user comment
$comment = "<h1>Hey there! How are you doing today?</h1>";

// Sanitize and print comment string


$sanitizedComment = filter_var($comment, FILTER_SANITIZE_STRING);
echo $sanitizedComment;
?>

The output of the above example will look something like this:

Hey there! How are you doing today?

Validate Integer Values

The following example will validate whether the value is a valid integer or not.

<?php
// Sample integer value
$int = 20;

// Validate sample integer value


if(filter_var($int, FILTER_VALIDATE_INT)){
echo "The <b>$int</b> is a valid integer";
} else{
echo "The <b>$int</b> is not a valid integer";
}
?>

In the above example, if variable $int is set to 0, the example code will display invalid integer message.
To fix this problem, you need to explicitly test for the value 0, as follow:

<?php
// Sample integer value
$int = 0;

// Validate sample integer value


if(filter_var($int, FILTER_VALIDATE_INT) === 0 || filter_var($int,
FILTER_VALIDATE_INT)){
echo "The <b>$int</b> is a valid integer";
} else{
echo "The <b>$int</b> is not a valid integer";
}
?>

14
Validate IP Addresses

The following example will validate whether the value is a valid IP address or not.

<?php
// Sample IP address
$ip = "172.16.254.1";

// Validate sample IP address


if(filter_var($ip, FILTER_VALIDATE_IP)){
echo "The <b>$ip</b> is a valid IP address";
} else {
echo "The <b>$ip</b> is not a valid IP address";
}
?>

You can further apply validation for IPV4 or IPV6 IP addresses by using the FILTER_FLAG_IPV4 or
FILTER_FLAG_IPV6 flags, respectively. Here's an example:

<?php
// Sample IP address
$ip = "172.16.254.1";

// Validate sample IP address


if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)){
echo "The <b>$ip</b> is a valid IPV6 address";
} else {
echo "The <b>$ip</b> is not a valid IPV6 address";
}
?>

Sanitize and Validate Email Addresses

The following example will show you how to sanitize and validate an e-mail address.

<?php
// Sample email address
$email = "someone@@example.com";

// Remove all illegal characters from email


$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail address


if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "The <b>$email</b> is a valid email address";
} else{
echo "The <b>$email</b> is not a valid email address";
}
?>

Sanitize and Validate URLs

The following example will show you how to sanitize and validate a url.

<?php
// Sample website url
$url = "http:://www.example.com";

// Remove all illegal characters from url


$url = filter_var($url, FILTER_SANITIZE_URL);

15
// Validate website url
if(filter_var($url, FILTER_VALIDATE_URL)){
echo "The <b>$url</b> is a valid website url";
} else{
echo "The <b>$url</b> is not a valid website url";
}
?>

You can also check whether a URL contains query string or not by using the flag
FILTER_FLAG_QUERY_REQUIRED, as shown in the following example:

<?php
// Sample website url
$url = "http://www.example.com?topic=filters";

// Validate website url for query string


if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)){
echo "The <b>$url</b> contains query string";
} else{
echo "The <b>$url</b> does not contain query string";
}
?>

See on HTML URL to learn about the different components of a URL.

Validate Integers within a Range

The following example will validate whether the supplied value is an integer or not, as well as whether it
lies within the range of 0 to 100 or not.

<?php
// Sample integer value
$int = 75;

// Validate sample integer value


if(filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range" =>
0,"max_range" => 100)))){
echo "The <b>$int</b> is within the range of 0 to 100";
} else{
echo "The <b>$int</b> is not within the range of 0 to 100";
}
?>

PHP Error Handling

In this section you will learn how to use the PHP's error handling functions to deal with the error
conditions gracefully. Sometimes your application will not run as it supposed to do, resulting in an error.
There are a number of reasons that may cause errors, for example:

 The Web server might run out of disk space


 A user might have entered an invalid value in a form field
 The file or database record that you were trying to access may not exist
 The application might not have permission to write to a file on the disk
 A service that the application needs to access might be temporarily unavailable

These types of errors are known as runtime errors, because they occur at the time the script runs. They are
distinct from syntax errors that need to be fixed before the script will run.

16
A professional application must have the capabilities to handle such runtime error gracefully. Usually this
means informing the user about the problem more clearly and precisely.

Understanding Error Levels

Usually, when there's a problem that prevents a script from running properly, the PHP engine triggers an
error. Each error is represented by an integer value and an associated constant. The following table lists
some of the common error levels:

Error Level Valu Description


e
E_ERROR 1 A fatal run-time error, that can't be recovered from. The execution of the script is
stopped immediately.
E_WARNING 2 A run-time warning. It is non-fatal and most errors tend to fall into this category. The
execution of the script is not stopped.
E_NOTICE 8 A run-time notice. Indicate that the script encountered something that could possibly
an error, although the situation could also occur when running a script normally.
E_USER_ERROR 256 A fatal user-generated error message. This is like an E_ERROR, except it is generated
by the PHP script using the function trigger_error() rather than the PHP engine.
E_USER_WARNING 512 A non-fatal user-generated warning message. This is like an E_WARNING, except it is
generated by the PHP script using the function trigger_error() rather than the
PHP. engine
E_USER_NOTICE 1024 A user-generated notice message. This is like an E_NOTICE, except it is generated by
the PHP script using the function trigger_error() rather than the PHP engine.
E_STRICT 2048 Not strictly an error, but triggered whenever PHP encounters code that could lead to
problems or forward incompatibilities
E_ALL 8191 All errors and warnings, except of E_STRICT prior to PHP 5.4.0.

For more error levels, please check out the reference on PHP Error Levels.

The PHP engine triggers an error whenever it encounters a problem with your script, but you can also
trigger errors yourself to generate more user friendly error messages. This way you can make your
application more sofisticated. The following section describes some of common methods used for
handling errors in PHP:

Basic Error Handling Using the die() Function

Consider the following example that simply tries to open a text file for reading only.

<?php
// Try to open a non-existent file
$file = fopen("sample.txt", "r");
?>

If the file does not exist you might get an error like this:

Warning: fopen(sample.txt) [function.fopen]: failed to open stream: No such file or directory in C:\wamp\www\
project\test.php on line 2

If we follow some simple steps we can prevent the users from getting such error message.

<?php
if(file_exists("sample.txt")){
$file = fopen("sample.txt", "r");

17
} else{
die("Error: The file you are trying to access doesn't exist.");}
?>

Now if you run the above script you will get the error message like this:

Error: The file you are trying to access doesn't exist.

As you can see by implementing a simple check whether the file exist or not before trying to access it, we
can generate an error message that is more meaningful to the user.

The die() function used above simply display the custom error message and terminate the current script
if 'sample.txt' file is not found.

Creating a Custom Error Handler

You can create your own error handler function to deal with the run-time error generated by PHP engine.
The custom error handler provides you greater flexibility and better control over the errors, it can inspect
the error and decide what to do with the error, it might display a message to the user, log the error in a file
or database or send by e-mail, attempt to fix the problem and carry on, exit the execution of the script or
ignore the error altogether.

The custom error handler function must be able to handle at least two parameters (errno and errstr),
however it can optionally accept an additional three parameters (errfile, errline, and errcontext), as
described below:

Parameter Description
Required — The following parameters are required
errno Specifies the level of the error, as an integer. This corresponds to the appropriate error level constant
( E_ERROR, E_WARNING, and so on)
errstr Specifies the error message as a string
Optional — The following parameters are optional
errfile Specifies the filename of the script file in which the error occurred, as a string
errline Specifies the line number on which the error occurred, as a string
errcontext Specifies an array containing all the variables and their values that existed at the time the error
occurred. Useful for debugging

Here's an example of a simple custom error handling function. This handler, customError() is triggered
whenever an error occurred, no matter how trivial. It then outputs the details of the error to the browser
and stops the execution of the script.

<?php
// Error handler function
function customError($errno, $errstr){
echo "<b>Error:</b> [$errno] $errstr";
}
?>

You need to tell the PHP to use your custom error handler function — just call the built-in
set_error_handler() function, passing in the name of the function.

<?php
// Error handler function
function customError($errno, $errstr){
echo "<b>Error:</b> [$errno] $errstr";

18
}
// Set error handler
set_error_handler("customError");

// Trigger error
echo($test);
?>

Error Logging

Log Error Messages in a Text File

You can also logs details of the error to the log file, like this:

<?php
function calcDivision($dividend, $divisor){
if($divisor == 0){
trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
return false;
} else{
return($dividend / $divisor);
}
}
function customError($errno, $errstr, $errfile, $errline, $errcontext){
$message = date("Y-m-d H:i:s - ");
$message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
$message .= "Variables:" . print_r($errcontext, true) . "\r\n";

error_log($message, 3, "logs/app_errors.log");
die("There was a problem, please try again.");
}
set_error_handler("customError");
echo calcDivision(10, 0);
echo "This will never be printed.";
?>

Send Error Messages by E-Mail

You can also send e-mail with the error details using the same error_log() function.

<?php
function calcDivision($dividend, $divisor){
if ($divisor == 0){
trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
return false;
} else{
return($dividend / $divisor);
}
}
function customError($errno, $errstr, $errfile, $errline, $errcontext){
$message = date("Y-m-d H:i:s - ");
$message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
$message .= "Variables:" . print_r($errcontext, true) . "\r\n";

error_log($message, 1, "[email protected]");
die("There was a problem, please try again. Error report submitted to
webmaster.");
}
set_error_handler("customError");
echo calcDivision(10, 0);
echo "This will never be printed.";

19
?>

20
Trigger an Error

Although the PHP engine triggers an error whenever it encounters a problem with your script, however
you can also trigger errors yourself. This can help to make your application more robust, because it can
flag potential problems before they turn into serious errors.

To trigger an error from within your script, call the trigger_error() function, passing in the error
message that you want to generate:

trigger_error("There was a problem.");

Consider the following function that calculates division of the two numbers.

<?php
function calcDivision($dividend, $divisor){
return($dividend / $divisor);
}
// Calling the function
echo calcDivision(10, 0);
?>

If a value of zero (0) is passed as the $divisor parameter, the error generated by the PHP engine will
look something like this:

Warning: Division by zero in C:\wamp\www\project\test.php on line 3

This message doesn't look very informative. Consider the following example that uses the
trigger_error() function to generate the error.

<?php
function calcDivision($dividend, $divisor){
if($divisor == 0){
trigger_error("The divisor cannot be zero", E_USER_WARNING);
return false;
} else{
return($dividend / $divisor);
}
}
// Calling the function
echo calcDivision(10, 0);
?>

Now the script generates this error message:

Warning: The divisor cannot be zero in C:\wamp\www\project\error.php on line 4

As you can see the error message generated by the second example explains the problem more clearly as
compared to the previous one.

21

You might also like