0% found this document useful (0 votes)
6 views55 pages

2 PHP

The document provides an overview of PHP functions related to mathematical operations and date/time handling. It details various built-in functions such as abs(), ceil(), floor(), fmod(), max(), min(), pow(), rand(), round(), sqrt(), date(), and checkdate(), along with their syntax and examples. These functions are essential for performing calculations and managing date formats in PHP programming.

Uploaded by

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

2 PHP

The document provides an overview of PHP functions related to mathematical operations and date/time handling. It details various built-in functions such as abs(), ceil(), floor(), fmod(), max(), min(), pow(), rand(), round(), sqrt(), date(), and checkdate(), along with their syntax and examples. These functions are essential for performing calculations and managing date formats in PHP programming.

Uploaded by

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

504 – Web Services and Framework (TYBCA Sem-V)

Unit – 2 PHP Functions


2.1 Math Functions, Date and Time Functions, GET and POST
Methods
As you know PHP is a sever side script language and is used for creating
dynamic web pages. PHP provides a number of built-in math functions which help in
performing several operations while dealing with mathematical data. It has nice
support for mathematical processing. No installation is required to use these
functions.
Math Functions
 abs()
This function takes negative value as input and returns the absolute (positive) value of
a integer or float number.
Syntax:
number abs ( mixed $number )

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 )

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 38


504 – Web Services and Framework (TYBCA Sem-V)

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)

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 39


504 – Web Services and Framework (TYBCA Sem-V)

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 )

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 40


504 – Web Services and Framework (TYBCA Sem-V)

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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 41


504 – Web Services and Framework (TYBCA Sem-V)

echo "By using sqrt function Your number is : ".$num; is : 25


?>
<?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
echo "By using sqrt function Your number is : ".$num; is : -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
echo "By using sqrt function Your number is : ".$num; is : -NAN
?>

 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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 42


504 – Web Services and Framework (TYBCA Sem-V)

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
?>

Date and Time Functions


 date()
The PHP date() function converts timestamp to a more readable date and time
format. The computer stores dates and times in a format called UNIX Timestamp,
which measures time as a number of seconds since the beginning of the Unix epoch
(midnight Greenwich Mean Time on January 1, 1970, i.e. January 1, 1970, 00:00:00
GMT ). Since this is an impractical format for humans to read, PHP converts timestamp
to a format that is readable and more understandable to humans.
Syntax:
date(format, timestamp)

Parameter:

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 43


504 – Web Services and Framework (TYBCA Sem-V)

 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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 44


504 – Web Services and Framework (TYBCA Sem-V)

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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 45


504 – Web Services and Framework (TYBCA Sem-V)

// 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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 46


504 – Web Services and Framework (TYBCA Sem-V)

echo date("M-d-Y", mktime(0, 0, 0, 12, 1, 2021)) . Jan-09-2022


"<br>";
// Using mktime() function to know the
// complete date for an out-of-range input
echo date("M-d-Y", mktime(0, 0, 0, 12, 40, 2022));
?>

 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);
?>

Get and Post Methods


The Hypertext Transfer Protocol (HTTP) is designed to enable communications
between clients and servers. HTTP works as a request-response protocol between a
client and server. A web browser may be the client, and an application on a computer
that hosts a website may be the server. A client (browser) submits an HTTP request to
the server; then the server returns a response to the client. The response contains
status information about the request and may also contain the requested content.
There are 2 HTTP request methods:
 GET: Requests data from a specified resource.
 POST: Submits data to be processed to a specified resource.
GET Method: In the GET method, the data is sent as URL parameters that are usually
strings of name and value pairs separated by ampersands (&). In general, a URL with
GET data will look like this:
Example:
http://www.example.com/action.php?name=Sam&weight=55

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 47


504 – Web Services and Framework (TYBCA Sem-V)

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"] )

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 48


504 – Web Services and Framework (TYBCA Sem-V)

{
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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 49


504 – Web Services and Framework (TYBCA Sem-V)

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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 50


504 – Web Services and Framework (TYBCA Sem-V)

Example: This example is using the require() function in PHP.


 even.php
<?php
// File to be included
echo "Hello GeeksforGeeks";
?>

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).

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 52


504 – Web Services and Framework (TYBCA Sem-V)

 $context: It is an optional parameter which is used to set the behavior of the


stream.
Return Value:
It returns a file pointer resource on success, or FALSE on error.
Exceptions:
 When writing to a text file, the correct line-ending character should be used
