© Gunnard Engebreth, Satej Kumar Sahu 2023
G. Engebreth, S. K. SahuPHP 8 Basicshttps://doi.org/10.1007/978-1-4842-8082-9_9

9. PHP Exceptions, Validation, and Regular Expressions

Gunnard Engebreth1   and Satej Kumar Sahu2
(1)
Madison, WI, USA
(2)
Bangalore, India
 

PHP is indeed one of the most used programming languages in the world to develop applications and websites on the Internet. PHP 8 is a very dynamic, flexible programming language; it’s also easy to use as embedded language, for instance, for HTML.

In this chapter, you will learn all about exceptions, form validation, and regular expressions. What are they and when do we need to use them?

PHP is indeed very flexibility programming language, also when it comes to handling exceptions, which are out-of-the-ordinary scenarios that may occur in code. A code exception can be something like an input or code bug, and PHP version 8, compared to previous versions, has been updated to be more secure and to handle more exceptions better.

We will explain how to use PHP exceptions using try, catch, and throw.

Also, as developer, you will need to do web form validation, which means validating certain values entered in a PHP form of various input field types like text boxes, checkboxes, radio buttons, and checklists.

Finally, we will describe the usage of PHP regular expressions, which are simply a sequence of characters that form a search pattern and can be used, for instance, to check with your PHP code if a provided string of text contains a certain pattern of characters.

This chapter consists of the following sections:
  • PHP Exceptions (try, catch, finally, and throw)

  • PHP Form Validation (validating Name and E-Mail values)

  • PHP Regular Expressions

PHP Exceptions

As we said in the introduction of the chapter, an exception in a programming language is simply an unexpected outcome of a PHP program. Your goal is to tell your code how to handle any unexpected outcome by itself, where possible.

Please remember that the main difference between an error and an exception is that an exception will disrupt the normal flow of your code but by adding some additional code it can be handled while an error cannot be handled by the code itself. You will see how to use PHP to handle exceptions thrown and catch them.

PHP, like all programming languages, must have a code exception mechanism to handle runtime errors, also known exceptions. This, in PHP and any other language, is necessary to maintain the normal flow of the application.

Each language includes a set of throwable exceptions and errors. In PHP, there are many different types of errors that may occur in your code. Here are some:
  • CompileError

  • ParseError

  • TypeError

  • ArithmeticError

PHP also include an exception called implements throwable, which can be the following:
  • ClosedGeneratorException: Occurs when trying to attempt to perform a traversal on a generator that has already been closed or terminated.

  • DOMException: When an operation is impossible to perform for logical reasons

  • ErrorException: Used to convert a PHP error to an exception

  • IntlException: As per the PHP documentation, this class is used for generating exceptions when errors occur inside an intl function. Such exceptions are only generated when intl.use_exceptions is enabled.

PHP can help us handle runtime errors such as IOException, SQLException, ClassNotFoundException, and many more.

Let’s start with an example where unfortunately the exception is not caught, generating a fatal error issued with an "Uncaught Exception" message.

In this example, you will throw an exception without catching it by sending the number 3 to a PHP function named checkMyNum, which is expecting only a value of 1 or below.

Here is the code:

Chapter9/exception1.php
<?php
//here we create a function with an exception
function checkMyNum($mynumber) {
  if($mynumber>1) {
    throw new Exception("The entered number must be 1 or below!!");
  }
  return true;
}
checkMyNum(3);
?>
Fatal error: Uncaught exception 'Exception'
with message The entered number must be 1 or below!!' in C:mytest.php:5
Stack trace: #0 C:mytest.php(11):
checkMyNum(3) #1 {main} thrown in C:mytest.php on line 5
To fix this error, let’s see how to handle and correct the above uncaught exception error by using PHP exception handling ways named try, catch, and throw.
  • try: The try block includes your function triggered in the case of an exception of your code. If no exception triggers the try, the code will simply continue as normal. If an exception is triggered, it means that the exception is "thrown."

  • throw: This is how you trigger a certain exception but remember that each throw must have at least one catch in the code.

  • catch: The catch block mainly retrieves the exception occurred and creates an object containing the exception information and decides what to do, like print an error message.

  • finally: The finally block can be specified after or instead of a catch block. The code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown and before normal execution resumes.

