Unit - 1 Core PHP Programming - WFS
Unit - 1 Core PHP Programming - WFS
PHP started out as a small open source project that evolved as more and more people found
out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module
on the Unix side. The MySQL server, once started, executes even very complex queries
with huge result sets in record-setting time.
PHP Syntax is C-Like.
Characteristics of PHP
Five important characteristics make PHP's practical nature possible −
Simplicity
Efficiency
Security
Flexibility
Familiarity
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential
example, first we will create a friendly little "Hello, World!" script.
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal
HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this −
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
Output:
Hello, World!
What is PHP?
Key Points:
PHP evolved from simple scripts to a full-fledged, powerful programming language.
Continuously improved to support modern web development needs like OOP, security,
and faster processing.
What is XAMPP?
A free, open-source cross-platform web server solution package.
Includes Apache, MySQL/MariaDB, PHP, and Perl.
What is WAMP?
A Windows-based web development environment.
Includes Windows + Apache + MySQL + PHP.
Installation Steps (Common for XAMPP/WAMP):
1. Download the XAMPP/WAMP installer from the official website.
2. Run the Installer and follow the setup wizard.
3. Select components (Apache, MySQL, PHP) to install.
4. Choose the installation directory (default is C:\xampp or C:\wamp).
5. Complete the installation.
Configuration:
Start the Apache and MySQL services from the XAMPP/WAMP control panel.
Access the localhost via browser:
o XAMPP: http://localhost/dashboard/
WAMP: http://localhost/
o
Place PHP files inside:
o XAMPP: C:\xampp\htdocs
o WAMP: C:\wamp\www
Test PHP Setup:
<?php
phpinfo();
?>
Variables
variable starts with the $ sign, followed by the name of the variable:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Note: Remember that PHP variable names are case-sensitive!
Variable Scope
PHP has three types of variable scopes:
1. Global variable
2. Local variable
3. Static variable
Global
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function:
Example
Variable with global scope:
<?php
$name = "Sanaya Sharma"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Another way to use the global variable inside the function is predefined $GLOBALS array.
<?php
$num1 = 5; //global variable
$num2 = 13; //global variable
function global_var()
{
$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
echo "Sum of global variables is: " .$sum;
}
global_var();
?>
Local
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
Example
Variable with local scope:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
Static
It is a feature of PHP to delete the variable, once it completes its execution and memory is
freed. Sometimes we need to store a variable even after completion of function execution.
Therefore, another important feature of variable scoping is static variable. We use the static
keyword before the variable to define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program
execution leaves the scope. Understand it with the help of an example:
Example:
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
Constants
PHP constants are name or identifier that can't be changed during the execution of the script
except .
1. Using define() function
2. Using const keyword
Syntax
define(name, value)
Example
<?php
define("MSG1","Hello JavaTpoint PHP");
echo MSG1;
const MSG2="Hello const by JavaTpoint PHP";
echo MSG2;
?>
echo
The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command
Example:
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
?>
Print
The print statement can be used with or without parentheses: print or print().
Display Text
The following example shows how to output text with the print command (notice that the text
can contain HTML markup):
Example
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print ("Hello by PHP print()");
?>
Echo VS Print
Echo Print
1. echo does not return any value. 1. print always returns an integer value,
2. We can pass multiple strings separated which is 1.
by comma (,) in echo. 2. Using print, we cannot pass multiple
3. echo is faster than print statement. arguments.
3. print is slower than echo statement.
Data types
A type specifies the amount of memory that allocates to a value associated with it.
Scalar type:
It hold single value only:
1. Boolean: Booleans are the simplest data type works like switch. It holds only two
values: TRUE (1) or FALSE (0)
2. Integer:Integer means numeric data with a negative or positive sign. It holds only
whole numbers, i.e., numbers without fractional part or decimal points. The
range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -
2^31 to 2^31.
3. Float: A floating-point number is a number with a decimal point.
4. String: A string is a non-numeric data type. It holds letters or any alphabets,
numbers, and even special characters.String values must be enclosed either
within single quotes or in double quotes. But both are treated differently.
Example: $name = "Raman";
//both single and double quote statements will treat different
echo "Hello $name";
echo "</br>";
echo 'Hello $name';
Output:
Hello Javatpoint
Hello $company
Compound Type:
It hold multiple values
1. Array: An array is a compound data type. It can store multiple values of same data type in a
single variable.
Example:
$scores = [1, 2, 3];
2. Objects are the instances of user-defined classes that can store both values and functions.
Special type
1.Resource: Resources are not the exact data type in PHP. Basically, these are used to store
some function calls or references to external PHP resources. For example - a database call.
2. Null: Null is a special data type that has only one value: NULL
Operators
PHP divides the operators in the following groups:
Arithmetic operators: The PHP arithmetic operators are used to perform common
arithmetic operations such as addition, subtraction, etc. with numeric values.
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise
0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of
comparison operators are given:
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same
data type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not
of same data type
<= Less than or equal $a <= $b Return TRUE if $a is less than or equal $b
to
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a
variable.
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators
The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:
=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of
same type in same order
to write code that perform different actions based on the results of a logical or comparative
test conditions at run time.
The if statement
The if...else statement
The if...elseif....else statement
The switch...case statement
The if Statement
The if statement is used to execute a block of code only if the specified condition evaluates to
true.
Syntax:
if(condition){
// Code to be executed
}
Example:
output "Have a nice weekend!" if the current day is Friday:
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
The if...else Statement
You can enhance the decision making process by providing an alternative choice through
adding an else statement to the if statement. The if...else statement allows you to execute one
block of code if the specified condition is evaluates to true and another block of code if it is
evaluates to false. It can be written, like this:
Syntax:
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
Exaple:Output "Have a nice weekend!" if the current day is Friday, otherwise it will output
"Have a nice day!"
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
The if...elseif...else Statement
The if...elseif...else a special statement that is used to combine multiple if...else statements.
Syntax:
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
Example:
output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the
current day is Sunday, otherwise it will output "Have a nice day!"
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
The switch-case statement is an alternative to the if-elseif-else statement, which does almost
the same thing. The switch-case statement tests a variable against a series of values until it
finds a match, and then executes the block of code corresponding to that match.
switch(n){
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels
}
Consider the following example, which display a different message for each day.
Example
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>
Arrays
It is used to hold multiple values of similar type in a single variable.
Advantage of PHP Array
Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.
There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
Indexed Array
PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
OR
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
Associative Array
We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
OR
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data
in an array. PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.
Definition
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
Php Loops
the following loop types:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
Examples
The example below displays the numbers from 1 to 5:
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
do...while Loop
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less
than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
Examples
The example below displays the numbers from 0 to 10:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the
array pointer is moved by one, until it reaches the last array element.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
Array Function:
Function Description Example Output
array() Creates an $cars=array("Volvo","BMW","Toyota
array ")
$age=array("Peter"=>"35","Ben"=>"3
7","Joe"=>"43");
$cars=array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
)
array_change_key_cas Changes all $age=array("Peter"=>"35","Ben"=>"3 Array ( [peter] => 35 [ben] =>
e() keys in an 7","Joe"=>"43"); 37 [joe] => 43 )
array to print_r(array_change_key_case($age
lowercase or ,CASE_LOWER));
uppercase
array_chunk() Splits an $cars=array("Volvo","BMW","Toyota Array ( [0] => Array ( [0] =>
array into ","Honda","Mercedes","Opel"); Volvo [1] => BMW ) [1] =>
chunks of print_r(array_chunk($cars,2)); Array ( [0] => Toyota [1] =>
arrays Honda ) [2] => Array ( [0] =>
Mercedes [1] => Opel ) )
array_combine() Creates an $fname=array("Peter","Ben","Joe"); Array ( [Peter] => 35 [Ben] =>
array by using $age=array("35","37","43"); 37 [Joe] => 43 )
the elements
from one $c=array_combine($fname,$age);
"keys" array print_r($c);
and one
"values"
array
array_count_values() Counts all the $a=array("A","Cat","Dog","A","Dog"); Array ( [A] => 2 [Cat] => 1
values of an print_r(array_count_values($a)); [Dog] => 2 )
array
array_diff() Compare $a1=array("a"=>"red","b"=>"green", Array ( [d] => yellow )
arrays, and "c"=>"blue","d"=>"yellow");
returns the $a2=array("e"=>"red","f"=>"green","
differences g"=>"blue");
(compare
values only) $result=array_diff($a1,$a2);
print_r($result);
array_diff_assoc() Compare $a1=array("a"=>"red","b"=>"green", Array ( [d] => yellow )
arrays, and "c"=>"blue","d"=>"yellow");
returns the $a2=array("a"=>"red","b"=>"green",
differences "c"=>"blue");
(compare
keys and $result=array_diff_assoc($a1,$a2);
values) print_r($result);
print_r($result);
count() Returns the $cars=array("Volvo","BMW","Toyota 3
number of ");
elements in echo count($cars);
an array
in_array() Checks if a $people = array("Peter", "Joe", Match found
specified "Glenn", "Cleveland");
value exists in
an array if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
krsort() Sorts an $age=array("Peter"=>"35","Ben"=>"3 Key=Peter, Value=35
associative 7","Joe"=>"43"); Key=Joe, Value=43
array in krsort($age); Key=Ben, Value=37
descending
order, foreach($age as $x=>$x_value)
according to {
the key echo "Key=" . $x . ", Value=" .
$x_value;
echo "<br>";
}
ksort() Sorts an $age=array("Peter"=>"35","Ben"=>"3 Key=Ben, Value=37
associative 7","Joe"=>"43"); Key=Joe, Value=43
array in krsort($age); Key=Peter, Value=35
ascending
order, foreach($age as $x=>$x_value)
according to {
the key echo "Key=" . $x . ", Value=" .
$x_value;
echo "<br>";
}
rsort() Sorts an $cars=array("Volvo","BMW","Toyota Volvo
indexed array "); Toyota
in descending rsort($cars); BMW
order
sort() Sorts an $cars=array("Volvo","BMW","Toyota BMW
indexed array "); Toyota
in ascending sort($cars); Volvo
order
Function Description
boolval() Returns the boolean value of a variable
empty() Checks whether a variable is empty
is_array() Checks whether a variable is an array
is_bool() Checks whether a variable is a Boolean
is_float()/is_double() Checks whether a variable is of type float
is_int()/is_integer() Checks whether a variable is of type integer
Miscellaneous functions:
Function Description Example
Define define(name,value,case_insensiti define("pi",3.14);
ve) echo pi;
A constant's value cannot be
changed after it is set Output:3.14
Constant names do not need a
leading dollar sign ($)
Constants can be accessed
regardless of scope
Constant values can only be
strings and numbers
Exit() exit(message) $x = 1;
prints a message and terminates exit ($x);
the current script
Die() die(message) mysql_connect(“hostname”,”mysqluserna
Print a message and terminate me”,””) or die(‘We are aware of the
the current script problem and working on it’);
Note: exit() is used to stop the
execution of the program,
and die() is used to throw an
exception and stop the
execution.
Header header(header, replace, http_res header("Expires: Mon, 26 Jul 1997 05:00:00
ponse_code) GMT");
Sends a raw HTTP header to a header("Cache-Control: no-cache");
client
User-defined Functions
Function Arguments
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-
length argument list.
Call by value:
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
$name=’Chirag’;
sayHello("Sonoo");
?>
Call by reference:
By default, value passed to the function is call by value. To pass value as a reference, you need
to use ampersand (&) symbol before the argument name.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Default Argument Value
We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Returning Value
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
we have passed two parameters $x and $y inside two functions add() and sub().
<?php
//add() function with two parameter
function add($x,$y)
{
$sum=$x+$y;
echo "Sum = $sum <br><br>";
}
//sub() function with two parameter
function sub($x,$y)
{
$sub=$x-$y;
echo "Diff = $sub <br><br>";
}
//call function, get two argument through input box and click on add or sub button
if(isset($_POST['add']))
{
//call add() function
add($_POST['first'],$_POST['second']);
}
if(isset($_POST['sub']))
{
//call add() function
sub($_POST['first'],$_POST['second']);
}
?>
<form method="post">
Enter first number: <input type="number" name="first"/><br><br>
Enter second number: <input type="number" name="second"/><br><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
</form>
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server logs, in the
browser's Location: box.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to
the server.
GET can't be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment
variable.
The PHP provides $_GET associative array to access all the sent information using GET
method.
Try out following example by putting the source code in test.php script.
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
The PHP provides $_POST associative array to access all the sent information using POST
method.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We
will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
Input Validation and Sanitization:
Input validation and sanitization are essential techniques in PHP to ensure that data received
from users is safe and usable. These steps protect your application from attacks like XSS, SQL
injection, and malformed input.
filter_var() is a built-in PHP function used to validate and sanitize data (mostly user input). It
applies a filter to a variable and returns the filtered result.
Syntax:
filter_var(variable, filter, options)
variable: The value to be filtered.
filter: The ID of the filter to apply (like FILTER_VALIDATE_EMAIL,
FILTER_SANITIZE_STRING, etc.).
options: Optional. An associative array of options or flags to customize behavior.
Validation Example:
Check if an email is valid:
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
Sanitization Example:
Remove illegal characters from an email:
$email = "test@@example.com";
$clean_email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $clean_email; // Outputs: test@@example.com (removes invalid parts)
Common Filters:
Filter Type Filter Name Description
Validation FILTER_VALIDATE_INT Validates integer
FILTER_VALIDATE_EMAIL Validates email format
FILTER_VALIDATE_URL Validates URL format
Sanitization FILTER_SANITIZE_STRING Removes HTML tags
FILTER_SANITIZE_EMAIL Removes illegal characters in email
FILTER_SANITIZE_URL Removes illegal URL characters
Note: As of PHP 8.1, FILTER_SANITIZE_STRING is deprecated. Use other methods like
strip_tags() and htmlspecialchars() for strings.
1. Input Validation
Input validation checks whether the user input meets expected rules (like format, type, length,
etc.).
Example: Validating Email Address
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email: " . $email;
} else {
echo "Invalid email format.";
}
Example: Validating Integer
$age = $_POST['age'];
if (filter_var($age, FILTER_VALIDATE_INT)) {
echo "Valid age: " . $age;
} else {
echo "Age must be an integer.";
}
2. Input Sanitization
Sanitization cleans input by removing or escaping unwanted characters to make it safe for
further processing.
Example: Sanitizing Email Input
php
CopyEdit
$email = $_POST['email'];
$clean_email = filter_var($email, FILTER_SANITIZE_EMAIL);