based on the platform.For example Unix systems use \n, Windows systems use
\r\n, and Macintosh systems use \r as the line ending character.
 It is recommended to use the ‘b’ flag when opening files with fopen().
 An error of level E_WARNING is generated if the open fails.
 When safe mode is enabled, PHP checks whether the directory in which the
script is operating has the same UID (owner) as the script that is being
executed.
 If you are unsure whether filename is a file or a directory, you may need to use
the is_dir() function before calling fopen() since fopen() function may also
succeed when filename is a directory.

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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 53


504 – Web Services and Framework (TYBCA Sem-V)

 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:

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 54


504 – Web Services and Framework (TYBCA Sem-V)

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;
?>

Directory Handling in PHP


PHP includes a set of directory functions to deal with the operations, like,
listing directory contents, and create/ open/ delete specified directory and etc. These
basic functions are listed below.
 mkdir(): To make new directory.
 opendir(): To open directory.
 readdir(): To read from a directory after opening it.
 closedir(): To close directory with resource-id returned while opening.
 rmdir(): To remove directory.
Creating Directory
For creating a new directory using PHP programming script, mkdir() function is
used, and, the usage of this function is as follows.
<?php
mkdir($directory_path, $mode, $recursive_flag, $context);
?>
This function accepts four arguments as specified. Among them, the first
argument is mandatory, whereas, the remaining set of arguments is optional.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 55


504 – Web Services and Framework (TYBCA Sem-V)

 $directory_path: By specifying either relative and absolute path, a new


directory will be created in such location if any, otherwise, will return an error
indicating that there are no such locations.
 $mode: The mode parameter accepts octal values on which the accessibility of
the newly created directory depends.
 $recursive: This parameter is a flag and has values either true or false, that
allow or refuse to create nested directories further.
 $context: As similar as we have with PHP unlink() having a stream for
specifying protocols and etc.
This function will return boolean data, that is, true on successful
execution, false otherwise.
Listing the Directory Content
For listing the contents of a directory, we require two of the above-listed PHP
directory functions, these are, opendir() and readdir(). There are two steps in
directory listing using the PHP program.
 Step 1: Opening the directory.
 Step 2: Reading content to be listed one by one using a PHP loop.
Step 1: Opening Directory Link
As its name, opendir() function is used to perform this step. And, it has two
arguments, one is compulsory for specifying the path of the directory, and the other is
optional, expecting stream context if any. The syntax will be,
<?php
opendir($directory_path, $context);
?>

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);

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 56


504 – Web Services and Framework (TYBCA Sem-V)

while ($directory_item = readdir($directory_handle)) {


echo $directory_item . "<br>";
}
?>

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";
?>

The current working directory can be changed using


the chdir() function. chdir() takes as the only argument the path of the new directory:
<?php
$current_dir = getCwd();

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 57


504 – Web Services and Framework (TYBCA Sem-V)

echo "Current directory is $current_dir <br>";


chdir ("/tmp");
$current_dir = getCwd();
echo "Current directory is now $current_dir <br>";
?>

Listing Files in a Directory


The files in a directory can be read using the PHP scandir() function. scandir() takes
two arguments. The first argument is the path the directory to be scanned. The second
optional argument specifies how the directory listing is to be sorted. If the argument is
1 the listing is sorted reverse-alphabetically. If the argument is omitted or set to 0 the
list is sorted alphabetically:
<?php
chdir ("/tmp");
$current_dir = getCwd();
echo "Current directory is now $current_dir";
$array = scandir(".", 1);
print_r($array);
?>

Copying Files from One Location to Another