The syntax of the try...catch...finally block looks like this:
<?php
try {
     // do something in our code
} catch (Exception $e) {
     // code to handle any exception
} finally {
     // code to clean up the resource and complete the code execution
}
In general, this is what happens when you run the code and an exception is triggered:
  • The current state of your code will be saved.

  • The execution of your code will be switched automatically to the predefined exception handler function you added in the code.

  • Finally, the handler function will halt the execution of program, will either resume the execution from the last saved code state, or continue the execution of your code from another part of it.

Let’s now take your uncaught exception error PHP code and fix it with try, catch, finally, and throw methods.

Chapter9/exception2.php
<?php
//here we create a function with an exception
function checkMyNum($mynumber) {
  if($mynumber>1) {
    throw new Exception("The entered number must be 1 or below!!");
  }
  return true;
}
//let's trigger the exception in a "try" block sending the number 3
try {
  checkMyNum(3);
  //In the case of the exception thrown, this text will not be shown to the user
  echo 'The number you entered is 1 or below!!';
}
//our code will catch exception and generate a message
catch(Exception $e) {
echo 'Caught exception: ',  $e->getMessage(), " ";
}
// finally block to complete our code execution process
finally {
    echo "Code execution completed.";
}
?>
The output of this code is the following:
Caught exception: The entered number must be 1 or below!!
Code execution completed.
Let’s explain the code.
  • You create a checkMyNum() function, which simply checks if a number is greater than 1.

  • Since you sent the number 3, the exception within the checkMyNum() function is thrown

  • The checkMyNum() function is called in the try block.

  • Your code in the catch block will simply retrieve the exception and create the object ($e) that contains the exception information, in your case to print the “Caught exception” error message using echo, which finally will print the error message from the exception by calling $e->getMessage().

  • The finally block will complete your code, just closing the code execution and writing the message “Code execution completed.”

Please remember that you can develop your own PHP customized exception handler by just creating a special class with functions that can be called when a certain exception occurs in your PHP code. This customized exception handler class must be an extension of the exception class.

Let’s see next how to validate a PHP web form.

PHP Form Validation

Web form validation at the client side is very important for security reasons, helping developers protect PHP forms from hackers and spammers.

You may need to perform a PHP form validation of the values entered in a PHP form containing various types of fields like text boxes, checkboxes, radio buttons, and checklists.

Say you have an HTML web form and you want to use PHP to validate the values entered in the form prior sending it to the server.

First, build a simple HTML web form like this:

Chapter9/form-action.html
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>PHP Form Validation</h2>
<form  method="post" action="form-action.php" >
  Name: <input type="text" name="name">
  <br><br>
  E-mail: <input type="text" name="email">
  <br><br>
    <input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When you run your HTML form, it will look like Figure 9-1.
Figure 9-1

HTML form web page

Now you need to write some PHP code that will allow you to simply verify the values entered as Name and E-mail before they are sent to the server.

Suppose you wish to have the HTML value of Name required and that it must only contain letters and whitespace. The E-mail value will also be required and must contain a valid email address (including @ and . as typical email format characters).

Let’s start from the previous HTML web page and add some PHP validation code. Create a new PHP file named form-action.php, which for now will only validate if the values entered are not empty:

Chapter9/form-action.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$name = "";
$email = "";
$nameError = "";
$emailError = "";
  if (empty($_POST["name"])) {
    $nameError = "Name is required";
  }
  if (empty($_POST["email"])) {
    $emailError = "Email is required";
  }
?>
<h2>PHP Form Validation</h2>
<p><span class="error">* required field</span></p>
<form  method="post" action="form-action.php" >
  Name: <input type="text" name="name">
  <span class="error">* <?php echo $nameError;?></span>
  <br><br>
  E-mail: <input type="text" name="email">
  <span class="error">* <?php echo $emailError;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When you run your PHP file, it will look like Figure 9-2.
Figure 9-2

PHP form web page

As you can see, the web form informs you that the Name and E-mail fields are required and therefore cannot be empty. When you try to submit the form with one or both fields empty, you will get the error messages shown in Figure 9-3.
Figure 9-3

PHP form web page submitted with empty fields

Let’s update the PHP example so that it will validate the value entered for Name, which must only be letters and whitespace, and validate that the format of the E-mail value must contain @ and . characters as part of the value submitted.

Here is the updated code:

