2 PHP
2 PHP
Example:
<?php Output
echo (abs(-7)."<br/>"); // 7 (integer) 7
echo (abs(7)."<br/>"); //7 (integer) 7
echo (abs(-7.2)."<br/>"); //7.2 (float/double) 7.2
?>
ceil()
This function takes numeric value as argument and returns the next highest
integer value by rounding up value if necessary.
Syntax:
float ceil ( float $value )
Example:
<?php Output
echo (ceil(3.3)."<br/>");// 4 4
echo (ceil(7.333)."<br/>");// 8 8
echo (ceil(-4.8)."<br/>");// -4 -4
?>
floor()
This function takes numeric value as argument and returns the next lowest integer
value (as float) by rounding down value if necessary.
Syntax:
float floor ( float $value )
Example:
<?php Output
echo (ceil(3.3)."<br/>");// 4 4
echo (ceil(7.333)."<br/>");// 8 8
echo (ceil(-4.8)."<br/>");// -4 -4
?>
fmod()
This function takes two arguments as input returns the floating point
remainder (modulo) of division of arguments.
Syntax:
float fmod ( float $x , float $y );
Example:
<?php Output
$x = 7;
$y = 2; By using 'fmod()' Function
echo "Your Given Nos is : $x=7, $y=2" your value is:1
$result ="By using 'fmod()' Function your value is:".fmod($x,$y);
echo $result;
// $result equals 1, because 2 * 3 + 1 = 7
?>
<?php Output
$x = 5.7; Your Given Nos is : x=5.7,
$y = 1.3; y=1.3
echo "Your Given Nos is : x=5.7, y=1.3"; By using 'fmod()' Function
echo "<br>"."By using 'fmod()' function your value is:".fmod($x, $y); your value is:0.5
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>
max()
The max() function is used to find the highest value from the given numbers or the
given array which depends upon the parameter.
Syntax:
max(array_values);
OR
max(value1,value2,value3,value4...);
Example:
<?php Output
$num=max(4,14,3,5,14.2); Your number is
echo "Your number is =max(4,14,3,5,14.2)".'<br>'; =max(4,14,3,5,14.2)
echo "By using max function Your number is : ".$num; By using max function Your
?> number is : 14.2
<?php Output
$num=max(.1, .001, .2, -.5); Your number is =max(.1, .001,
echo "Your number is =max(.1, .001, .2, -.5)".'<br>'; .2, -.5)
echo "By using max function Your number is : ".$num; By using max function Your
?> number is : 0.2
<?php Output
$arr= array(110, 20, 52 ,105, 56, 89, 96); Your number is =array(110,
echo "Your number is =array(110, 20, 52 ,105, 56, 89, 96)".'<br>'; 20, 52 ,105, 56, 89, 96)
echo "By using max() function Your number is : ".max($arr); By using max() function Your
?> number is : 110
min()
The min() function is used to find the smallest value from the given numbers or the
given array which depends upon the parameter.
Syntax:
min(array_values);
OR
min(value1,value2,value3,value4...);
Example:
<?php Output
$num=min(4,14,3,5,14.2); Your number is
echo "Your number is =min(4,14,3,5,14.2)".'<br>'; =min(4,14,3,5,14.2)
echo "By using min function Your number is : ".$num; By using min function Your
?> number is : 3
<?php Output
$num=min(.1, .001, .2, -.5); Your number is =max(.1, .001,
echo "Your number is =min(.1, .001, .2, -.5)".'<br>'; .2, -.5)
echo "By using min function Your number is : ".$num; By using max function Your
?> number is : 0.001
<?php Output
$arr= array(110, 20, 52 ,105, 56, 89, 96); Your number is =array(110,
echo "Your number is =array(110, 20, 52 ,105, 56, 89, 96)".'<br>'; 20, 52 ,105, 56, 89, 96)
echo "By using min() function Your number is : ".min($arr); By using max() function Your
?> number is : 20
pow()
The pow() is a PHP mathematic function. It raises the first number to the power
of the second number.
Syntax:
number pow ( number $base , number $exp )
Example:
<?php Output
$num=pow(3, 2); Your number is = pow (3, 2)
echo "Your number is = pow (3, 2)".'<br>'; By using sqrt function Your number is : 9
echo "By using sqrt function Your number is : ".$num;
?>
<?php Output
$num=pow(-5, 2); Your number is = pow (-5, 2)
echo "Your number is = pow (-5, 2)".'<br>'; By using sqrt function Your number is : 2
echo "By using sqrt function Your number is : ".$num; 5
?>
<?php Output
$num=pow(-3, -3); Your number is = pow (-3, -3)
echo "Your number is = pow (-3, -3)".'<br>'; By using sqrt function Your number is : -
echo "By using sqrt function Your number is : ".$num; 0.037037037037037
?>
<?php Output
$num=pow(-3, -1.5); Your number is = pow (-3, -1.5)
echo "Your number is = pow (-3, -1.5)".'<br>'; By using sqrt function Your number is : -
echo "By using sqrt function Your number is : ".$num; NAN
?>
rand()
The rand() function is used to generate the random integer.
Syntax:
Int rand(void)
OR
Int rand(int $min, int $max)
Example:
<?php Output
echo "Get Random number by using rand() function: ".(rand( Get Random number by using
) . "<br>"); rand() function: 81627923
echo "Get Random number by using rand() function: ".(rand( Get Random number by using
) . "<br>"); rand() function: 1857469033
echo "<b>"."Note: Refresh page to get another random value Note: Refresh page to get another
"."<b>"; random value
?>
<?php Output
$num=pow(-5, 2); Your number is = pow (-5, 2)
echo "Your number is = pow (-5, 2)".'<br>'; By using sqrt function Your number
round()
The round() function in PHP is used to round a floating-point number. It can be
used to define a specific precision value which rounds number according to that
precision value.Precision can be also negative or zero.
Syntax:
float round($number, $precision, $mode);
Parameters:
1. $number: It is the number which you want to round.
2. $precision: It is an optional parameter. It specifies the number of decimal
digits to round to. The default value of this parameter is zero.
3. $mode: It is an optional parameter. It specifies a constant to specify the
rounding mode. The constant can be one of the following:
PHP_ROUND_HALF_UP: This mode tells to round up the number specified
by parameter $number by precision specified by parameter $precision away
from zero.
PHP_ROUND_HALF_DOWN: This mode tells to round up the number
specified by parameter $number by precision specified by
parameter $precision towards zero.
PHP_ROUND_HALF_EVEN: This mode tells to round up the number specified
by parameter $number by precision specified by
parameter $precision towards nearest even value.
PHP_ROUND_HALF_ODD: This mode tells to round up the number specified
by parameter $number by precision specified by
parameter $precision towards nearest odd value.
Return Value: It returns the rounded value.
Example:
<?php
Output:
// round to nearest even value
echo(round(7.5,0,PHP_ROUND_HALF_EVEN)); 8
echo "\n"; 7
// round to nearest odd value 7
echo(round(7.5,0,PHP_ROUND_HALF_ODD)); 8
echo "\n";
// round towards zero
echo(round(7.5,0,PHP_ROUND_HALF_DOWN));
echo "\n";
// round away from zero
echo(round(7.5,0,PHP_ROUND_HALF_UP));
?>
sqrt()
PHP provides us with a built-in function sqrt() which can be used to calculate
the square root of a number. The sqrt() function in PHP is used to calculate the square
root of a number.
Syntax:
float sqrt(value)
Parameters: This function accepts a single parameter $value. It is the number whose
square root you want to know.
Return Value: It returns a floating-point value which is the square root of the
argument $value passed to it.
Examples:
<?php Output:
echo sqrt(25).”<br>”; 5
echo sqrt(-25) .”<br>”; NaN
echo sqrt(0.09) .”<br>”; 0.3
echo sqrt(0) .”<br>”; 0
?>
Parameter:
The format parameter in the date() function specifies the format of returned
date and time.
The format parameter of the date() function is a string that can contain
multiple characters allowing to generate the dates in various formats. Date-
related formatting characters that are commonly used in the format string:
d: Represents day of the month; two digits with leading zeros (01 or 31).
D: Represents day of the week in the text as an abbreviation (Mon to Sun).
m: Represents month in numbers with leading zeros (01 or 12).
M: Represents month in text, abbreviated (Jan to Dec).
y: Represents year in two digits (08 or 14).
Y: Represents year in four digits (2008 or 2014).
h: Represents hour in 12-hour format with leading zeros (01 to 12).
H: Represents hour in 24-hour format with leading zeros (00 to 23).
i: Represents minutes with leading zeros (00 to 59).
s: Represents seconds with leading zeros (00 to 59).
a: Represents lowercase antemeridian and post meridian (am or pm).
A: Represents uppercase antemeridian and post meridian (AM or PM).
The parts of the date can be separated by inserting other characters, like
hyphens (-), dots (.), slashes (/), or spaces to add additional visual formatting.
The timestamp is an optional parameter, if it is not included then the current
date and time will be used.
Example:
<?php Today's date is :05/12/2017
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;?>
checkdate()
The checkdate() function is a built-in function in PHP which checks the validity
of the date passed in the arguments. It accepts the date in the format mm/dd/yyyy.
The function returns a boolean value. It returns true if the date is a valid one, else it
returns false.
Syntax:
checkdate ( $month, $day, $year )
Parameters:
1. $month – This parameter specifies the month. The month has to be in between 1 to
12 for a valid date.
2. $day – This parameter specifies the day. The day can be in range 1-31 depending
on the month entered for it to be a valid day. In case of a leap year, the day is in
range 1-29 and for a non-leap year the day is in range 1-28.
3. $year – This parameter specifies the year. The year has to be in range 1-32767
inclusive depending on the $month and $day for it to be a valid date.
Return Value: The function returns a boolean value. It returns true if the passed date
is a valid date. It returns false if the passed date is not a valid one.
Examples:
Example:
<?php Output:
// PHP program to demonstrate the checkdate() function bool(true)
$month = 12; bool(false)
$day = 31;
$year = 2017;
// returns a boolean value after validation of date
var_dump(checkdate($month, $day, $year));
var_dump(checkdate(2, 29, 2017));
?>
getdate()
The getdate() function is an inbuilt function in PHP which is used to get date/time
information of the current local date/time.
Syntax:
getdate($timestamp)
Parameters: The getdate() function accepts one parameter and it is described below:
$timestamp: It is an optional parameter which specifies an integer unix
timestamp. Default is the current local time (time()).
Return Value:
The function returns an array with information of the timestamp.
[seconds] – seconds
[minutes] – minutes
[hours] – hours
[mday] – day of the month
[wday] – day of the week
[mon] – month
[year] – year
[yday] – day of the year
[weekday] – name of the weekday
[month] – name of the month
[0] – seconds since Unix Epoch
Example:
<?php Output:
// PHP program to illustrate Array
// getdate() function (
[seconds] => 40
print_r(getdate()); [minutes] => 25
?> [hours] => 6
[mday] => 3
[wday] => 2
[mon] => 7
[year] => 2018
[yday] => 183
[weekday] => Tuesday
[month] => July
[0] => 1530599140)
mktime()
The mktime() function is an inbuilt function in PHP which is used to return the
Unix timestamp for a date. The timestamp returns a long integer containing the
number of seconds between the Unix Epoch (January 1, 1970, 00:00:00 GMT) and the
time specified. The hour, minute, second, month, day and year are sent as parameters
to the mktime() function and it returns an integer Unix timestamp on success and
False on error.
Syntax:
int mktime( $hour, $minute, $second, $month, $day, $year, $is_dst)
Parameters:
$hour: It is an optional parameter which specifies the hour.
$minute: It is an optional parameter which specifies the minute.
$second: It is an optional parameter which specifies the second.
$month: It is an optional parameter which specifies the month.
$day: It is an optional parameter which specifies the day.
$year: It is an optional parameter which specifies the year.
$is_dst: It is an optional parameter which can be set to 1 if the time is during
daylight savings time (DST), or 0 if it is not.
Return Value: This function returns an integer Unix timestamp on success and False
on error.
Exceptions:
PHP 5.3.0 version throws an E_DEPRECATED error if the is_dst parameter is
used.
The mktime() function throws a E_NOTICE on every call to a date/time if the
time zone is not valid.
Example:
<?php Output:
// Using mktime() function to know the complete date Dec-01-2021
time()
The time() function is a built-in function in PHP which returns the current time
measured in the number of seconds since the Unix Epoch. The number of seconds can
be converted to the current date using date() function in PHP.
Syntax:
int time()
Parameter: This function does not accepts any parameters as shown above.
Return Value: This function returns the current time measured in the number of
seconds since the Unix Epoch.
<?php
Output:
// PHP program to demonstrate the use of current
// date since Unix Epoch 2022-07-12
// variable to store the current time in seconds
$currentTimeinSeconds = time();
// converts the time in seconds to current date
$currentDate = date('Y-m-d', $currentTimeinSeconds);
// prints the current date
echo ($currentDate);
?>
Here, the bold parts in the URL denote the GET parameters and the italic parts
denote 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.
Example:
<?php
error_reporting(0);
if( $_GET["name"] || $_GET["weight"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['weight']. " kgs in weight.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Weight:<input type="text" name="weight" />
<input type="submit" />
</form>
</body>
</html>
Advantages:
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.
GET requests can be cached and GET requests to remain in the browser history.
GET requests can be bookmarked.
Disadvantages:
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.
POST Method: In the POST method, the data is sent to the server as a package in a
separate communication with the processing script. Data sent through the POST
method will not be visible in the URL.
Example:
<?php
error_reporting(0);
if( $_POST["name"] || $_POST["weight"] )
{
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['weight']. " kgs in weight.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Weight: <input type = "text" name = "weight" />
<input type = "submit" />
</form>
</body>
</html>
Advantages:
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.
Disadvantages:
Since the data sent by the POST method is not visible in the URL, so it is not
possible to bookmark the page with a specific query.
POST requests are never cached
POST requests do not remain in the browser history.
Difference between HTTP GET and HTTP POST
HTTP GET HTTP POST
In GET method we can not send large In POST method large amount of data can
amount of data rather limited data is sent be sent because the request parameter is
because the request parameter is appended appended into the body.
into the URL.
GET request is comparatively better than POST request is comparatively less better
Post so it is used more than the than Get so it is used less than the Get
Post request. request.
GET request is comparatively less secure POST request is comparatively more
because the data is exposed in the URL bar. secure because the data is not exposed in
the URL bar.
Request made through GET method are Request made through POST method is
stored in Browser history. not stored in Browser history.
GET method request can be saved as POST method request can not be saved as
bookmark in browser. bookmark in browser.
Request made through GET method are Request made through POST method are
stored in cache memory of Browser. not stored in cache memory of Browser.
Data passed through GET method can be Data passed through POST method can
easily stolen by attackers. not be easily stolen by attackers.
In GET method only ASCII characters are In POST method all types of data is
allowed. allowed.
2.2 Files: Include, File Parsing, Directories, File Uploading, File
Downloading
PHP allows us to create various functions and various elements that are used
multiple times in multiple pages. Scripting the same function in multiple pages is a
task of great effort and would consume lots of time & also impacts the execution of the
code. This can be avoided if we follow and use the concept of file inclusion which helps
us to include various files including text or codes into a single program which saves
the effort of writing the full function or code multiple times. This also provides
another advantage. If we want to change any code then instead of editing it in all the
files, we just need to edit the source file and all codes will be automatically changed.
There are two functions that help us to include files:
include():
This function is used to copy all the contents of a file called within the function,
text wise into a file from which it is called. This happens before the server executes the
code.
Example:
even.php
<?php
// File to be included
echo "Hello from PHP";
?>
Now, try to include this file into another PHP file index.php file, will see the
contents of both the file are shown.
index.php
<?php
include("even.php");
echo "<br>Above File is Included"
?>
require():
The require() function performs same as the include() function. It also takes
the file that is required and copies the whole code into the file from where the
require() function is called.
Now, if we try to include this file using require() function this file into a web
page we need to use a index.php file. We will see that the contents of both files are
shown.
index.php
<?php
require("even.php");
echo "<br>Above File is Required"
?>
include() vs require(): Both functions act as same and produce the same
results, but if by any chance a fatal error arises, then the difference comes to the
surface, which we will see following this example. Consider the following code:
<?php
include("even.php");
echo "<br>Above File is Included"
?>
Output: Now, if we don’t have a file named even.php, then in the case of the include(),
the following output will be shown with warnings about a missing file, but at least the
output will be shown from the index.php file:
Warning message in include() function
In the case of the require(), if the file PHP file is missing, a fatal error will rise
and no output is shown and the execution halts.
Warning message in require() function
This is the only difference. This also shows that require() function is better
than the include() function since the script should not continue executing if files are
missing or such an error is generated.
include() require()
The include() function does not stop the execution The require() function will stop the execution of
of the script even if any error occurs. the script when an error occurs.
The include() function does not give a fatal error. The require() function gives a fatal error
The include() function is mostly used when the file The require() function is mostly used when the
is not required and the application should continue file is mandatory for the application.
to execute its process when the file is not found.
504 – Web Services and Framework (TYBCA Sem-V)
The include() function will only produce a warning The require() will produce a fatal error
(E_WARNING) and the script will continue to (E_COMPILE_ERROR) along with the warning.
execute.
File Parsing
File handling is needed for any application. For some tasks to be done file needs
to be processed. File handling in PHP is similar as file handling is done by using any
programming language like C. PHP has many functions to work with normal files.
Those functions are:
fopen()
The fopen() function in PHP is an inbuilt function which is used to open a file or
an URL. It is used to bind a resource to a steam using a specific filename. The filename
and mode to be checked are sent as parameters to the fopen() function and it returns a
file pointer resource if a match is found and a False on failure. The error output can be
hidden by adding an ‘@’ in front of the function name.
Syntax:
resource fopen ( $file, $mode, $include_path, $context)
Parameters:
$file: It is a mandatory parameter which specifies the file.
$mode: It is a mandatory parameter which specifies the access type of the file
or stream.
It can have the following possible values:
“r”: It represents Read only. It starts at the beginning of the file.
“r+”: It represents Read/Write.It starts at the beginning of the file.
“w”: It represents Write only.It opens and clears the contents of file or
create a new file if it doesn’t exist.
“w+”: It represents Read/Write. It opens and clears the contents of file
or creates a new file if it doesn’t exist.
“a”: It represents Write only. It opens and writes to the end of the file or
creates a new file if it doesn’t exist.
“a+”: It represents Read/Write. It preserves the file’s content by writing
to the end of the file.
“x”: It represents Write only. It creates a new file and returns FALSE and
an error if the file already exists.
“x+”: It represents Read/Write.It creates a new file and returns FALSE
and an error if file already exists.
$include_path: It is an optional parameter which is set to 1 if you want to
search for the file in the include_path (Ex. php.ini).
fread()
The fread() function in PHP is an inbuilt function which reads up to length
bytes from the file pointer referenced by file from an open file. The fread() function
stops at the end of the file or when it reaches the specified length passed as a
parameter, whichever comes first. The file and the length which has to be read are
sent as parameters to the fread() function and it returns the read string on success, or
FALSE on failure.
Syntax:
string fread ( $file, $length )
Parameters:
$file: It is a mandatory parameter which specifies the file.
$length: It is a mandatory parameter which specifies the maximum number of
bytes to be read.
Return Value:
It returns the read string on success, or False on failure.
Exceptions:
Both binary data, like images and character data, can be written with this
function since fread() is binary-safe.
To get the contents of a file only into a string, use file_get_contents() as it has
much better performance than the code above.
Since systems running Windows differentiate between binary and text files, the
file must be opened with ‘b’ included in fopen() mode parameter.
fwrite()
The fwrite() function in PHP is an inbuilt function which is used to write to an
open file. The fwrite() function stops at the end of the file or when it reaches the
specified length passed as a parameter, whichever comes first. The file, string and the
length which has to be written are sent as parameters to the fwrite() function and it
returns the number of bytes written on success, or FALSE on failure.
Syntax:
fwrite(file, string, length)
Parameters:
1. file : It is a mandatory parameter which specifies the file.
2. string : It is a mandatory parameter which specifies the string to be written.
3. length : It is an optional parameter which specifies the maximum number of
bytes to be written.
Return Value: It returns the number of bytes written on success, or False on failure.
Exceptions:
1. Both binary data, like images and character data, can be written with this
function since fwrite() is binary-safe.
2. If writing operation is performed twice to the file pointer, then the data will be
appended to the end of the file content.
fclose()
The fclose() function in PHP is an inbuilt function which is used to close a file
which is pointed by an open file pointer. The fclose() function returns true on success
and false on failure. It takes the file as an argument which has to be closed and closes
that file.
Syntax:
bool fclose( $file )
Parameters: The fclose() function in PHP accepts only one parameter which is $file.
This parameter specifies the file which has to be closed.
Return Value: It returns true on success and false on failure.
Errors And Exception:
1. A file has to be closed first using the fclose() function if it has been written via
fwrite() function and you have to read the contents of the file.
2. The fclose() function in PHP doesn’t works for remote files.It only works on
files which are accessible by the server’s filesystem.
Common examples for all file parsing commands are as follows:
Example:
<?php Output:
// Opening a file using fopen() File does not exist!
// function in read only mode
$myfile = fopen("test.txt", "r") or die("File does not exist!");
?>
<?php Output:
// Opening a file using fopen() One line from test,txt file will be
// function in read/write mode printed
$myfile = fopen("test.txt", 'r+')
or die("File does not exist!");
$pointer = fgets($myfile);
echo $pointer;
fclose($myfile);
?>
<?php Output:
// Opening a file using fopen() function Complete test.txt file get printed
// in read mode along with b flag
$myfile = fopen("test.txt", "rb");
$contents = fread($myfile, filesize($myfile));
fclose($myfile);
print $contents;
?>
Unlike PHP mkdir() returning boolean value, this function will return resource
data as like as fopen(), mysql_query() and etc. After receiving the resource identifier
returned by this function, then only we can progress with the subsequent steps to
read, rewind, or close the required directory with the reference of this resource id.
Otherwise, a PHP error will occur for indicating to the user, that the resource id
is not valid.
Step 2: Reading Directory Content
For performing this step, we need to call readdir() function recursively until the
directory handle reaches the end of the directory. For that, we need to specify the
resource-id returned while invoking opendir(), indicated as directory handle.
PHP readdir() will return string data on each iteration of the loop, and this
string will be the name of each item stored in the directory with its corresponding
extension. For example,
<?php
$directory_handle = opendir($directory_path);
And, thereby executing the above code sample, we can list the content of a
directory as expected.
Closing Directory Link
Once the directory link is opened to perform a set of dependent operations like
reading directory content, we need to close this link after completing the related
functionalities required. For example,
<?php
$directory_handle = opendir($directory_path);
...
...
closedir($directory_handle);
?>
Removing Directory
For removing the entire directory, PHP provides a function named
as rmdir() which accepts the same set of arguments, as mkdir().
These are, the $directory_path and $context(Optional) as stated below.
<?php
rmdir($directory_path, $mode, $recursive_flag, $context); ?>
But, this function will remove the directory, if and only if it is empty. For
removing the non-empty directory, we need to create a user define function that
recursively calls unlink() function to remove each file stored in the directory to be
deleted.
Finding and Changing the Current Working Directory
It is unlikely that a web application will be able to perform all of its file related
tasks in a single directory. For this reason, it is vital to be able to both find out the
current working directory, and change to another directory from within a PHP script.
The current working directory can be identified using the getCwd() function:
<?php
$current_dir = getCwd();
echo "Current directory is $current_dir";
?>
To make this example work, the target directory which is backup and the
source file i.e. "example.txt" has to exist already; otherwise PHP will generate an error.
Note: In addition to a file-select field the upload form must use the HTTP post method
and must contain an enctype="multipart/form-data" attribute. This attribute ensures
that the form data is encoded as mulitpart MIME data — which is required for
uploading the large quantities of binary data such as image, audio, video, etc.
Step 2: Processing the uploaded file
Here's the complete code of our "upload-manager.php" file. It will store the
uploaded file in a "upload" folder on permanent basis as well as implement some basic
security check like file type and file size to ensure that users upload the correct file
type and within the allowed limit.
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Check if file was uploaded without errors
if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0)
{
$allowed_ext = array("jpg" => "image/jpg",
"jpeg" => "image/jpeg",
"gif" => "image/gif",
"png" => "image/png");
$file_name = $_FILES["photo"]["name"];
$file_type = $_FILES["photo"]["type"];
$file_size = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed_ext))
die("Error: Please select a valid file format.");
// Verify file size - 2MB max
$maxsize = 2 * 1024 * 1024;
if ($file_size > $maxsize)
die("Error: File size is larger than the allowed limit of 2MB");
// Verify MYME type of the file
if (in_array($file_type, $allowed_ext))
{
// Check whether file exists before uploading it
if (file_exists("upload/".$_FILES["photo"]["name"]))
echo $_FILES["photo"]["name"]." already exists!";
else
{
move_uploaded_file($_FILES["photo"]["tmp_name"],
"uploads/".$_FILES["photo"]["name"]);
echo "Your file uploaded successfully.";
}
}
else
{
echo "Error: Please try again!";
}
}
else
{
echo "Error: ". $_FILES["photo"]["error"];
}
}
?>
Once the form is submitted information about the uploaded file can be accessed via
PHP superglobal array called $_FILES. For example, our upload form contains a file
select field called photo (i.e. name="photo"), if any user uploaded a file using this field,
we can obtains its details like the name, type, size, temporary name or any error
occurred while attempting the upload via the $_FILES["photo"] associative array, like
this:
move_uploaded_file() function
The move_uploaded_file() function is used to move the uploaded file to a new location.
It moves the file only if it is uploaded through the POST request.
Syntax:
First Configure the php.ini File by ensure that PHP is configured to allow file
uploads. In your php.ini file, search for the file_uploads directive, and set it
to On i.e. file_uploads = On
2.3 Cookies and Sessions, Send Email
Session
session refers to a frame of communication between two medium. A PHP
session is used to store data on a server rather than the computer of the user. Session
identifiers or SID is a unique number which is used to identify every user in a session
based environment. The SID is used to link the user with his information on the server
like posts, emails etc.
Although cookies are also used for storing user related data, they have serious
security issues because cookies are stored on the user’s computer and thus they are
open to attackers to easily modify the content of the cookie. Addition of harmful data
by the attackers in the cookie may result in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies send the user
data each time the user views a page. Every time the browser requests a URL to the
server, all the cookie data for that website is automatically sent to the server within
the request.
Below are different steps involved in PHP sessions:
Starting a PHP Session: The first step is to start up a session. After a session is
started, session variables can be created to store information. The
PHP session_start() function is used to begin a new session.It also creates a
new session ID for the user.
Below is the PHP code to start a new session:
<?php
session_start();
?>
Important Points
1. The session IDs are randomly generated by the PHP engine .
2. The session data is stored on the server therefore it doesn’t have to be sent
with every browser request.
3. The session_start() function needs to be called at the beginning of the page,
before any output is generated by the script in the browser.
Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server
stores on the client computer. They are typically used to keep track of information
such as a username that the site can retrieve to personalize the page when the user
visits the website next time. A cookie can only be read from the domain that it has
been issued from. Cookies are usually set in an HTTP header but JavaScript can also
set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The
setcookie() function needs to be called prior to any output generated by the script
otherwise the cookie will not be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters:
Name: It is used to set the name of the cookie.
Value: It is used to set the value of the cookie.
Expire: It is used to set the expiry timestamp of the cookie after which the
cookie can’t be accessed.
Path: It is used to specify the path on the server for which the cookie will be
available.
Domain: It is used to specify the domain for which the cookie is available.
Security: It is used to indicate that the cookie should be sent only if a secure
HTTPS connection exists.
Below are some operations that can be performed on Cookies in PHP:
Creating Cookies: Creating a cookie named Auction_Item and assigning the
value Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours *
60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
<!DOCTYPE html>
Output:
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60); Cookie creation in PHP
?>
<html>
<body>
<?php
echo "cookie is created." ?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>
Note: Only the name argument in the setcookie() function is mandatory. To skip an
argument, the argument can be replaced by an empty string(“”).
Checking Whether a Cookie Is Set Or Not: It is always advisable to check whether a
cookie is set or not before accessing its value. Therefore to check whether a cookie is
set or not, the PHP isset() function is used. To check whether a cookie “Auction_Item”
is set or not, the isset() function is executed as follows:
Example: This example describes checking whether the cookie is set or not.
<!DOCTYPE html> Output:
<?php Checking for the cookie to be set
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 *
60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Accessing Cookie Values: For accessing a cookie value, the PHP $_COOKIE
superglobal variable is used. It is an associative array that contains a record of all the
cookies values sent by the browser in the current request. The records are stored as a
list where the cookie name is used as the key. To access a cookie named
“Auction_Item”, the following code can be executed.
Example: This example describes accessing & modifying the cookie value.
<!DOCTYPE html> Output:
<?php Accessing the Cookie value
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 *
60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Deleting Cookies: The setcookie() function can be used to delete a cookie. For
deleting a cookie, the setcookie() function is called by passing the cookie name and
other arguments or empty strings but however this time, the expiration date is
required to be set in the past. To delete a cookie named “Auction_Item”, the following
code can be executed.
Example: This example describes the deletion of the cookie value.
<!DOCTYPE html>
Output:
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60); Deleting the Cookie
?>
<html>
<body>
<?php
setcookie("Auction_Item", "", time() - 60);
?>
<?php
echo "cookie is deleted"
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Important Points:
If the expiration time of the cookie is set to 0 or omitted, the cookie will expire
at the end of the session i.e. when the browser closes.
The same path, domain, and other arguments should be passed that were used
to create the cookie in order to ensure that the correct cookie is deleted.
Send Mail in PHP
PHP is a server side scripting language that is enriched with various utilities
required. Mailing is one of the server side utilities that is required in most of the web
servers today. Mailing is used for advertisement, account recovery, subscription etc.
In order to send mails in PHP, one can use the mail() method.
Syntax:
bool mail(to , subject , message , additional_headers , additional_parameters)
Parameters:
to: Specifies the email id of the recipient(s). Multiple email ids can be passed
using commas
subject: Specifies the subject of the mail.
message: Specifies the message to be sent.
Summary:
Using mail() method one can send various types of mails such as standards,
html mail.
The mail() method opens the SMTP socket, attempts to send the mail, closes the
socket thus is a secure option.
mail() method should not be used for bulk mailing as it is not very cost-
efficient.
The mail() method only checks for parameter or network failure, thus a success
in the mail() method doesn’t guarantee that the intended person will receive
the mail.
2.4 Forms: Creating, Handling, Validation of Forms, PHP Filters,
JSON Parsing
Form Creating
HTML forms are used to send the user information to the server and returns
the result back to the browser. For example, if you want to get the details of visitors to
your website, and send them good thoughts, you can collect the user information by
means of form processing. Then, the information can be validated either at the client-
side or on the server-side. The final result is sent to the client through the respective
web browser. To create a HTML form, form tag should be used.
Attributes of Form Tag:
Attribute Description
name or id It specifies the name of the form and is used to identify individual forms.
Action It specifies the location to which the form data has to be sent when the form is
submitted.
method It specifies the HTTP method that is to be used when the form is submitted. The
possible values are get and post. If get method is used, the form data are visible to
the users in the url. Default HTTP method is get.
encType It specifies the encryption type for the form data when the form is submitted.
Novalidate It implies the server not to verify the form data when the form is submitted.
Controls used in forms: Form processing contains a set of controls through which
the client and server can communicate and share information. The controls used in
forms are:
Textbox: Textbox allows the user to provide single-line input, which can be used
for getting values such as names, search menu and etc.
Textarea: Textarea allows the user to provide multi-line input, which can be used
for getting values such as an address, message etc.
DropDown: Dropdown or combobox allows the user to provide select a value from
a list of values.
Radio Buttons: Radio buttons allow the user to select only one option from the
given set of options.
CheckBox: Checkbox allows the user to select multiple options from the set of
given options.
Buttons: Buttons are the clickable controls that can be used to submit the form.
All the form controls given above is designed by using the input tag based on
the type attribute of the tag. In the below script, when the form is submitted, no event
handling mechanism is done. Event handling refers to the process done while the form
is submitted. These event handling mechanisms can be done by using javaScript or
PHP. However, JavaScript provides only client-side validation. Hence, we can use PHP
for form processing.
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
<form id="form1" method="post">
FirstName:
<input type="text" name="firstname" required/>
<br>
<br>
LastName
<input type="text" name="lastname" required/>
<br>
<br>
Address
<input type="text" name="address" required/>
<br>
<br>
Email Address:
<input type="email" name="emailaddress" required/>
<br>
<br>
Password:
<input type="password" name="password" required/>
<br>
<br>
<input type="submit" value="Submit”/>
</form>
</body>
</html>
Form Handling
Form validation is done to ensure that the user has provided the relevant
information. Basic validation can be done using HTML elements. For example, in the
above script, the email address text box is having a type value as “email”, which
prevents the user from entering the incorrect value for an email. Every form field in
the above script is followed by a required attribute, which will intimate the user not to
leave any field empty before submitting the form. PHP methods and arrays used in
form processing are:
isset(): This function is used to determine whether the variable or a form control
is having a value or not.
$_GET[]: It is used the retrieve the information from the form control through the
parameters sent in the URL. It takes the attribute given in the url as the
parameter.
$_POST[]: It is used the retrieve the information from the form control through
the HTTP POST method. IT takes name attribute of corresponding form control as
the parameter.
$_REQUEST[]: It is used to retrieve an information while using a database.
Form Processing using PHP: Above HTML script is rewritten using the above
mentioned functions and array. The rewritten script validates all the form fields and if
there are no errors, it displays the received information in a tabular form.
Example:
<?php
if (isset($_POST['submit']))
{
if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) ||
(!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) ||
(!isset($_POST['password'])) || (!isset($_POST['gender'])))
{
$error = "*" . "Please fill all the required fields";
}
else
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
$gender = $_POST['gender'];
}
}
?>
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
<h1>Form Processing using PHP</h1>
<fieldset>
<form id="form1" method="post" action="form.php">
<?php
if (isset($_POST['submit']))
{
if (isset($error))
{
{
echo"<h1>INPUT RECEIVED</h1><br>";
echo "<table border='1'>";
echo "<thead>";
echo "<th>Parameter</th>";
echo "<th>Value</th>";
echo "</thead>";
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>".$firstname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Last Name</td>";
echo "<td>".$lastname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Address</td>";
echo "<td>".$address."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Email Address</td>";
echo "<td>" .$emailaddress."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Password</td>";
echo "<td>".$password."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Gender</td>";
echo "<td>".$gender."</td>";
echo "</tr>";
echo "</table>";
}
}
?>
</body>
</html>
Note: When the PHP and HTML are coded in a single file, the file should be saved as
PHP. In the form, the value for the action parameter should be a file name.
Form Validation
Data validation is an integral part of web development, especially while
working with forms where the user first enters their personal data and then sends
that to the database. Data sent in an invalid format can cause DBMS security problems.
Hackers often use SQL injections to insert malicious SQL commands into the database.
SQL injections can even destroy the database once inserted. An HTML form contains
various input fields such as text box, checkbox, radio buttons, submit button, and
checklist, etc. These input fields need to be validated, which ensures that the user has
entered information in all the required fields and also validates that the information
provided by the user is valid and correct.
There is no guarantee that the information provided by the user is always
correct. PHP validates the data at the server-side, which is submitted by HTML form.
You need to validate a few things: Empty String, Validate String, Validate Numbers,
Validate Email, Validate URL. Input length etc.
PHP Filters
PHP Filter is an extension that filters the data by either sanitizing or validating
it. It plays a crucial role in security of a website, especially useful when the data
originates from unknown or foreign sources, like user supplied input. For example
data from a HTML form.
There are mainly two types of filters which are listed below:
Validation: is used to validate or check if the data meets certain qualifications or
not. For example, passing in FILTER_VALIDATE_URL will determine if the data is a
valid url, but it will not change the existing data by itself.
Sanitization: unlike validation, sanitization will sanitize data so as to ensure that no
undesired characters by removing or altering the data. For example passing in
FILTER_SANITIZE_EMAIL will remove all the characters that are inappropriate for
an email address to contain. That said, it does not validate the data.
Example 1: PHP program to validate URL using FILTER_VALIDATE_URL filter.
<?php
// PHP program to validate URL
// Declare variable and initialize it to URL
$url = "https://www.geeksforgeeks.org";
// Use filter function to validate URL
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo("valid URL");
}
else {
echo("Invalid URL");
}
?>
}
else {
echo "Invalid Email";
}?>
Filter Functions: The filter function is used to filter the data coming from insecure
source.
filter_var(): Filters a specific variable
filter_var_array():Filters multiple variable i.e. array of variable
filter_has_var(): Check if the variable of specific input type exists or not
filter_id():helps to get filter id of the specified filter name
filter_list():Returns a list of supported filter name in the form of array.
filter_input():Gets an external variable and filters it if set to do so.
filter_input_array():same as filter_input() but here Gets multiple variables i.e.
array of variable and filters them if set to do so.
Predefined Filter Constants: There are many predefined filter constants which
are listed below:
Validate filter constants:
FILTER_VALIDATE_BOOLEAN: Validates a boolean
FILTER_VALIDATE_INT: Validates an integer
FILTER_VALIDATE_FLOAT: Validates a float
FILTER_VALIDATE_REGEXP: Validates a regular expression
FILTER_VALIDATE_IP: Validates an IP address
FILTER_VALIDATE_EMAIL: Validates an e-mail address
FILTER_VALIDATE_URL: Validates an URL
Sanitize filter constants:
FILTER_SANITIZE_EMAIL: Removes all illegal characters from an e-mail
address
FILTER_SANITIZE_ENCODED: Removes/Encodes special characters
FILTER_SANITIZE_MAGIC_QUOTES: Apply addslashes() function
FILTER_SANITIZE_NUMBER_FLOAT: Remove all characters, except digits, +-
and optionally
FILTER_SANITIZE_NUMBER_INT: Removes all characters except digits and + –
FILTER_SANITIZE_SPECIAL_CHARS: Removes special characters
FILTER_SANITIZE_FULL_SPECIAL_CHARS Encoding quotes can be disabled by
using FILTER_FLAG_NO_ENCODE_QUOTES.
FILTER_SANITIZE_STRING : Removes tags/special characters from a string
Peter_is_a_great_guy!
<?php
$string="Peter is a great guy!";
echo filter_var($string, FILTER_CALLBACK,
array("options"=>"strtoupper"));
?>
The output of the code will be:
JSON Parsing
PHP is a server-side scripting language used to process the data. JSON stands
for JavaScript object notation. JSON data is written as name/value pairs.
Syntax:
{
“Data”:[{
“key”:”value”,
“key”:value,
“key n “:”value”
},
...
...
{
“key”:”value”,
“key”:value,
“key n “:”value”
}]
}
Advantages:
JSON does not use an end tag.
JSON is a shorter format.
JSON is quicker to read and write.
JSON can use arrays.
Approach: Create a JSON file and save it as data.json. We have taken student data in
the file. The contents are as follows.
{
"customers": [
{
"name": "Andrew",
"email": "[email protected]",
"age": 62,
"countries": [
{
"name": "Italy",
"year": 1983
},
{
"name": "Canada",
"year": 1998
},
{
"name": "Germany",
"year": 2003
}
]
},
{
"name": "Sajal",
"email": "[email protected]",
"age": 65,
"countries": [
{
"name": "Belgium",
"year": 1994
},
{
"name": "Hungary",
"year": 2001
},
{
"name": "Chile",
"year": 2013
}
]
},
{
"name": "Adam",
"email": "[email protected]",
"age": 72,
"countries": [
{
"name": "France",
"year": 1988
},
{
"name": "Brazil",
"year": 1998
},
{
"name": "Poland",
"year": 2002
}
]
},
{
"name": "Monty",
"email": "[email protected]",
"age": 77,
"countries": [
{
"name": "Spain",
"year": 1982
},
{
"name": "Australia",
"year": 1996
},
{
"name": "Germany",
"year": 1987
}
]
}
]
}
file_get_contents() function
This function is used to read the file into PHP code.
Syntax:
file_get_contents(path, file_name)
file_name is the name of the file and path is the location to be checked.
Use json_decode() function to decode to JSON file into array to display it.
It is used to convert the JSON into an array.
Syntax:
json_decode($json_object, true)
Parameters
$json_object is the file object to be read.
Example
The following is the PHP code to parse JSON file.
<?php
$people_json = file_get_contents('data.json');
$decoded_json = json_decode($people_json, true);
$customers = $decoded_json['customers'];
foreach($customers as $customer) {
$name = $customer['name'];
$countries = $customer['countries'];
foreach($countries as $country) {
Output:
Andrew visited Italy in 1983.
Andrew visited Canada in 1998.
Andrew visited Germany in 2003.
Sajal visited Belgium in 1994.
Sajal visited Hungary in 2001.
Sajal visited Chile in 2013.
Adam visited France in 1988.
Adam visited Brazil in 1998.
Adam visited Poland in 2002.
Monty visited Spain in 1982.
Monty visited Australia in 1996.
Monty visited Germany in 1987.
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.
Creating Objects in PHP
Once you defined your class, then you can create as many objects as you like of
that class type. Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Here we have created three objects and these objects are independent of each
other and they will have their existence separately. Next we will see how to access
member function and process member variables.
Now you call another member functions to get the values set by in above
example.
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Constructor Functions
Constructor Functions are special type of functions which are called
automatically whenever an object is created. So we take full advantage of this
behaviour, by initializing many things through constructor functions.
PHP provides a special function called __construct() to define a constructor.
You can pass as many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will
initialize price and title for the book at the time of object creation.
function __construct( $par1, $par2 ) {
$this->title = $par1;
$this->price = $par2;
}
Now we don't need to call set function separately to set price and title. We can
initialize these two member variables at the time of object creation only. Check
following example below −
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );
/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Destructor
Like a constructor function you can define a destructor function using function
__destructor(). You can release all the resources with-in a destructor.
<?php Output
class MyClass The class "MyClass" was initiated!
{ The class "MyClass" was destroyed.
// Constructor The end of the file is reached.
public function __construct()
{
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
// Destructor
public function __destruct()
{
echo 'The class "' . __CLASS__ . '" was
destroyed.<br>';
}
}
// Create a new object
$obj = new MyClass;
// Destroy the object
unset($obj);
// Output a message at the end of the file
echo "The end of the file is reached.";
?>
Operator Description
^ It denotes the start of string.
$ It denotes the end of string.
. It denotes almost any single character.
() It denotes a group of expressions.
[] It finds a range of characters for example [xyz] means x, y or z .
[^] It finds the items which are not in range for example [^abc] means NOT a, b or c.
– (dash) It finds for character range within the given item range for example [a-z] means a through
z.
| (pipe) It is the logical OR for example x | y means x OR y.
? It denotes zero or one of preceding character or item range.
* It denotes zero or more of preceding character or item range.
+ It denotes one or more of preceding character or item range.
{n} It denotes exactly n times of preceding character or item range for example n{2}.
{n, } It denotes atleast n times of preceding character or item range for example n{2, }.
{n, m} It denotes atleast n but not more than m times for example n{2, 4} means 2 to 4 of n.
\ It denotes the escape character.
Shorthand Character Sets: Let us look into some shorthand character sets available.
Shorthand Meaning
\s Matches space characters like space, newline or tab.
\d Matches any digit from 0 to 9.
\w Matches word characters including all lower and upper case letters, digits and
underscore.
Predefined functions or Regex library: Let us look into the quick cheat sheet of pre-
defined functions for regular expressions in PHP. PHP provides the programmers to
many useful functions to work with regular expressions.
The below listed in-built functions are case-sensitive.
Function Definition
preg_match() This function searches for a specific pattern against some string. It returns true if
pattern exists and false otherwise.
preg_match_all() This function searches for all the occurrences of string pattern against the string.
This function is very useful for search and replace.
ereg_replace() This function searches for specific string pattern and replace the original string with
Note:
By default, regular expressions are case sensitive.
There is a difference between strings inside single quotes and strings inside
double quotes in PHP. The former are treated literally, whereas for the strings
inside double-quotes means the content of the variable is printed instead of
just printing their names.
preg_match () function
This function searches string for pattern, returns true if pattern exists,
otherwise returns false. Usually search starts from beginning of subject string. The
optional parameter offset is used to specify the position from where to start the
search.
Syntax:
int preg_match( $pattern, $input, $matches, $flags, $offset )
Parameters:
pattern: This parameter holds the pattern to search for, as a string.
input: This parameter holds the input string.
matches: If matches exists then it contains results of search. The $matches[0]
will contain the text that matched full pattern, $matches[1] will contain the text
that matched the first captured parenthesized subpattern, and so on.
flags: The flags can be following flags:
PREG_OFFSET_CAPTURE: If this flag is passed, for every match the
append string offset will be returned.
PREG_UNMATCHED_AS_NULL: If this flag is passed, subpatterns which
are not matched reports as NULL; otherwise they reports as empty
string.
offset: Usually, search starts from the beginning of input string. This optional
parameter offset is used to specify the place from where to start the search (in
bytes).
Return value: It returns true if pattern exists, otherwise false.
Example : Validating String with alphabets
$name = $_POST ["Name"];
if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
} else {
echo $name;
}
preg_match_all () function
The preg_match_all() function searches for all the matches to a regular
expression in a string.
Unlike the preg_match() function that stops searching when it finds the first
match, the preg_match_all() function continues searching for the next matches till the
end of the string.
Syntax
preg_match_all($pattern, $subject, &$matches = null, $flags = 0, $offset = 0):
int|false|null
Parameters:
$pattern is a string that specifies the pattern to search.
$subject is the input string to match the pattern.
$matches is a multi-dimensional array that contains all the matches.
$flags is a combination of the
flags PREG_PATTERN_ORDER, PREG_SET_ORDER, PREG_OFFSET_CAPTURE,
and PREG_UNMATCHED_AS_NULL. By default,
the $flags is PREG_PATTERN_ORDER if you skip it.
$offset is an integer that specifies the position from which the search starts. By
default, the preg_match_all() function starts searching from the beginning of the
string.
The preg_match_all() function returns a number that specifies the number of full
pattern matches. If there is no match, the preg_match_all() function returns zero. In
case of failure, it returns false.
1) Using the PHP preg_match_all() function to match numbers in a string
example
<?php Output:
$pattern = '/\d+/'; Array
$str = 'PHP 1.0 released in 1995'; (
if (preg_match_all($pattern, $str, $matches)) { [0] => Array
print_r($matches); (
[0] => 1
}
[1] => 0
[2] => 1995
)
)
The $matches array contains the full pattern matches in the first element and
the capturing groups in the second element. It returns the same result as if you use
the PREG_PATTERN_ORDER flag.
If you want to group each set of matches in an array element, you can use
the PREG_SET_ORDER flag.
<?php Output:
Array
$pattern = '/\b([a-zA-Z])\w+\b/'; (
$str = 'Alice, Bob, Peter'; [0] => Array
(
if (preg_match_all($pattern, $str, $matches, [0] => Alice
PREG_SET_ORDER)) { [1] => A
print_r($matches); )
} [1] => Array
(
[0] => Bob
[1] => B
)
[2] => Array
(
[0] => Peter
[1] => P
)
)
(
if (preg_match_all($pattern, $str, $matches, [0] => Array
PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) { (
print_r($matches); [0] => Alice
} [1] => 0
)
[1] => Array
(
[0] => A
[1] => 0
)
)
[1] => Array
(
[0] => Array
(
[0] => Bob
[1] => 7
)
[1] => Array
(
[0] => B
[1] => 7
)
)
[2] => Array
(
[0] => Array
(
[0] => Peter
[1] => 12
)
[1] => Array
(
[0] => P
[1] => 12
)
)
)
preg_replace() funation
The preg_replace() function searches for matches and replaces them with a
pattern.
Syntax:
preg_replace($pattern, $replacement, $subject, $limit = -1, &$count = null): string
Parameters:
$pattern is a regular expression to match.
$replacement is a string to replace. It may contain the backreferences.
$subject is a string to search and replace.
$limit is the maximum possible replacement for the pattern. By default, it is -1,
which is unlimited.
$count stores the number of replacements.
If the $subject matches the $pattern, the preg_replace() function replaces the
match with the $replacement and returns it.
1) Using the PHP preg_replace() function to change the date format
The following example uses the preg_replace() function to change the date
string from dd-mm-yyyy to mm-dd-yyyy format:
<?php Output:
$pattern = '/(\d{2})-(\d{2})-(\d{4})/'; 12-25-2021
$replacement = '\2-\1-\3';
$str = '25-12-2021';
echo preg_replace($pattern, $replacement, $str);
?>
The following regular expression matches the date in the dd-mm-yyyy format:
/(\d{2})-(\d{2})-(\d{4})/
It consists of three capturing groups for day (\d{2}), month (\d{2}), and
year (\d{4}).
The replacement string contains three backreferences \2 for the second
capturing group which is month, \1 for the first capturing group which is day,
and \3 for the third capturing group which is the year.
Therefore, the preg_replace() changes the format of the date from dd-mm-
yyyy to mm-dd-yyyy.
2) Using the PHP preg_replace() function to remove the excessive whitespace
<?php
Output:
$str = 'PHP is awesome';
echo preg_replace('/\s\s+/', ' ', $str); PHP is awesome
?>
Output:
May 5, 2020