You can copy a file from one location to another by calling PHP copy() function
with the file's source and destination paths as arguments. If the destination file
already exists it'll be overwritten. Here's an example which creates a copy of
"example.txt" file inside backup folder.
Example
<?php
// Source file path
$file = "example.txt";
// Destination file path
$newfile = "backup/example.txt";
// Check the existence of file
if(file_exists($file)){
// Attempt to copy file
if(copy($file, $newfile)){
echo "File copied successfully.";
} else{
echo "ERROR: File could not be copied.";
}
} else{
echo "ERROR: File does not exist.";?>

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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 58


504 – Web Services and Framework (TYBCA Sem-V)

File Uploading and Downloading


PHP allow you to upload any type of a file i.e. image, binary or text
files.etc..,PHP has one in built global variable i.e. $_FILES, it contains all information
about file.By the help of $_FILES global variable, we can get file name, file type, file
size and temparary file name associated with file.
 $_FILES['filename']['name'] - returns file name.
 $_FILES['filename']['type'] - returns MIME type of the file.
 $_FILES['filename']['size'] - returns size of the file (in bytes).
 $_FILES['filename']['tmp_name'] - returns temporary file name of the file
which was stored on the server.
Step 1: Creating an HTML form to upload the file
Below is the HTML source code for the HTML form for uploading the file to the
server. In the HTML <form> tag, we are using “enctype=’multipart/form-data” which
is an encoding type that allows files to be sent through a POST method. Without this
encoding, the files cannot be sent through the POST method. We must use this enctype
if you want to allow users to upload a file through a form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form action="file-upload-manager.php" method="post" enctype="multipart/form-data">
<!--multipart/form-data ensures that form data is going to be encoded as MIME data-->
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<!-- name of the input fields are going to be used in our php script-->
<p><strong>Note:</strong>Only .jpg, .jpeg, .png formats allowed to a max size of 2MB.</p>
</form>
</body>
</html>

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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 59


504 – Web Services and Framework (TYBCA Sem-V)

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"];
}

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 60


504 – Web Services and Framework (TYBCA Sem-V)

}
?>

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:

 $_FILES["photo"]["name"] — This array value specifies the original name of the


file, including the file extension. It doesn't include the file path.
 $_FILES["photo"]["type"] — This array value specifies the MIME type of the file.
 $_FILES["photo"]["size"] — This array value specifies the file size, in bytes.
 $_FILES["photo"]["tmp_name"] — This array value specifies the temporary
name including full path that is assigned to the file once it has been uploaded to
the server.
 $_FILES["photo"]["error"] — This array value specifies error or status code
associated with the file upload, e.g. it will be 0, if there is no error.

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:

move_uploaded_file ( string $filename , string $destination )

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.

How are sessions better than cookies?

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 61


504 – Web Services and Framework (TYBCA Sem-V)

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();
?>

 Storing Session Data: Session data in key-value pairs using


the $_SESSION[] superglobal array.The stored data can be accessed during
lifetime of a session.
Below is the PHP code to store a session with two session variables Rollnumber
and Name:
<?php
session_start();
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";
?>

 Accessing Session Data: Data stored in sessions can be easily accessed by


firstly calling session_start() and then by passing the corresponding key to
the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber
and Name is shown below:
<?php Output:
session_start(); The Name of the student is :Ajay
echo 'The Name of the student is :' . The Roll number of the student is :11
$_SESSION["Name"] . '<br>';
echo 'The Roll number of the student is :' .
$_SESSION["Rollnumber"] . '<br>';
?>

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 62


504 – Web Services and Framework (TYBCA Sem-V)

 Destroying Certain Session Data: To delete only a certain session data,the


unset feature can be used with the corresponding session variable in
the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative
session array:
<?php
session_start();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}
?>

 Destroying Complete Session: The session_destroy() function is used to


completely destroy a session. The session_destroy() function does not require
any argument.
<?php
session_start();
session_destroy();
?>

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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 63


504 – Web Services and Framework (TYBCA Sem-V)

 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>

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 64


504 – Web Services and Framework (TYBCA Sem-V)

<?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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 65


504 – Web Services and Framework (TYBCA Sem-V)

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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 66


504 – Web Services and Framework (TYBCA Sem-V)

 additional-headers(Optional): This is an optional parameter that can create