Chapter9/form-action.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$name = "";
$nameError = "";
$email = "";
$emailError = "";
  if (empty($_POST["name"])) {
    $nameError = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
      $nameError = "Error: Only letters and whitespace allowed!";
    }
  }
  if (empty($_POST["email"])) {
    $emailError = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailError = "Error: Invalid email format!";
    }
  }
?>
<h2>PHP Form Validation</h2>
<p><span class="error">* required field</span></p>
<form  method="post" action="form-action.php" >
  Name: <input type="text" name="name">
  <span class="error">* <?php echo $nameError;?></span>
  <br><br>
  E-mail: <input type="text" name="email">
  <span class="error">* <?php echo $emailError;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Rerun your PHP file. Now, just entering some special characters in the Name field and entering the E-mail value with no @ or . characters will result in error messages that the characters are not allowed and the email format is invalid. See Figure 9-4.
Figure 9-4

PHP form web page submitted with invalid values

When you analyze the code, you see that to validate the Name value, you utilize the PHP regular expression function preg_match() (you will learn more about it later in this chapter), which returns 1 if the pattern is found in the string and 0 if it is not.

So, in your PHP code you define the function as preg_match("/^[a-zA-Z-' ]*$/",$name)), where you force the value entered to have only letters and whitespace. If not, the code will produce an error message of “Error: Only letters and whitespace allowed!”

To validate the E-mail value, you use the PHP function named filter_var(), which filters a variable with a specified filter and utilizes the PHP predefined filter constant FILTER_VALIDATE_EMAIL, which validates a value as a valid format for an entered e-mail address.

If you didn’t enter @ or ., the code will produce the error “Error: Invalid email format!”

Let’s now learn how to use PHP regular expressions.

PHP Regular Expressions

As we said in the introduction of the chapter, a regular expression is simply a sequence of characters that forms a searching pattern. Regular expressions are commonly known as regex and by default they are case-sensitive.

In general, a regular expression can be a single character or a more complicated pattern made of several characters.

They are mainly used when you need to run a text search, perform a text replace operation, or split a string into multiple chunks, for instance.

Regular expressions use arithmetic operators (+, -, ^) to create complex expressions.

Consider using regular expressions when
  • You need to validate a certain text string in your code.

  • You need to analyze and search a pattern in a certain string or modify a text string.

  • You need to search for special keywords.

  • You need help with user input validation testing, validating browser detection, spamming filtration, password strength checking, and more.

The PHP regular expression syntax looks like this:
$pattern = "/mas[si]mo/i";
$text = "My name is Massimo.";
where
  • / is the delimiter .

  • mas[si]mo is the pattern you are searching for.

  • i is an example of a special character you can use with a regular expression (in this case, it forces case-insensitive searching).

  • [si]: This square bracket defines which character within a certain pattern might or might not be searched (in this case, it means match one character, s or i).

  • @Text is the given string you will search the pattern in.

In regular expressions, the delimiter can be any character, but it cannot be a letter, number, backslash, or space.

Regular Expressions Modifiers

Regular expressions utilize special characters named modifiers to define how the search is performed. They include
  • i: When you need to have a case-insensitive pattern search

  • m: When you need to perform a multiline search using a pattern to search at the beginning or end of a string to match

  • u: When you need to enable a correct matching of UTF-8 encoded patterns

Regular Expression Metacharacters

