PHP filters are used to validate and sanitize external input.
The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker.
The filter_list()
function can be used to list what the PHP filter extension offers:
Example
<table>
<tr>
<td>Filter Name</td>
<td>Filter ID</td>
</tr>
<?php
foreach (filter_list() as $id =>$filter) {
echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>';
}
?>
</table>
Why Use Filters?
Many web applications receive external input. External input/data can be:
- User input from a form
- Cookies
- Web services data
- Server variables
- Database query results
PHP filter_var() Function
The filter_var()
function both validate and sanitize data.
The filter_var()
function filters a single variable with a specified filter. It takes two pieces of data:
- The variable you want to check
- The type of check to use
Sanitize a String
The following example uses the filter_var()
function to remove all HTML tags from a string:
Example
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
Validate an Integer
The following example uses the filter_var()
function to check if the variable $int is an integer. If $int is an integer, the output of the code below will be: "Integer is valid". If $int is not an integer, the output will be: "Integer is not valid":
Example
<?php
$int = 100;
if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
Tip: filter_var() and Problem With 0
In the example above, if $int was set to 0, the function above will return "Integer is not valid". To solve this problem, use the code below:
Example
<?php
$int = 0;
if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int, FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
Validate an IP Address
The following example uses the filter_var()
function to check if the variable $ip is a valid IP address:
Example
<?php
$ip = "127.0.0.1";
if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {
echo("$ip is a valid IP address");
} else {
echo("$ip is not a valid IP address");
}
?>
Sanitize and Validate an Email Address
The following example uses the filter_var()
function to first remove all illegal characters from the $email variable, then check if it is a valid email address:
Example
<?php
$email = "john.doe@example.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Sanitize and Validate a URL
The following example uses the filter_var()
function to first remove all illegal characters from a URL, then check if $url is a valid URL:
Example
<?php
$url = "https://www.w3schools.com";
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
Validate an Integer Within a Range
The following example uses the filter_var()
function to check if a variable is both of type INT, and between 1 and 200:
Example
<?php
$int = 122;
$min = 1;
$max = 200;
if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) === false) {
echo("Variable value is not within the legal range");
} else {
echo("Variable value is within the legal range");
}
?>
Validate IPv6 Address
The following example uses the filter_var()
function to check if the variable $ip is a valid IPv6 address:
Example
<?php
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
echo("$ip is a valid IPv6 address");
} else {
echo("$ip is not a valid IPv6 address");
}
?>
Validate URL - Must Contain QueryString
The following example uses the filter_var()
function to check if the variable $url is a URL with a querystring:
Example
<?php
$url = "https://www.w3schools.com";
if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) {
echo("$url is a valid URL with a query string");
} else {
echo("$url is not a valid URL with a query string");
}
?>
Remove Characters With ASCII Value > 127
The following example uses the filter_var()
function to sanitize a string. It will both remove all HTML tags, and all characters with ASCII value > 127, from the string:
Example
<?php
$str = "<h1>Hello WorldÆØÅ!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
echo $newstr;
?>
Complete PHP Filter Reference
For a complete reference of all filter functions, go to our complete PHP Filter Reference. Check each filter to see what options and flags are available.
Callback Functions
A callback function (often referred to as just "callback") is a function which is passed as an argument into another function.
Any existing function can be used as a callback function. To use a function as a callback function, pass a string containing the name of the function as the argument of another function:
Example
Pass a callback to PHP's array_map()
function to calculate the length of every string in an array:
<?php
function my_callback($item) {
return strlen($item);
}
$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map("my_callback", $strings);
print_r($lengths);
?>
Starting with version 7, PHP can pass anonymous functions as callback functions:
Example
Use an anonymous function as a callback for PHP's array_map()
function:
<?php
$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map( function($item) { return strlen($item); } , $strings);
print_r($lengths);
?>
Callbacks in User Defined Functions
User-defined functions and methods can also take callback functions as arguments. To use callback functions inside a user-defined function or method, call it by adding parentheses to the variable and pass arguments as with normal functions:
Example
Run a callback from a user-defined function:
<?php
function exclaim($str) {
return $str . "! ";
}
function ask($str) {
return $str . "? ";
}
function printFormatted($str, $format) {
// Calling the $format callback function
echo $format($str);
}
// Pass "exclaim" and "ask" as callback functions to printFormatted()
printFormatted("Hello world", "exclaim");
printFormatted("Hello world", "ask");
?>
What is JSON?
JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data.
Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.
PHP and JSON
PHP has some built-in functions to handle JSON.
First, we will look at the following two functions:
- json_encode()
- json_decode()
PHP - json_encode()
The json_encode() function is used to encode a value to JSON format.
Example
This example shows how to encode an associative array into a JSON object:
<?php
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
echo json_encode($age);
?>
Example
This example shows how to encode an indexed array into a JSON array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo json_encode($cars);
?>
PHP - json_decode()
The json_decode() function is used to decode a JSON object into a PHP object or an associative array.
Example
This example decodes JSON data into a PHP object:
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
var_dump(json_decode($jsonobj));
?>
The json_decode() function returns an object by default. The json_decode() function has a second parameter, and when set to true, JSON objects are decoded into associative arrays.
Example
This example decodes JSON data into a PHP associative array:
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
var_dump(json_decode($jsonobj, true));
?>
PHP - Accessing the Decoded Values
Here are two examples of how to access the decoded values from an object and from an associative array:
Example
This example shows how to access the values from a PHP object:
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$obj = json_decode($jsonobj);
echo $obj->Peter;
echo $obj->Ben;
echo $obj->Joe;
?>
Example
This example shows how to access the values from a PHP associative array:
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$arr = json_decode($jsonobj, true);
echo $arr["Peter"];
echo $arr["Ben"];
echo $arr["Joe"];
?>
PHP - Looping Through the Values
You can also loop through the values with a foreach() loop:
Example
This example shows how to loop through the values of a PHP object:
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$obj = json_decode($jsonobj);
foreach($obj as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>
Example
This example shows how to loop through the values of a PHP associative array:
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$arr = json_decode($jsonobj, true);
foreach($arr as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>
What is an Exception?
An exception is an object that describes an error or unexpected behaviour of a PHP script.
Exceptions are thrown by many PHP functions and classes.
User defined functions and classes can also throw exceptions.
Exceptions are a good way to stop a function when it comes across data that it cannot use.
Throwing an Exception
The throw
statement allows a user defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed.
If an exception is not caught, a fatal error will occur with an "Uncaught Exception" message.
Lets try to throw an exception without catching it:
Example
<?php
function divide($dividend, $divisor) {
if($divisor == 0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
echo divide(5, 0);
?>
The result will look something like this:
Fatal error: Uncaught Exception: Division by zero in C:\webfolder\test.php:4
Stack trace: #0 C:\webfolder\test.php(9):
divide(5, 0) #1 {main} thrown in C:\webfolder\test.php on line 4
The try...catch Statement
To avoid the error from the example above, we can use the try...catch
statement to catch exceptions and continue the process.
Syntax
try {
code that can throw exceptions
} catch(Exception $e) {
code that runs when an exception is caught
}
Example
Show a message when an exception is thrown:
<?php
function divide($dividend, $divisor) {
if($divisor == 0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo divide(5, 0);
} catch(Exception $e) {
echo "Unable to divide.";
}
?>
The catch block indicates what type of exception should be caught and the name of the variable which can be used to access the exception. In the example above, the type of exception is Exception
and the variable name is $e
.
The try...catch...finally Statement
The try...catch...finally
statement can be used to catch exceptions. Code in the finally
block will always run regardless of whether an exception was caught. If finally
is present, the catch
block is optional.
Syntax
try {
code that can throw exceptions
} catch(Exception $e) {
code that runs when an exception is caught
} finally {
code that always runs regardless of whether an exception was caught
}
Example
Show a message when an exception is thrown and then indicate that the process has ended:
<?php
function divide($dividend, $divisor) {
if($divisor == 0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo divide(5, 0);
} catch(Exception $e) {
echo "Unable to divide. ";
} finally {
echo "Process complete.";
}
?>
Example
Output a string even if an exception was not caught:
<?php
function divide($dividend, $divisor) {
if($divisor == 0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo divide(5, 0);
} finally {
echo "Process complete.";
}
?>
The Exception Object
The Exception Object contains information about the error or unexpected behaviour that the function encountered.
Syntax
new Exception(message, code, previous)
Parameter Values
Parameter | Description |
---|---|
message | Optional. A string describing why the exception was thrown |
code | Optional. An integer that can be used used to easily distinguish this exception from others of the same type |
previous | Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter |
Methods
When catching an exception, the following table shows some of the methods that can be used to get information about the exception:
Method | Description |
---|---|
getMessage() | Returns a string describing why the exception was thrown |
getPrevious() | If this exception was triggered by another one, this method returns the previous exception. If not, then it returns null |
getCode() | Returns the exception code |
getFile() | Returns the full path of the file in which the exception was thrown |
getLine() | Returns the line number of the line of code which threw the exception |
Example
Output information about an exception that was thrown:
<?php
function divide($dividend, $divisor) {
if($divisor == 0) {
throw new Exception("Division by zero", 1);
}
return $dividend / $divisor;
}
try {
echo divide(5, 0);
} catch(Exception $ex) {
$code = $ex->getCode();
$message = $ex->getMessage();
$file = $ex->getFile();
$line = $ex->getLine();
echo "Exception thrown in $file on line $line: [Code $code]
$message";
}
?>
From PHP5, you can also write PHP code in an object-oriented style.
Object-Oriented programming is faster and easier to execute.
PHP What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.
Object-oriented programming has several advantages over procedural programming:
- OOP is faster and easier to execute
- OOP provides a clear structure for the programs
- OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
- OOP makes it possible to create full reusable applications with less code and shorter development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.
PHP - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
Look at the next chapters to learn more about OOP.
0 Comments