multiple header elements such as From (Specifies the sender), CC (Specifies the
CC/Carbon Copy recipients), BCC (Specifies the BCC/Blind Carbon Copy
Recipients. Note: In order to add multiple header parameters one must use
‘\r\n’.
 additional-parameters(Optional): This is another optional parameter and can
be passed as an extension to the additional headers. This can specify a set of
flags that are used as the sendmail_path configuration settings.
Return Type: This method returns TRUE if mail was sent successfully and FALSE on
Failure.
Examples:
<?php Output :
$to = "[email protected]"; Your Mail is sent successfully.
$sub = "Generic Mail";
$msg="Hello Geek! This is a generic email.";
if (mail($to,$sub,$msg))
echo "Your Mail is sent successfully.";
else
echo "Your Mail is not sent. Try Again.";
?>

Sending a Mail with Additional Options


<?php
Output :
$to = "[email protected]";
$sub = "Generic Mail"; Your Mail is sent successfully.
$msg = "Hello Geek! This is a generic email.";
$headers = 'From: [email protected]' . "\r\n"
.'CC: [email protected]';
if(mail($to,$sub,$msg,$headers))
echo "Your Mail is sent successfully.";
else
echo "Your Mail is not sent. Try Again.";
?>

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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 67


504 – Web Services and Framework (TYBCA Sem-V)

 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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 68


504 – Web Services and Framework (TYBCA Sem-V)

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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 69


504 – Web Services and Framework (TYBCA Sem-V)

 $_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))
{

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 70


504 – Web Services and Framework (TYBCA Sem-V)

echo "<p style='color:red;'>"


. $error . "</p>";
}
}
?>
FirstName:
<input type="text" name="firstname"/>
<span style="color:red;">*</span>
<br>
<br>
Last Name:
<input type="text" name="lastname"/>
<span style="color:red;">*</span>
<br>
<br>
Address:
<input type="text" name="address"/>
<span style="color:red;">*</span>
<br>
<br>
Email:
<input type="email" name="emailaddress"/>
<span style="color:red;">*</span>
<br>
<br>
Password:
<input type="password" name="password"/>
<span style="color:red;">*</span>
<br>
<br>
Gender:
<input type="radio"
value="Male"
name="gender"> Male
<input type="radio"
value="Female"
name="gender">Female
<br>
<br>
<input type="submit" value="Submit" name="submit" />
</form>
</fieldset>
<?php
if(isset($_POST['submit']))
{
if(!isset($error))

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 71


504 – Web Services and Framework (TYBCA Sem-V)

{
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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 72


504 – Web Services and Framework (TYBCA Sem-V)

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");
}
?>

Example 2: PHP program to validate email using FILTER_VALIDATE_EMAIL filter.


<?php
// PHP program to validate email
// Declare variable and initialize it to email
$email = "[email protected]";
// Use filter function to validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email";

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 73


504 – Web Services and Framework (TYBCA Sem-V)

}
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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 74


504 – Web Services and Framework (TYBCA Sem-V)

 FILTER_SANITIZE_STRIPPED : Alias of FILTER_SANITIZE_STRING


 FILTER_SANITIZE_URL: Removes all illegal character from s URL
<?php
if(isset($_POST['email'])) {
echofilter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
echo"<br/><br/>";
}
if(isset($_POST['homepage'])) {
echofilter_var($_POST['homepage'], FILTER_SANITIZE_URL);
echo"<br/><br/>";
}
?>
<form name="form1"method="post"action="form-sanitize.php">
Email Address: <br/>
<input type="text"name="email"value="<?php echo $_POST['email']; ?>"size="50"/><br/><br/>
Home Page: <br/>
<input type="text"name="homepage"value="<?php echo $_POST['homepage']; ?>"size="50"/><br/>
<br/>
<input type="submit"/>
</form>

 Other filter constants:


 FILTER_UNSAFE_RAW :Do nothing, optionally strip/encode special characters
 FILTER_CALLBACK :Call a user-defined function to filter data
Example
<?php
function convertSpace($string)
{
return str_replace(" ", "_", $string);
}
$string = "Peter is a great guy!";
echo filter_var($string, FILTER_CALLBACK,
array("options"=>"convertSpace"));
?>
The output of the code will be:

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:

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 75


504 – Web Services and Framework (TYBCA Sem-V)

PETER IS A GREAT GUY!

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
},

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 76


504 – Web Services and Framework (TYBCA Sem-V)

{
"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",

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 77


504 – Web Services and Framework (TYBCA Sem-V)

"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) {

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 78


504 – Web Services and Framework (TYBCA Sem-V)

echo $name.' visited '.$country['name'].' in '.$country['year'].'.'.'<br>';


}}?>

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.

2.5 Classes and Objects in PHP


Object-oriented programming is a programming model organized
around Object rather than the actions and data rather than logic. Basic
terminology of OOP to revise are as follows:

 Class − This is a programmer-defined data type, which includes local


functions as well as local data. You can think of a class as a template for
making many instances of the same kind (or class) of object.
 Object − An individual instance of the data structure defined by a class. You
define a class once and then make many objects that belong to it. Objects are
also known as instance.
 Member Variable − These are the variables defined inside a class. This data
will be invisible to the outside of the class and can be accessed via member
functions. These variables are called attribute of the object once an object is
created.
 Member function − These are the function defined inside a class and are
used to access object data.
 Inheritance − When a class is defined by inheriting existing function of a
parent class then it is called inheritance. Here child class will inherit all or
few member functions and variables of a parent class.
 Parent class − A class that is inherited from by another class. This is also
called a base class or super class.
 Child Class − A class that inherits from another class. This is also called a
subclass or derived class.
 Polymorphism − This is an object oriented concept where same function can
be used for different purposes. For example function name will remain same
but it take different number of arguments and can do different task.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 79


504 – Web Services and Framework (TYBCA Sem-V)

 Overloading − a type of polymorphism in which some or all of operators


have different implementations depending on the types of their arguments.
Similarly functions can also be overloaded with different implementation.
 Data Abstraction − Any representation of data in which the implementation
details are hidden (abstracted).
 Encapsulation − refers to a concept where we encapsulate all the data and
member functions together to form an object.
 Constructor − refers to a special type of function which will be called
automatically whenever there is an object formation from a class.
 Destructor – refers to a special type of function which will be called
automatically whenever an object is deleted or goes out of scope.

Defining PHP Classes


The general form for defining a new class in PHP is as follows −
<?php
class phpClass {
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}?>

Here is the description of each line −


 The special form class, followed by the name of the class that you want to define.
 A set of braces enclosing any number of variable declarations and function
definitions.
 Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a
constant value.
 Function definitions look much like standalone PHP functions but are local to the
class and will be used to set and access object data.
Example
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 80


504 – Web Services and Framework (TYBCA Sem-V)

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.

Calling Member Functions


After creating your objects, you will be able to call member functions related to
that object. One member function will be able to process member variable of related
object only.
Following example shows how to set title and prices for the three books by
calling member functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

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();

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 81


504 – Web Services and Framework (TYBCA Sem-V)

$maths->getPrice();

This will produce the following result −


Physics for High School
Advanced Chemistry
Algebra
10
15
7

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();

This will produce the following result −


Physics for High School
Advanced Chemistry
Algebra
10
15
7

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 82


504 – Web Services and Framework (TYBCA Sem-V)

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.";
?>

2.6 Regular Expressions and Exception Handling


Regular Expression
Regular expressions commonly known as a regex (regexes) are a sequence of
characters describing a special search pattern in the form of text string. They are
basically used in programming world algorithms for matching some loosely defined
patterns to achieve some relevant tasks. Some times regexes are understood as a mini
programming language with a pattern notation which allows the users to parse text
strings. The exact sequence of characters are unpredictable beforehand, so the regex
helps in fetching the required strings based on a pattern definition.
Regular Expression is a compact way of describing a string pattern that
matches a particular amount of text. As you know, PHP is an open-source language
commonly used for website creation, it provides regular expression functions as an
important tool. Like PHP, many other programming languages have their own
implementation of regular expressions. This is the same with other applications also,
which have their own support of regexes having various syntaxes. Many available
modern languages and tools apply regexes on very large files and strings. Let us look
into some of the advantages and uses of regular expressions in our applications.
Advantages and uses of Regular expressions:

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 83


504 – Web Services and Framework (TYBCA Sem-V)

 Regular expressions help in validation of text strings which are of programmer’s


interest.
 It offers a powerful tool for analyzing, searching a pattern and modifying the text
data.
 It helps in searching specific string pattern and extracting matching results in a
flexible manner.
 It helps in parsing text files looking for a defined sequence of characters for
further analysis or data manipulation.
 With the help of in-built regexes functions, easy and simple solutions are provided
for identifying patterns.
 It effectively saves a lot of development time, which are in search of specific string
pattern.
 It helps in important user information validations like email address, phone
numbers and IP address.
 It helps in highlighting special keywords in a file based on search result or input.
 It helps in identifying specific template tags and replacing those data with the
actual data as per the requirement.
 Regexes are very useful for creation of HTML template system recognizing tags.
 Regexes are mostly used for browser detection, spam filtration, checking
password strength and form validations.
The following table shows some regular expressions and the corresponding string
which matches the regular expression pattern.
Regular Expression Matches
Geeks The string “Geeks”
^geeks The string which starts with “geeks”
geeks$ The string which have “geeks” at the end.
^geeks$ The string where “geeks” is alone on a string.
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any letter which is NOT a uppercase letter
(gif|png) Either “gif” or “png”
[a-z]+ One or more lowercase letters
^[a-zA-Z0-9]{1, }$ Any word with at least one number or one letter
([ax])([by]) ab, ay, xb, xy
[^A-Za-z0-9] Any symbol other than a letter or other than number
([A-Z]{3}|[0-9]{5}) Matches three letters or five numbers
Note: Complex search patterns can be created by applying some basic regular
expression rules. Even many arithmetic operators like +, ^, – are used by regular
expressions for creating little complex patterns.
Operators in Regular Expression:

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 84


504 – Web Services and Framework (TYBCA Sem-V)

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.

Special Character Classes in Regular Expressions:


Special Character Meaning
\n It denotes a new line.
\r It denotes a carriage return.
\t It denotes a tab.
\v It denotes a vertical tab.
\f It denotes a form feed.
\xxx It denotes octal character xxx.
\xhh It denotes hex character hh.

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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 85


504 – Web Services and Framework (TYBCA Sem-V)

the replacement string, if found.


eregi_replace() The function behaves like ereg_replace() provided the search for pattern is not case
sensitive.
preg_replace() This function behaves like ereg_replace() function provided the regular expressions
can be used in the pattern and replacement strings.
preg_split() The function behaves like the PHP split() function. It splits the string by regular
expressions as its parameters.
preg_grep() This function searches all elements which matches the regular expression pattern
and returns the output array.
preg_quote() This function takes string and quotes in front of every character which matches the
regular expression.
ereg() This function searches for a string which is specified by a pattern and returns true if
found, otherwise returns false.
eregi() This function behaves like ereg() function provided the search is not case sensitive.

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.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 86


504 – Web Services and Framework (TYBCA Sem-V)

 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;
}

Example : Validating numeric


$mobileno = $_POST ["Mobile_no"];
if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
echo $mobileno;
}

Example: Validating Email


$email = $_POST ["Email"];
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
if (!preg_match ($pattern, $email) ){
$ErrMsg = "Email is not valid.";
echo $ErrMsg;
} else {
echo "Your valid email address is: " .$email;
}

Example: Validate URL


$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$websiteURL)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}

 preg_match_all () function
The preg_match_all() function searches for all the matches to a regular
expression in a string.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 87


504 – Web Services and Framework (TYBCA Sem-V)

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
)
)

2) Using the preg_match_all() function with flags parameters


<?php Output:
$pattern = '/\b([a-zA-Z])\w+\b/'; Array
$str = 'Alice, Bob, Peter'; (
if (preg_match_all($pattern, $str, $matches)) { [0] => Array
print_r($matches); (
} [0] => Alice
[1] => Bob

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 88


504 – Web Services and Framework (TYBCA Sem-V)

[2] => Peter


)
[1] => Array
(
[0] => A
[1] => B
[2] => P
)
)

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
)
)

The $flags can also be:


 PREG_OFFSET_CAPTURE returns the offset of the match together with the
matched string.
 PREG_UNMATCHED_AS_NULL returns NULL instead of an empty string if no
match is found for the subpatterns a.k.a capturing groups.
<?php Output:
Array
$pattern = '/\b([a-zA-Z])\w+\b/'; (
$str = 'Alice, Bob, Peter'; [0] => Array

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 89


504 – Web Services and Framework (TYBCA Sem-V)

(
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

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 90


504 – Web Services and Framework (TYBCA Sem-V)

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
?>

The pattern /\s\s+/ matches one or more spaces.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 91


504 – Web Services and Framework (TYBCA Sem-V)

PHP preg_replace() function with arrays


The preg_replace() function also accepts the $pattern, $replacement,
and $subject as arrays:
preg_replace(string|array $pattern, string|array $replacement, string|array $subject,
int $limit = -1, int &$count = null): string|array|null
If both $pattern and $replacement are arrays and $subject is a string,
the preg_replace() function will replace each pattern in the $pattern array with the
replacement in the $replacement array.
If the $replacement array has fewer elements than the $pattern array,
the preg_replace() function wil replace extra patterns with an empty string.
If the $subject is an array, the preg_replace() function searches and replaces
each string in the array and returns the result as an array.
Example:
<?php
$date = 'May 29, 2020';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1} 5,$3';

//display the result returned by preg_replace


echo preg_replace($pattern, $replacement, $date);
?>

Output:
May 5, 2020

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 92

You might also like