Regular expression syntax includes the use of special characters, also called metacharacters, with certain special meanings:
  • is a general escape character with several uses.

  • ^ means to assert start of subject (or line, in multiline mode).

  • $ means to assert end of subject or before a terminating newline (or end of line, in multiline mode).

  • . means match any character except newline (by default).

  • [ means start character class definition.

  • ] means end character class definition.

  • | means the start of an alternative branch.

  • ( means start a subpattern.

  • ) means end a subpattern.

  • ? extends the meaning of (, also 0 or 1 quantifier, also makes greedy quantifiers lazy (see repetition).

  • * is used for 0 or more quantifiers.

  • + is used for 1 or more quantifiers.

  • { is a start min/max quantifier.

  • } is an end min/max quantifier.

Regular Expression Square Brackets

In a regular expression, square brackets surrounding a pattern of characters are called a character class, So [abcdef] will match a single character out of your list of specified characters. In this example of a regular expression, [abcdef] will only match the a, b, c, d , e, or f characters and nothing else.

Here is how square brackets can be used with regular expressions:
  • [abc] means match one character from the options in the brackets.

  • [^abc] means match any character NOT in the brackets.

  • [0-9] means match one character from the range 0 to 9.

Regular Expression Quantifiers

Regular expressions also include so-called quantifiers to specify the specific number of times that a character or a group of characters can be repeated in a regular expression. Here are some examples:
  • a+ matches any string that contains at least one character a.

  • a* matches any string that contains zero or more occurrences of the character a.

  • a{x} matches any string that contains the letter a exactly x times.

  • a{2} matches any string that contains the letter a exactly two times.

  • a{x,y} matches any string that contains a between x and y times.

Finally, PHP regular expressions use grouping via parentheses to apply quantifiers to entire patterns.

Regular Expression Functions

Let’s have a look now at the major regular expression functions that are used with PHP:
  • preg_match() returns 1 if the pattern is found in the string and 0 if it is not.

  • preg_match_all() returns the number of how many times the pattern was found in the string or false on failure.

  • preg_replace() returns a new string where matched patterns have been replaced with another string; otherwise, the subject is returned unchanged or null if an error occurrs.

Let’s start your first example of PHP regular expression using preg_match(), which will return 1 if the pattern is found in the string and 0 if it is not. Here is the code:

Chapter 9 (regexpress1.php)
<?php
$pattern = "/massimo/i";
$text = "My name is Massimo.";
if(preg_match($pattern, $text)){
    echo "Match was found!"; }
else{
   echo "Match was not found."; }
?>

The output of this code is Match was found! because “Massimo” is in the text and the i means case-insensitive, which means “Massimo” and “Massimo” are the same.

Removing the i from the pattern means a match will be not found because regular expressions are by default case-sensitive.

Let’s have the same example but using some squared brackets.

Chapter 9/regexpress2.php
<?php
$pattern = "/mas[trgs]imo/i";
$text = "My name is Massimo.";
if(preg_match($pattern, $text)){
    echo "Match was found!"; }
else{
   echo "Match was not found."; }
?>

The output of this code is Match was found! as “Massimo” is in the text, with the i meaning case-insensitive but in this case one of the needed characters, s, is in the square bracket of [trgs], which means match one character from the options in the brackets. Since s is in the square bracket, the pattern is found.

Here’s an example using the metacharacter $, which means look for a match at the end of the string:

Chapter9/regexpress3.php
<?php
$pattern = "/imo$/";
$text = "Massimo";
if(preg_match($pattern, $text)){
    echo "Match was found!"; }
else{
   echo "Match was not found."; }
?>

The output of this code is Match was found! as the pattern “imo” is found at the end of the text “Massimo.”

Let’s create an example of a regular expression with a group and quantifier. You want to search for a match in a string that contains the letters “co” exactly two times.

Chapter9/regexpress4.php
<?php
$pattern = "/(co){2}/i";
$text = "I like coconut.";
if(preg_match($pattern, $text)){
    echo "Match was found!"; }
else{
   echo "Match was not found."; }
?>

The output of this code is Match was found! because the pattern “co” is found exactly two times in the text “I love coconut.”

Let’s create a new PHP example of a regular expression using preg_match_all(), which will return the number of how many times the pattern was found in the string.

Chapter9/regexpress5.php
<?php
$pattern = "/na/i";
$text = "My name is Massimo and I was born in Naples";
echo preg_match_all($pattern, $text);
?>

The output of this code is 2 because the pattern “na” is found two times: in the words “name” and “Naples,” because you added I so the case is insensitive.

Finally, let’s create a new PHP example of a regular expression using preg_replace(), which returns a very new string where matched patterns are replaced with another string.

Chapter9/regexpress6.php
<?php
$pattern = "/red/i";
$text = "My favorite color is red!";
echo preg_replace($pattern, "blue", $text);
?>

The output of this code is “My favorite color is blue!” because the pattern “red” is found in the text and is replaced with the new text “blue.” The case is insensitive because you added i.

Summary

In this chapter, you first learned about PHP proper exceptions and how to deal with them using the try, throw, and catch methods. Then you saw how to use PHP to validate client HTML form values entered before sending the value to the server. Finally, you learned about PHP regular expressions, which are used almost everywhere in current application programming, allowing you to search for a specific pattern of characters inside a given string.

In the next chapter, you will see PHP and MySQL working together and learn how to create MySQL databases, tables, and use PHP programming code to handle them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset