PHP Nirali Publi

Download as pdf or txt
Download as pdf or txt
You are on page 1of 130

COMPUTER ENGINEERING AND

INFORMATION TECHNOLOGY GROUP

WEB BASED APPLICATION


DEVELOPMENT WITH PHP

PRASHANT D. SOMWANSHI
Mrs. MANI A. SHPOKHAARKAR
Mrs. MRUN AL
P. FATAN GARE

DiaaKnen an

Scanned with CamScanner


4,1 History and Advantages of PHP, Syntax of PHP.
4,2 Variables, Data Types, Expressions and Operators, Constants.
1.3 Decision Making Control Statements - if, if-else, Nested if, switch, break and continue Statement.
1,4 Loop Control Structures - while, do-while, for and foreach.

2.1 Creating and Manipulating Array, Types of Arrays - Indexed, Associative and Multi-Dimensional Arrays.
2.2 Extracting Data from Arrays, Implode, Explode, and Array Flip.
2.3 Traversing Arrays
2.4 Function and its Types - User Defined Function, Variable Function and Anonymous Function.
2.5 Operations on String and String Function : str_world_count(), strlen(), strrev(), strops(), str_replace(),
ucwords(), strtoupper(), striolower(), stremp)().
2.6 Basic Graphics Concepts, Creating Images, Images with Text, Scaling Images, Creation of PDF
Document.

3.1 Creating Classes and Objects.


3.2 Constructor and Destructor.
3.3 Inheritance, Overloading and Overriding, Cloning Object.
3.4 Introspection, Serialization.

4.1 Creating a Webpage using GUI Components, Browser Role - GET and POST Methods, Server Role.
4.2 Form Controls: Textbox, Textarea, Radiobutton, Checkbox, List, Buttons.
4.3. Working with multiple Forms:
- A Web Page having Many Forms.
- AForm having Multiple Submit Buttons.
4.4 Web Page Validation.
45 Cookies - Use of Cookies, Attributes of Cookies, Create Cookies, Modify Cookies Value, and Delet
Cookies.
4.6 Session - Use of Session, Start Session, Get Session Variables, Destroy Session.
4.7 Sending E-mail.

5.1 Introduction to MySQL - Create a Database.


5.2 Connecting to a MySQL Database: MySQL Database Server from PHP.
5.3 Database Operations: Insert Data, Retrieving the Query Result.
5.4 Update and Delete Operations on Table Data.

Scanned with CamScanner


i 1,0 Introduction
| 4.4 History, Advantages and Syntax of PHP
1.1.1. History of PHP
1.1.2 Advantages and Disadvantagesof PHP
1.1.3 of PHP
44.4 a Run Program using XAMPP Server 15
1.2 Variables 1.
1.2.1 Data Types
1.2.2 Expressions and Operators
1.2.2.1 Expressions 1
1.2.2.2 Operators
1.2.3 Operator Precedence and Associatively 1
1.2.4 Constants 1.1
1.3 Decision making Control Statements /
1.3.1 if Statement 1
1.3.2 if-else Statement
| 1.3.3 Nested
if Statement 1.21
1.3.4 switch Statement 1.22
1.3.5 break Statement 24
1,3.6 continue Statement 1 25
1.4 Loop and Control Structures 1.26
1.4.1 while Loop 1.27
| 1.4.2 do while Loop 1.28
1.4.3 for Loop 1.28
1.4.4 foreach Loop 1:20
‘ Practice Questions 130

2.0 Introduction
2 1 /
2.1 Creating and Manipulating Array
21
2.1.1 Types of Arrays
a2
2.1.1.1 Indexed Array
22
Btls Associative Array
22
2.1.1.3 Multi-Dimensional Array
2.2 Extracting Data from Arrays 23
a8
2.2.1 Implode
222 Explode 2.4
2.2.3 Array Flip -
* aa
23 Traversing Arrays 26

2.4 Function and its Types


z
2
oh

2.4.1
©

1 Defining
a Function 2
©

24.1.3 2
+

Function Arguments
24.14 Returning Values
2
2
rh
Fr,"4 . 2.4.1.5 Function Body 2.13
24.2 Function Types 213
2.4.2.1 User Defined Functions 242
2.4.2.2 Variable Function 213

2.4.2.3 Anonymous Function (Lambda Function) 2.14


2.6 Operations on String and String Functions 2.14
2.5.1 String Functions/String Operations 2.17
2.5.1.1 str_word_count() DA17
2.5.1.2 strlen() 2.17
2.5.1.3 strrev() 2.18
2.5.1.4 strpos() 2.18
2.5.1.5 — strrpos() 2.18
2.5.1.6 str_replace() 2.18

2.5.1.7 ucwords() 2.19


2.5.1.8 strtoupper() 2.20
2.5.1.9 strtolower() 2.20
2.20
2.5.1.10 stremp()
2.6 Basic Graphics Concepts azo
Creating Images 2.21
2.6.1
2.6.2 Images with Text a
2.22
2.6.3 Scaling Images
Creation of PDF Document 2.23
2.6.4
2.24
: Practice Questions

3.1
3.0 Introduction
3.2
3.1 Creating Classes and Objects
3.2
3.1.1 Creating Classes
a3
3.1.2 Creating Object
34
3.2 Constructor and Destructor
3.4
3.2.1 Constructor
3.6
3.2.2 Destructor
3.6
3.3 Inheritance
37
3.3.1 Method of Function Overloading 38
3.3.2 Method of Function Overriding ae
3.3.3 Cloning Object
3.10
3.4 Introspection
3.10
3.4.1 Examining Classes
3.11
3.4.2 Examining an Object 3.11
3.5 Serialization
é Practice Questions

4.1
4.0 Introduction
4.1 Creating a Webpage using GUI Components 42
Methods
4.1.1. Browser Role GET and POST
4.1.2 Server Role
4.2 Form Controls 45
4.2.1 Textbox
4.2.2 Textarea

Scanned with CamScanner


42.3 Radio Button
424 Checkbox
4.25 List
nt wi l
with iltiple Forms
44
a Page having Many Forms
43.2 Form having Multiple Submit Buttons

44 Web Page Validation


45 Cookies
45.1 Types of Cookies
4.5.2 Use of Cookies
45.3 Attribute of Cookies
454 Create Cookies
45.5 Modify Cookies Value
45.6 Delete Cookies
46 Session
4.6.1 Use of Session
46.2 Start Session
4.6.32 Get Session Variables
4.6.4 Destroy Session
Sending E-mail
Practice Questions

5.0 Introduction
5.1 Introduction to MySQL
5.1.1 Create a Database
5.2 Connecting to a MySQL Database
5.2.1 MySQL Database Server from PHP
5.2.1.1 mysqli_connect() Function
5.2.1.2 PDO::_ _construct() Function
5.3 Database Operations
5.3.1 Insert Data
5.3.2 Retrieving the Query Result
5.4 Update and Delete Operations on Tab
le Data
5.4.1 Update Data
5.4.2 Delete Data
Practice Questions
Write simple PHP program to solve the given expression.
Use relevant decision making control statement to solve the given problem.
=

Solve the given iterative problem using relevant loop statement.


=

To learn Web Based Application Development using PHP


To understand Basic Concepts of PHP
eee

To study History, Syntax, Data Types, Variables etc., in PHP


To learn Decision Making Control Statements in PHP
To study Loop Control Structures in PHP

At
A Web application is a computer software or program that performs some specific tasks at its client
by using a Web browser. The Web-based applications are also known as Web apps.
Web applications are usually based on the client-server architecture where the client input/request
data while the server stores and responds with result.
Fig. 1.1 shows concept of Web application. User/client triggers a request to the web server over
Web
the Internet, either through a web browser or the Application’s User Interface (API).
server.
server forwards this client/user request to the appropriate web application
the database or
The Web application server performs the requested task - such as querying
application server sends
processing the data - then generates the results of the requested data. Web
or processed data.
results to the web server with the requested information
then appears on the
Web server responds back to the client/user with the requested information that while user/client
user's display. In short, a Web application is a program that runs on a Web server
accesses it using Web browser.
Advantages of using Web-Based Applications:
1. Web-based apps are cross-platform and
universally accessible.
2. Web-based applications are highly
scalable.
3. Web-based apps deployment is easy, cost-
effective, and fast.
4. Web-based applications are easy to
Fig. 1.1: Concept of Web Application (App)
update and maintain. [1-1]

Scanned with CamScanner


Web Sased Application Development with PHF 12 Expressions and Control Statements in Pap
. Web applications use 2 combination of server-side scripts like PHP to handle the storage ss
retrieval of the information and client-side scripts like JavaScript and/or HIML to presen
information to users.
. A script is a set of programming instructions that is interpreted at runtime. A scripting language is a
language that interprets scripts at runtime.
e The purpose of the scripts is usually to enhance the performance or perform routine tasks for an
application. Server side scripts are interpreted on the server while client side scripts are interpreteg

e PHP is a server side script that is interpreted on the server while JavaScript is an example of a client
side script that is interpreted by the client browser. Both PHP and JavaScript can be embedded into
HIML pages.
« The development of a web application is similar in many ways to that of any other software system.
We have to find out what the users require, choose an appropriate software architecture, design and
build the overall framework and create all the necessary components, all the while testing the
ee ee geen ee nee Seems fo cheanging requirements
circumstances.
¢ PHP isa widely used open source language that is specifically used for web application development
and can be embedded within HTML PHPis a server-side scripting language that is used in Web-
based applications.
« PHP is ageneral-purpose programming

application development.
PHP is a recursive
acronym for “PHP: Hypertext Preprocessor’.
e PHP isan open source, server side programming
language. PHPis one of the most popular
scripting languages of the last couple of years
for developingweb application.
« PHP is an interpreted
language, ie there is no
need for compilation.
PHP files have extension
“php”. PHP is a server side scripting language
that is embedded in HTML It is used to manage
dynamic content, databases, session tracking,
even build entire e-commerce
sites.
* PHP is integrated with a number of popular
databases, including MySQL, PostgreSQL
Oracle, Sybase, Informix, and Microsoft SQL
Server.
¢ The basic architecture
of a PHP web application
and how the server handles the requests is E
shown in Fig 1.2. Fig. 12: Basic Architecture of PHP Web App

Features
of PHP:
1. Web Application Features: PHP is a programming language support most commonly used Web
application features like HTTP Cookie, Session, File Upload, etc.
2. CLI (Command Line Interface): PHP is commonly used to write Web applications to be integrated
to Web servers using the Common Gateway Interface (CGI). But PHP can also be used to write
standalone applications to be executed by the CLI (Command Line Interface).
3. Built-in Modules: The standard PHP build comes with many free and open source libraries
included as built-in modules for calendar dates handling, FTP protocol support, XML processing,
encryption and decryption, ODBC support, ZIP support, regular expression support, etc. —
4. Object-Oriented Programming (OOP): PHP supports object-oriented programming features
object, classes, object references, private and protected member variables and methods, abstract
and final classes and methods, constructors and destructors, interfaces, etc.

Wee Scanned with CamScanner


«iil
Web Based Application Development with PHP 1.3 Expressions and Control Statements In PHP

5. Pre-Compilation: PHP Web applications are usually deployed in source code, which will be
interpreted on-the-fly when Web requests arrive to the server. But PHP Web applications can also
be pre-compiled and deployed in executable format to speed-up Web requests response time.
6. Real Time Access Monitoring: PHP provides access logging by creating the summary of recent
accesses for the user.
7. File 1/0: PHP supports most commonly used file I/O features like local file and path management,
remote resource access using Internet protocols like HTTP and FTP.
aoe as

in this section we study history, syntax, advantages and disadvantages of PHP.


History of PHP
PHP was written in the C programming language by Rasmus Lerdorf in 1994 for use in monitoring
his online resume and related personal information. For this reason, PHP originally stood for
“Personal Home Page”.
Lerdorf combined PHP with his own Form Interpreter, releasing the combination publicly as PHP/FI
(generally referred to as PHP 2.0) on june 8, 1995.
Two programmers, Zeev Suraski and Andi Gutmans, rebuilt PHP's core, releasing the updated result
as PHP/FI 2.0 in 1997.
The acronym was formally changed to PHP: HyperText Preprocessor, at this time, this is an example
of a recursive acronym (where the acronym itself is in its own definition).
In 1998, PHP 3 was release d,
which was the first widely used version.
PHP 4 was released in May 2000, with a new core, known as the Zend Engine 1.0. PHP 4 featured
improved speed and reliability over PHP 3. In terms of features, PHP 4 added references, the Boolean
type, COM support on Windows, output buffering, many new array functions, expanded object-
oriented programming, inclusion of the PCRE library, and more. Maintenance releases of PHP 4 are
still available, primarily for security updates.
On July 13, 2004, PHP 5 was released, powered by the new Zend Engine II. PHP 5 included new
features such as improved support for object-oriented programming, the PHP Data Objects (PDO)
extension (which defines a lightweight and consistent interface for accessing databases), and
numerous performance enhancements.
On 2 November 2006, PHP S.2 was released, with native JSON support.
On 30 June 2009, PHP 5.3 was released, with Namespace support; late static bindings, jump label
(limitedgoto), closures, PHP archives (phar),garbage collectionfor circular _ references,
improved Windows support, sqlite3, mysqind as a replacement for libmysql as underlying library for
the extensions that work withMySQL, fileinfo as a replacement for mime_magic for
better MIME support, the Internationalization extension, and deprecation of ereg extension.
On 1 March 2012, PHP 5.4 was released with several improvements to existing features, performance
and reduced memory requirements. Removed items: register_globals, session_register(),
session_unregister().
On 20 June 2013, PHP 5.5 was released, with generators and finally blocks for exceptions
handling support.
On 28 August 2014, PHP 5.6 version is released which includes features like Constant expressions,
Default character encoding, pgsql async support, an interactive debugger phpdbg and so on.
On 3 December 2015 a new major PHP version was developed, which was numbered PHP7.0 PHP
version7 comes with features like Null coalescing operator, Scalar type declarations, Return type
declarations, Spaceship operator and many more.
On 1 December 2016 PHP 7.1 version was released with features like Nullable types, Asynchronous
signal handling, Class constant visibility, Symmetric array destructur and ing
so on.
On 30 November 2017 PHP 7.2 version was released with features like Abstract method overriding,
New object type etc.

Scanned with CamScanner


‘Web Based Application Development with PHP ed Expressions st Conte Sammars npg
December 2018 PHP 7.3 version was released with features like Abstract meioy
; On ding, Parameter type widening, Flexible heredoc and nomdoc syntares a0 oon 7
2019, offers to build eppliceriors
The latest version of PHP is 7.4 released on 28 Novemberizati
Hoe

ons and the coud


-%

: influences everything from the website and mobile to organ


nt
PEE] Advaand ag
Disa es
dvan tages of PHP
Advantages
of PHP:
1, Speed: It is relative fast since it uses much system resource.
2. Easy to Use/Simplicity: It uses C like syntax, so for those who are familiar with ©. it's very <2zy
for them to pick up and to create a website.
j 3, Stable: Since it is maintained by many developers, so when bugs are found, it can be quickly
fixed.
4. Platform Independent/Portability:
Can be run on many platforms, incuding Windows, Lior
and Mac, it’s easy for users to find hosting service providers.
5. Open Source: PHP is open source and free of cost. It can be downloaded (without any fee
anywhere and readily available to use for the development of web applications.
6. Built-in Database Connection Modules: We can connect to database easily using PHP, sims
many websites are data/content driven, so we will use database frequently. this will lergely
reduce the development time of web apps.
7. Powerful Library Support: We can easily find functional modules we need such 2s PDF, Grap=
ec
8. Flexibility: Because PHP is an embedded language, it is extremely flexible towards meeting the
needs of the developer.
9. Database Connectivity: The PHP based application can easily be loaded and connected to the
database. PHP support for many databases connectivity such 2s MySQL Oracle, DBZ
. PostgreSQL etc.
10. Speed-up Custom Web Application Development: Nowadays, PHP programmers have to writ
| web applicat based on complex
ions
requirements.
Disadvantages of PHP:
. chi AP iad is not that secure because of its open source, as the source code can be easily

2. Weak Type: Implicit conversion may surprise unwary programmers and lead to
bugs. For example, unexpected
the strings “1000” and “1e3” compare equal because implicitly
floating point numbers,
Pat -
3. Not Suitable for Large Web Applications: PHP programs/codes are
not very modular, PHP unable to handle ha
to rd
maintain since it j
/manage large numbers of applications.
4, Desktop Applications: Not good to create deskto
p applications,
5. Modifi cation Problem: PHP do not allow the change or modification in
doolinetane core behavior of the web

BREA syntax of pup


mn # A PHP script is executed on the server, and the
* A PHP script can be placed plain HTML result is sent back to the browser.
<?php and ends with ?>, anywhere in the document.A PHP progra mming
script starts with
<?php
// PHP code goes here.
?>
* The default
file extens .
PHP scripting code, lon for PHP files is “php”. A PHP file normally contains HTML tags and some
* Below, we have an example of a simple PHP file , with a PHP script that uses a built-in ;
if PHP function
“echo” 1 output the text “Hello World!” on a web page
echo
Web Based Application Development with PHP 15 Expressions
anc Contrei Statements in FEF

Example: First PHP program.


<!DOCTYPE html>
<html>
<body>
<hl>My first PHP page</h1>
<?php |
echo “Hello World!”;
a>
</body>
</html>
Output:
My first PHP page
Hello World!
PHP code can be included or embedded into web page in following ways:
1. SGML style<? php code... >>
2. ASPstyle<% php code. %>
3. Scriptstyle<script language = “php*> PHP Code... </script>
Step to Run Program using XAMPP Server
° XAMPP stands for Cross-Platform (X), Apache (A), MariaDB (M), PHP (P) and Peri (P| EAMPPis =
software distribution which provides the Apache web server, MySQL detabase (actually MariaDs).
PHP and Perl (as command-line executables and Apache modules) all in one packac=
AMPP server is available for Windows, MAC and Linux operating systems.
Follow the following steps to run PHP program using XAMPP server:
Step 1; Download the XAMPP server from the internet,
(https://www.apachefriends.org/download.html).
Step 2: Install the XAMPP software.
Step 3: Open and click on the start button that is in front of Apache text. |
|%
|j
i i ni
sie) ly
bene

>]

T1220
PM (Agacte] Stams change cetectet runmng

Step 4: Create php file in htdocs directory which is resides in xampp directory. [C-\xampp\htdocs].
Example: (first.php). The PHP echo statement is often used to output data to the screen.
<!DOCTYPE html>
<html>
<body>
<hl>My first PHP page</hl>
<?php
echo “Hello PHP";
?>
</body>
</html>
ee
Web Based Application Development with PHP 1.6 Expressions and Control Statements in Pup |
. j then open your browser
first
Step 5: searecil in .php
php /first htdocons addre
directory and the n '
type
bok ss bar and press Enter key.
a

Hello PHP
ae hs at aes, a —™®
ee i \ : “v

PHP variables are nothing but a nam in the memory. A variable is a named
container in a PHP script in which a data value can be stored.
The stored value can be referenced using the variable's name and changed (varied) as the script
proceeds/executes. ;
Variables in PHP are identifiers prefixed with a dollar sign ($). For example,
$name
$Age
$_ Address
$MAXIMUM_IMPACT ;
A variable may hold any type of value. There is no compile-time or runtime type checking on
variables. We can store any type of value in the same variable.
For example,
$a = "Hello";
$a = 12;
$a = array(10, 20, 3@);
Variable Declaration:
A variable is an identifier for a piece of data stored in memory during the program execution.
A variable starts with the $ sign, followed by the name of the variable.
Syntax: $variable;
For example: $PhoneNo;
Some rules for PHP variables declaration are given below:
. Avariable starts with the $ sign, followed by the name of the variable like $Sum.
Whee

. Avariable name must start with a letter or the underscore character (ay
. Avariable name cannot start with a number like 10RolINo.
. Avariable name can only contain alpha-numeric characters and underscores
(A-z, 0-9 and _).
wp

. Variable names are case-sensitive, ($RollNo and $rollNo are two different
variables).
6. PHP variable can be of any length and does not contain spaces.
Defining/Assigning Values to Variables:
A variable stores a value of any type such as string, number, array, object, resource and so on.
A variable is automatically declared in PHP when we assign
a value to it.
Assigning a value to a variable in PHP is accomplished
with the assignment operator (=), with the
variable on the left-h
and side and the expression to be evaluated on the right.
Syntax to define a variable in PHP is: $variable_name=
value;
For example: $EmpId=10;
$StudentName=“Vedant”;
Variable Variables:
. PHP allows us to use dynamic variable names, called variable variables. Variable variables are simply
variables whose names are dynamically created by
another variable's value.
Sometimes, it is convenient to be able to have variable variable names. That is, a variable name
which can be set and used dynamically. Value of existing variable is used as a name
of new variable.

ii
Scanned with CamScanner
rE

Web Based Application Development with PHP i Expressions and Control Statements In PHP

A variable variables takes the value of a variable and treats that as the name of a variable.
$a = ‘hello’; //hello is value of variable $a
¢¢a = ‘PHP’; //$($a) is equals to $(hello)
echo $hello; //$hello is PHP i.e. #hello is new variable with value ‘PHP’
Variable References:
e Variable reference is an alias (duplicate name) of existing variable.
¢ Avariable reference points to the same value as the variable that references it. In PHP we can create
reference to some variable.
For example,
$a = 5;
$b = &$a;
Here, $b is the reference variable or $b is an alias for the variable $a. $b is now another name for the
value that is stored in $a.
« Now, same value can be used by both the names.
echo $b;
$b = $b + 2;
echo $a;
Output:
7 ($b is lias of $q i.e. $q and $b are same variable).
« Wecan unset the variable by using unset function but the reference is still set.
unset ($a);
echo $b; // Output: 5
Variable Scope:
* Scope of variable is an area or part of program in which it is accessible/visible. In PHP, variables can
be declared anywhere in the script.
* Scope can be defined as, "the range of availability of a variable has to the program in which it is
declared". The scope of a variable is the part of the script where the variable can be referenced/used.
* There are four types of variable scope in PHP i.e., local, global, static and function parameter.
1. Local Scope:
e Avariable which is declared inside the function is called as local variable.
* Local variable has access or life only within that function. Local Variable cannot be accessed from
outside the function,
Example: For local scope.
<?php
ta = 4; // global scope, ga is a global varible
function assigna()
{
ga = @; // local variable $a

print "a inside function is Sa. 5

}
assigna();
print "a outside of function is $a. "3
?>
Output:
a inside function is 8.
a outside of function is 4.

Scanned with CamScanner


,
: E ressio ns and Control Statem
Ce
ent with PHP
Application Developm 2:
in ot he r la ng ua ge, in PHP we can'tc
Unlike
rovide local scope.
ee itiona | branch, or other type of block.
scope is a loop, cond
ssed
1 Scope:
are by de fa ul t gl ob al variables and can acce
cllaared outside function
ples dedec
eer can be accessed in any part of the program pk Fs inside the functio

using the ‘GLOBAL keyword.


on, these variables are accessed
ple: For global scope.

= 15;
= 20;
ction addit()

BAL $x; // global variable;

= 18; // global variable;

16 and y = 11
Variable: ;
ow that, when function ends then all the variables declared inside the function ar
ariables are those variables which can hold value when function called again.
variables are used only with the functions. These variables retain their value
ent calls
to a function.
n declare a variable to be static simply by placing the keyword static in front of
- The initialization of this variable is done only for the first call to function and no
ple: For static scope/variable.

on keep_track()

ATIC $count = @;
punt++;
int $count;
int "<br>";

ep_track();
ep_track();
ep_track();
Web Based Application Development with PHP 1.9 Expressions and Control Statements in PHP

4. Function Parameter:
e Function parameters are local, i.e. they are available only inside the function.
¢ Function parameters are declared after the function name and inside parentheses. They are declared
much like a typical variable.
Example: For function parameter.
<?php
// multiply a value by and return it to the caller
function multiply ($value)
{
$value = $value * 4;
return $value;
}
$retval = multiply (10);
Print “Return value is $retval\n";
?>
Output;
Return value is 408
PHP Pre-defined Variables:
* PHP automatically have some variables called pre-defined variables available anywhere in the
program. They are array variables and known as superglobals. These variables are $_ENV, $_GET,
$_POST, $ COOKIE, and $_SERVER, referred to as EGPCS.
* There is a setting in the configuration file (php.ini) called register_globals. The default value is OFF,
and it restricts how we can access some predefined variables. register_globals determine whether or
not to register the EGPCS variables as global variables.
¢ Regardless of the setting of the option register_globals, PHP creates following six global arrays that
contain the EGPCS information as given below:
az $_COOKIE: This global array contains any cookie values passed as part of the request, where the
keys of the array are the names of the cookies.
2. $_GET: This global array contains any parameters that are part of a GET request, where the keys
of the array are the names of the form parameters.
$_POST: This global array contains any parameters that are part of a POST request, where the
keys of the array are the names of the form parameters.
$_FILES: This global array contains information about any uploaded files.
$_SERVER: This global array contains useful information about the web server, as described in
the next section.
$_ENV: This global array contains the values of any environment variables, where the keys of the
array are the names of the environment variables.
$GLOBALS: Contains a reference to every variable which is currently available within the global
scope of the script. The keys of this array are the names of the global variables.
$_SERVER: This is an array containing information such as headers, paths, and script locations.
The entries in this array are created by the web server. There is no guarantee that every web
server will provide any of these.
2; $_SESSION: An associative array containing session variables available to the current script.

Data Types
* A data type is defined as, "a set of values and the allowable operations on those values”, The data type
determines the operations that we can perform on it.
* PHP supports eight primitive types as shown in Fig. 1.3.

a
Scanned with CamScanner
=

i Web Based Application Development with PHP 1.10 Expressions and Control Statements in Pup .

> Four Scalar Types: (integer, float, string and Boolean).


i e Two Compound Types: (2rray and object).
° Two Special Types: (resource and Null).
[oss ea]

Fig. 1.3: Data Types in PHP


1. Integers:
The integer data type is used to specify a numeric value without a fractional component. The range
.

of integers in PHP is equivalent to the range of the long data type in C.


¢ On 32-bit platforms, integer values can range from —2,147,483,648 to +2,147,483,647.
¢ Integers can be written in decimal, octal or hexadecimal If it is decimal, it is just the nurnber. If it is
octal, then number should precede with (zero) 0. If it is hexadecimal then precede with OX.
* PHP does not support unsigned integers. Integer size cam be determined using the constant
PHP_INT_SIZE.
¢ InPHP, is int() or is_integer() are used to test whether a value is an integer.
<?php
if(is_int($a))
{
echo”Number is an integer”;
}
?>
2. Floating Point Numbers:
Floating point numbers are real numbers, representing numeric values with decimal digits.
Usually,
this allows numbers between 1.7E - 308 and 17E + 308 with 15 digits of accuracy.
° PHP recognizes floating point numbers written in two different
formats:
(i) Common format: 3.14, 2.25.
(ii) Scientific format: 17.9€-3 // 17.8*1@-3, or @.@17.
* Use the is_float() function (or its is_real() alias) to test whether a value is a floating point number:
if (is_float($x))
{
// $x is a floating-point number
| }
3. Strings:
i} A string is a sequence of characters where a character is the same as a byte.
PHP only supports a 256
character set.
* String literals are delimited
by either single
or double quotes.
Example: For ‘Good’ and "Good" is same.

Scanned with CamScanner


Web Based Application Development with PHP 1.411 Expressions and Control Statements in PHP

e Variables are expanded within double quotes not within single quote.
$a="Good”;
echo “$a, morning \n”;
echo ’$a, morning’;
Output:
Good, morning
$a, morning
+ Useis_string() function to test whether the value is strin g or not.
if(is_string($x))
{
// $x is a string
}
4. Boolean:
* Boolean value can be either TRUE value or FALSE value. Both are case-insensitive.
For example,
<?php
$x = True; // assign the value TRUE to $x
?>
¢ In PHP, is_bool() function is used to test whether value is Boolean or not.
$x = True;
if(is_bool($xX))
{
// $x is boolean;
}
* In PHP, the following values are false:
The keyword false.
OO DG

The integer 0.
The floating-point value 0.0.
The empty string ("") and the string "0".
G8

An array with zero elements.


0

An object with no values or functions.


oOo

The NULL value.


5. Arrays:
* An array stores group of values under single variable name.In PHP array is a collection of the
different type of values.
* The values can be identified by position or some identifying name called as associative.
$5) =“array(“ AY; 8B? 9 °°C*95§
$b = array(‘First’ => ‘A’,
‘Second’ => ‘B’
‘Third’ «> *C”);
$a is indexed array and elements are recognized by index starting with 0.
ie. $a[@]="A”;
$a[1]="8";
$a[2]="C";
$b is associative array in which key and value both are given.
ie. $b[‘First?] = “A”;
$b[ “Second’?] = “B”;
Pee
4.12 Expressions and Control Statements in PHp
Web Based Application Development with PHP

$b[ ‘Third? ] = "CC";


foreach loop is most common in arrays.
ie. foreach ($a1 as $valuel)
{ echo “Hello, $al \n’;
}
. Objects:
PHP supports Object Oriented Programming (OOP). Objects are the special instances of the classes
that are created by user.
Object is a term used in association with classes, A class is a definition of a structures that contains
properties (variables) and methods (functions).
Classes are defined with the ‘class’ keyword. Once a class is defined, any number of objects can be
made from it with the ‘new’ keyword.
Objects properties and methods can be accessed with the -> construct.
Example: For objects in PHP.
<?php
class Person
{
public $name = ‘ ‘;
function name ($newname)
{
$this -> name = $newname;
}
yy

}
$p = new Person();
$p -> name(“Amar”);
echo “Hello $p->name”;
?>
Output:
Hello Amar
Use is_object() to test whether a value is an object.
if (is_object($x))
{
// $x is an object
}
Resources:

rons used for dealing with the outside world. Resources


are created and used by special
ons. For example, database connection function returns a resource which is used
to identify
that connection when you call the query and
close functions.
Their main benefit is that they're garbage collected when no longer in use.
When the last reference
to a resource value: goes away, , the extensi on that created the resource is c alled to free any memory,
close any connection, etc. for that resource.
For example,
$result = database_connect();
database_query ($result)
;
$result=“something”; // connection is closed.
Use me is_resource() function to test
whether a value is a resource.
if(is_resource($x) )

Scanned with CamScanner


| Web Based Application Development with PHP 1.14 -
Expressions and Control Statements in PHP

~$a Negation Opposite of $a.


$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication | Product of $a and $b. a
$a / $b Division Quotient of $a and $b..
$a % $b Modulus Remainder of $a divided by $b.
$a ** $b | Exponentiation | Result of raising $a to the $b'th power. Introduced in PHP 5.6.
* The division operator ("/ ") returns a float value unless the two operands are integers, (or strings that
get converted to integers),
String Concatenation Operator:
* The concatenation operator returns the concatenation of its right and left operands. Operands are
first converted to strings, if necessary. For example:
<?php
$a = "Hello “;
$b = $a . “World!"; // now $b contains "Hello World!"
echo $b; // Display Hello World!
?>
2. Autoincrement and Autodecrement Operators:
* PHP supports C-style pre- and post-increment and decrement operators.
* The increment/decrement operators only affect numbers and strings. Arrays, objects and resources
are not affected, Decrementing NULL values has no effect too, but incrementing them results in 1.

++$a Pre-increment | Increments $a by one, then returns $a,


$Sat++ Post-increment | Returns $a, then increments $a by one.
--$a Pre-decrement | Decrements $a by one, then returns $a.
§a-- Post-decrement | Returns $a, then decrements $a by one.
* These operators can be applied to strings as well as numbers. Incrementing an alphabetic character
turns it into the next letter in the alphabet.
For example:
Incrementing "a" gives"b"
Incrementing"z" gives"aa"
Incrementing"spaz"gives"spba"
Incrementing"k9" gives"Le"
3, Comparison Operators;
PHP provides comparison operators to compare two operands. A comparison operator returnsa
Boolean value, either true or false, If the comparison is truthful, the comparison operator
returns true, otherwise it returns false.
There are following comparison operators supp
orted by PHP language:

Equal True if $a is equal to $b after type juggling.


$a === $b | Identical True if $a is equal to $b, and they are of the same
| type.
contd...

— Scanned with CamScanner


hd
Web Based Application Development with PHP 1.15 Expressions and Control Statements In PHP

$a != $b or | Not equal True if $a is not equal to $b after type juggling.


$a <> $b
$a !== $b Not identical True if $a is not equal to $b, or they are not of the
same type.
$a < $b Less than True if $a is strictly less than $b.
$a > $b Greater than True if $a is strictly greater than $b.
$a <= $b Less than or equal to True if $a is less than or equal to $b.
$a >= $b Greater than or equal to True if $a is greater than or equal to $b.
Logical Operators:
Generally, logical operator used in decision making. Logical operators treat their operands as
Boolean values and return a Boolean value.
There are following logical operators supported by PHP language:

$a &and $b, $a and $b AND True if both $a and $b are True.


$a || $b, $a or $b OR True if either $a or $b is True.
$a xor $b XOR True if either $a or $b is True, but not both.
! $a NOT True if $a is not True.
Assignment Operators:
The basic assignment operator (=) assigns a value to a variable. The lefthand operand is always
a
variable. The righthand operand can be any expression-any simple literal, variable, or complex
expression. The righthand operand’s value is stored in the variable named by the lefthand operand.
In addition to the basic assignment operator, there are “combined operators" (or short hand
assignment operator) for all of the binary arithmetic, array union and string operators that allow
you to use a value in an expression and then set its value to the result of that expression.
For example:
<?php
$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
>>
These assignment operators are plus-equals (+=), Minus-equals (-=), Divide-equals (/=), Multiply-
equals (*=), Modulus-equals (%=), Bitwise-XOR-equals (*=), Bitwise-AND-equals (&=), Bitwise-OR-
equals (|=) and Concatenate-equals (.=).
Bitwise Operators:
Bitwise operators perform operations on the binary representation of the operands. The following
illustrates bitwise operators in PHP:

Sa and $b | AND If both bits are 1, the corresponding bit in the


result is 1; otherwise, the corresponding bit is 0.
$a | $b OR (inclusive or) If both bits are O, the resulting bit is 0;
otherwise, the resulting bit is 1.
$a A $b XOR (exclusive or) | If either of the bits in the pair, but not both, is 1,
the resulting bit is 1; otherwise, the resulting bit
is 0.
contd...

Scanned with CamScanner


Web Based Application Development with PHP 1.16 ssion
snd Conitrcd
Expre ic, cee
Statarnarits s »
~ $a NOT chan gessinthebinary
1s toOsandOstoi _
representations of the operands. |
$a << $b Shift Left to the left (each step
Shift the bits of $a $b steps
means “multiply by two’).
$a >> $b Shift Right Shift the bits of $a $b steps to the right (each
step means “divide by two’).
7. Casting Operators:
¢ Casting operator changes type of its operand by force. PHP casting operators are (int), (float)
(string), (bool), (array), and (object).
For example:
$a = “5”; // type of $a is string
$b = (int) $a; // type of $b is integer
8. Miscellaneous Operators:
(i) Error Suppression (@): This operator is also called as error control operator, works only on
expression. When the operator is used with expression then any error messages that might be
generated by that expression will be ignored.
(ii) Execution (‘..."): PHP supports one execution operator backticks (‘"). Note that these are not
single-quotes. PHP will attempt to execute the contents of the backticks as a shell command.
$output = ‘ls -1’; // shell command for long list of files.
echo $output; {f{ Displays long list of files from present directory.
(iii) Conditional (?:): It is also called as ternary operator.
Syntax: expr1? expr2:expr 3
Meaning
is, if expr1 is true, execute expr2 otherwise
expr3.
For example:
<?php
$a = 16;
$b = 15;
$max = $a > $b? $a: $b;
$min = $a < $b? $a: $b;
echo "max = $max";
echo “min = $min";
?>
Output:
max = 15
min = 18

Operator Precedence and Associativity


* The precedence and associativity of operators are significant characteristics of a programming
language. Operator precedence is a characteristic of operators that determines the order in which
they evaluate the operands surrounding them. The associativity characteristics of an operator
specifies how operations of the same precedence are evaluated as they are executed.
* Associativity can be performed in two directions, left-to-right or right-to-left. Left-to-right
areca yite means that the various operations making up the expression are evaluated from left to
ght.
* Operator Precedence is the order in which operators in an expression are evaluated. For example, in
the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("**) operator has
2
higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if
necessary. For instance: (1 + 5S) * 3 evaluates to 18.

Pd
Scanned with CamScanner
Web Based Application Development
with PHP 1.17 in PHP
Expressions and Control Statements

° When operators have equal precedence their associativity decides how the operators are grouped.
For example “-" is left-associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and evaluates to - 4. "=" on the
other hand is right-associative, so $a = $b = $c is grouped as $a = ($b = $c).
Operators of equal precedence that are non-associative cannot be used next to each other, for
example 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal, because
the == operator has lesser precedence than the <= operator.
The following table shows the operators with the highest precedence appear at the top of the table;
those with the lowest appear at the bottom. Within an expression, higher precedence operators will
be evaluated first.

Unary a Right-to-left
Multiplicative ar. oe Left-to-right
Additive +,- Left-to-right
Relational <, <=>, >= Left-to-right
Equality ==, != Left-to-right
Logical AND &and Left-to-right
Logical OR ll Left-to-right
Conditional 2 Right-to-left
Assignment => SS Right-to-left
peta Constants
A constant is a name or an identifier for a simple value. A constant value cannot change during the
execution of the script.
A constant is a value that cannot be changes in the PHP script, once the value has been assigned
to
the named variable. The value is available to the code only after it has been declared.
A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. To
create a constant, use the define() function.
Only single values i.e. scalars can be constants, like Boolean, integer, double, string etc. Value of
constants are set using the define() function.
Syntax: define("constant_Name", value);
For example,
define(‘PI’, 3.14);
echo PI;
We can also use the function constant() to read a constant's value if we wish to obtain the constant'
s
name dynamically.

The process of determining the order in which statements execute in a program is called decision
making or flow control. A statement is code that performs a task.
The control statements are used to control the flow of execution of the program. This execution order
depends on the supplied data values and the conditional logic.
PHP supports a number of traditional programming constructs for controlling the flow of execution
of a program.
Conditional statements allow a program to execute different piece of code depending on the
condition such as if-else and switch.
if Statement
The if statement allows us to make decision based on one or more conditions and execute a piece of
code conditionally.

Scanned with CamScanner


Web Based Application Development with PHP 1.18 Expressions and Control State

« The if statement in PHP contain statements that are only executed when the condition
means the condition is true. The if statement cannot do anything if the condition is false.
* The syntax of the if statement:
if (expression) if (condition)
statements OR { a
// put the code here;

* The following is an example of using the


PHP ifstatement. We have $x variable with
value 11. In the if statement, we check if value
of $x is greater than 10 we display a message.
<?php
$x = 11;
if($x > 16)
{
echo ‘$x is greater than 10';
}
* PHP if statement flow diagram is shown in
Fig. 1.5. Fig. 1.5: Flow diagram of if Statement
+ Ifthe expression evaluates to true, the code block inside the if statement is executed.
For example: for if statement.
<?php
$a="Amar";
$b="Akbar";
if ($a==$b)
echo “Both string are equal";
echo “if block not executed";
?>
Output:
if block not executed

EEE] if-else statement


¢ The if statement allows us to run a block of code if the condition evaluates to true. If theconditi Ir
evaluates to false, the if statement skips the code block inside its body.
* The following illustrates the syntax of the if else statement:
if(expression) if (condition)
Statement... {
éiee // execute if condition evaluates to True..
Statement... OR ae

{
// execute if condition evaluates to False...
}
* The following example demonstrates how to use the PHP if else statement:
<?php
$x = 2;
if($x > 10){
echo “$x is greater than 10";
}
else
Web Based Application Development with PHP 1.19 Expressions and Control Statements in PHP

echo “$x is less than 10";


}
¢ PHP if-else statement flow diagram is shown in Fig. 1.6.

Fig. 1.6 : Flow diagram of if-else Statement


* We can enhance the if statement by adding else statement to run an alternative code block if the
condition evaluates to false.
Example: For if-else statement.
<?php
$varl="php";
$var2="java";
if ($var1 == $var2)
echo "Both the strings are equal";
else
echo "Both the strings are not equal";
>>
Output:
Both the strings are not equal
Example:
<?php
$marks=880;
if($marks>= 68 )
{
echo"You are passed". "<br>";
echo"Your marks= ".$marks."<br>";
echo"First division”;
}
else

{ '

echo"Failed"; |
}
?> |
Output:
You are passed
Your marks= 8@
First division
1,20 Expressions arid Cantal Statarnarta |p trip
Web Based Application Development with PHP
|
Example: A
<html>
<head>
<titleoPHP Decision Making Example</title>
</head>
<body>
<?php
$numl = 5;
$num2 = 10;
tnum3 = 15;
if ($numi>$num2)
{
echo "5 is greater than 16";
}
Lf ($num3>$num2)
{
echo "15 is greater than 10";
}
r>
</body>
</html>
Output:
15 is greater than 10

« If we have more than one Boolean condition to test, we


can use the if elseif statement,
Syntax:
if (condition)
{
//code block of if branch to be executed
yelseif(condition2)
{
//code block of elseif branch to be executed
Jelseif(condition3)
//code block of elseif branch to be executed
yelse
{
//code block of else branch to be executed
} Fig. 1.7; Flow diagram of if-elseif
* PHP if elseif statement flow diagram is shown in Fig, 1.7, Seana '
Example: For if-elseif statement
<?php
$x = 20; I
if($x > @)
{
echo "$x is greater than zero”
;
De

Web Based Application Development with PHP 1.21 Expressions and Control Statements in PHP

else if($x == 0)
{
echo "$x is zero”;
}
else
{
echo "$x is less than zero”;
}
?>
Output:
28 is greater than zero.
PHP also provide an alternative for conditional and looping control structure. In place of opening
brace colon (:) is used and to close the block endif keyword is used (in this case).
Syntax:
if(condition);
//code block to be executed if condition is true
doe.
else
// code block to be executed if condition is false
Wifi
endif;
Example:
<?php
$a=7
Lf ($a == 5):
echo "a equals 5";
echo 7.4."
elseif ($a == 6):
echo “a equals 6";
echo "I!1";
else:
echo “$ais neither 5 nor 6";
endif;
?>
Output:
a is neither 5 nor 6

Ley Nested if Statement


* When one if statement contains another if statement then such
type of structure is known as nested
if. Nested if structure also helps in multi-way decision making where
one condition depends on
other.
* Ithas the following form/syntax:
if (condition 1)
{
if (condition 2) / * nested if */
{
Statement(s);
in PHp
Expressions and Control Statements
1.22
Web Based Application Development with PHP
}
else

{
Statement(s);
}
}
else
{
Statement(s);
}
Example: For nested if statement.
<IDOCTYPE html>
<html>
<body>
<?php
$a=10;
$b=28;
if ($a==18)
{
if ($b==20)
{
echo “The addition is: “.($a+$b);

}
?>
</body>
</html>
Output:
The addition is: 36

switch Statement
Consider the case where value of a single variable may determine one of a number of different
choices (e.g., the variable holds the username and we want to do something different for each user).
The switch statement is designed for just this situation.
Switch statement is used to compare the value with multiple cases or values. All statements in 4
matching case are executed upto the first break keyword.
If none match and ‘default’ is given, all statements following the default keyword are executed up to
the first break keyword.
Syntax:
switch( variable)
{
case valuel:
// code block 1
break;
case value2:
// code block 2
break;
TINTS SSS ae

Web Based Application Development with PHP 1.23 Expressions and Control Statements in PHP

default:
// default code block
}
+ Alternative Syntax |
switch(variable): |
case valuel: |
// code block 1 |
break;
case value2:
// code block 2
break;
default:
// default code block
endswitch;
* PHP switch statement flow diagram is shown in Fig. 1.8.
; switch
| (a variable or expression)|

case
value 1

case
value3

~ code block in :
default

Fig. 1.8 : Flow diagram of switch Statement


Example: For switch statement.
<?php
$var=date("D");
switch($var)
{
case "Sun":
echo "It is Sunday.";
break;
case “Mon":
echo "It is Monday.";
break;
case "Tue":
echo "It is Tuesday.”;
1.24 Expressions and Control Statements jp, Pip
with PHP
on Development
Web Based Applicati

break;
case "Wed":
"
echo “It is Wednesday.
break;
case "Thu":
echo “It is Thursday.";
break;
case “Fri":
echo “It is Friday.";
break;
case “Sat”:
echo "It is Saturday.";
break;
default:
echo “Something wrong”;
?>
Output:
It is monday

‘eee break Statement


is situated inside the
* Wecan prematurely exit a loop with the ‘break’ keyword. The break statement
statement block.
* It gives us full control and whenever we want to exit from the loop we can come out. After coming
out of a loop immediate statement to the loop will be executed.
Syntax:
fortic.)
{
i ere
if(condition)
{
break;

rere /* Never executed after executing break statement*/


}
« emm
Ifthe condition a
is true, the break statement will be ex ecuted and the loop willi be break. It willi skipi all

Loop
False

Fig. 1.9: Flow Diagram for break Stat


ement
Web Based Application Development with PHP 1.25 Expressions and Control Statements in PHP

« Inthe following code, $i never reach a value of 6, because the loop is stopped once it reaches 5.
Example: For break statement.
<?php
$i=1;
while($i<=10)
{
echoes: =";
if($i == 5)
break;
$i++;
}
?>
Output:
12,3 4.5
* Optionally, we can put a number after the break keyword, indicating how many levels of loop
structures to break out of. In this way, a statement buried deep in nested loops can break out of the
outermost loop.
Example:
<?php
$i = 1;
while ($i <= 16)
{
$j = 1;
while ($j <= 18)
{
if ($j == 5)
break 2; // breaks out of two while loops
$i++;
}
$i++;
}
echo $i;
echo “<br>”;
echo $j;
?>
Output:
2
5

‘EE continue Statement


* The continue statement forces the next iteration of the loop skipping the remaining code of the loop.
* Thecontinue statement is situated inside the statement block containing the code that the loop
executes, preceded by a conditional test. For the pass encountering continue statement, rest of the
loop code is skipped and next pass starts.
Syntax: |
for(initialisation; condition; increment/decrement) |
{
if(True Condition) //Continues Loop with the Next Value
continue;
Expressions and Control Statements in PHp |

Fig. 1.10: Flow Diagram for continue Statement


lowing program disp
onlyla
odd ys
numbers from the array.
For continue statement.

= array(1,2,3,
4,5);

west ($e 2s $value)

if($value%2 == @)
continue;

echo $value . =" 2

maaan
a
PHP is used to execute a statement ora
block of statements, multiple times unti
condition is met. This helps the user l and unless a
to Save both time an d effort of writing the
same code —
loops in PHP are used to execute the
same block of code a specified number of times. PHP
the following four loop types:
Web Based Application Development with PHP 1.27

while Loop
¢ The while loop is the simplest loop statement in
PHP. While loop will execute block of code until
certain condition is met.
Condition False
Syntax: expression
while(expression)
{
True
//code block to be executed
}
* The while loop statement checks the expressi
on
at the beginning of each iteration. If the
expression evaluates totrue, the code
block
inside the curly braces is executed. If
the
expression evaluates to false, the loop exits.

Fig. 1.11: Flow Diagram for while Loop


Example: Program to displays number
from 1 to 10.
<?php

$i=1;
while($i<=10)
{

echo gr 7. et
$i++;
}
?>
Output:
22 345 16-708 5240
* The alternative syntax for while statement is:
while(expression):
statement;

endwhile;
Example: for while loop.
<?php
$i=1;
while($i<=18):
echo $i." ";
$i++;
endwhile;
?>
Output:
A234 516 7 89 10
re )
1.28 Expressions and Control Statements
s } Web Based lication Development with PHP

| do while Loop
wor: ks same as whil
e, except that
. while loop
Se

aluated at the end of each


the expression : is ev
a
~ do while —
| iteration. code block
: Syntax:
do {
//code block to be executed

} while(expression) ;
loop body
Use a do while loop to ensure that the Condition
} is executed at least once.
tement
i} * The code block insidedo whileloop sta
n is che cke d at
executes first and then expressio
sion
the end of each iteration. If the expres
totrue, the code block exec utes
evaluates
Fig. 1.12: Flow Diagram for do while Loop
repeatedly until the expression evaluates to false.
} Example: Program displays number from ito 10.
<?php
: $i=1;
do {
wom,
echo $i . 3

$itt+;
}while($i<=18);
. ?>

| for Loop
* The for loop is same as while loop but it is shorter and easier to use.
Syntax:
for(init_expr; condition_expr;increment_expr)
{
//code block to be executed

}
through the loop, the
e At the beginning, the counter initialization occurs only once. Each time
d; if it is false, the loop ends.
expression condition is tested. If it is true, the body of the loop is execute
The expression increment/decrement is evaluated after the loop body runs.

)
Fig. 1.13: Flow Diagram of ‘for’ Loop

.. Scanned with CamScanner


Ces ccee sees
s sees enn ene
Web Based Application Development with PHP 1.29 Expressions and Control Statements in PHP

Example: Program displays number from 1 to 10.


<?php
for ($i=1; $i<=10; $i++)
{
echo $i a ” ot:

}
?>
+ The alternative syntax for ‘for’ loop:
for (initialization; condition; increment):
statement;
ote
endfor;
Example:
<?php
for ($i=1; $i<=10; $i++):
echo $1 5-7 "3
endfor;
?>

foreach Loop
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and
objects, and will issue an error when we try to use it on a variable with a different data type or an
uninitialized variable.
* PHP provides the foreach loop statement that allows you to iterate over elements of an array
or
public properties of an object.
* There are two syntax:
foreach (array_expression as $value) OR foreach (array_expression as $key => $value)
statement statement
* The first form loops over the array given by array_expression. On each iteration, the value of the
current element is assigned to $value and the internal array pointer is advanced by one (so on the
next iteration, we will be looking at the next element).
* The second form will additionally assign the current element's key to the $key variable on each
iteration.
Example: For foreach loop.
<?php
garr = array(1, 2, 3, 4);
foreach (¢arr as $value)
{
“ .
echo $value . ’

}
?>
Output:
wo WD 3h
* The alternative syntax for foreach loop is:
foreach (array_expression as $value):
// PHP code here...
end foreach;
Web Based Application Development with PHP 1.13 Expressions and Control Statements in PHP

{
// $x is a resource
}
Null:
This data type is having only one value denoted by the keyword NULL.
The null value represents a variable that has no value. A variable is considere
d to be null if:
(i) it has been assigned the constant NULL.
(ii) it has not been set to any value yet.
(iii) it has been unset().
is_null() function is used to test whether a value is null or not null.

Expressions and Operators


Processing data is accomplished in PHP programming, as it is in other programming language
s, by
way of operators and expressions.
Operators are the symbols that tell PHP what operations to perform, and expressions are the
individual sets of variables and operators that make a result when processing is complete.
pee Expressions
Expressions are any code that evaluates to a value, The assignment of a value to a variable is an
expression in itself, although we tend to think of expressions as similar to
equations,
(like $z = $x + $y, where $x + $y is the expression we have in mind). Therefore, $x =5 is
an expression,
because it evaluates to then value 5,
An expression is a piece of code that evaluates to a value. A value a number, a string of text,
or a
Boolean. An expression is a combination of values, variables, operators, and functions
that results in
a value.
The simplest expressions are literal values, variables and complex expressions can be formed
using
simple expressions and operators.
Operators
An operator is a symbol that manipulates one or more values, usually producing a new value
in the
process. The PHP operators are used to perform the operations in PHP.
Operators are special symbols that perform some specific operations using the operands and
operator as shown in Fig. 1.4.
os Operands

Z=X+Y
Operator
Fig. 1.4: Concept of Operator and Operand
Operators indicate the operation to be carried out on operands, while o perands are the values
going
to be operated.
Categories of operators are as follows:
1. Unary Operators: Operates on single operand.
2. Binary Operators: Which take two operands and produces output/result value,
3. Conditional Operator (Ternary Operator): Which takes three operands and evaluates either the
second or third expression, depending on the evaluation of the first expression
Let see various operators in PHP in detail.
Arithmetic Operators:
The arithmetic operators require numeric values. And non-numeric values are converted
automatically to numeric values.
There are following arithmetic operators supported by PHP language:

Scanned with CamScanner


1.30 Expressions and Control Statements in Pip
Web Based Application Development with PHP

Pract ice Questions


a
=
What is web application?
Or holt

How to develop a web application?


What is PHP?
eS

Enlist features of PHP.


What is variable? How to declare it? Explain with example.
Explain constants in PHP with example.
What are the decision statements used by PHP?
Describe loops in PHP.
What is operator? Which operators used by PHP? Explain with example.
Se

. Define the term expressions with example.


ad
BREESE

. Describe data types in PHP in detail.


. Explain variable scope in PHP.
. Write the difference between break and continue statement of PHP with example.
pe pe pe

. Explain any two control statements with syntax and example.


sha

. Describe syntax of PHP with example.


. Find output:
>

<?php
$a= “9 Lives.” -1;
var_dump($a);
?>
Avs Find the output.
<? php
$ str = “welcome”;
echo ‘You are $ str’;
i>
18 - Write program to find a area of rectangle.
Li ie ile was 6 ae ae
Manipulate the given type of arrays to get the desired result.
iam ®

Apply implode, explode functions on the given array,


Apply the given string functions on the character array.
Scale the given image using graphics concepts/functions.

To understand Concepts of Array


To learn Types of Arrays
meee

To study Traversing Arrays and Extracting Data from Arrays


To understand Basic Concepts of Functions in PHP
To learn String and String Functions
To understand Basic Graphics Concepts in PHP

A function is a named block of code that is designed to perform a specific task. Once, a function is
defined, we can reuse it without copying and pasting a code block again and again.
A function may accept one or more arguments, which are the values that we pass to the function. A
function may return a value so that the calling script can communicate with it.
In PHP, a string is a sequence of characters. PHP also support graphics programming with functions
that create, open and manipulate graphics.
An array in PHP is a collection of key/value pairs. PHP arrays are a collection of variables, which
stores multiple values of different data type at a time.
yee CR) MANIPULATING 4
An array is a collection of data values, organized as an ordered collection of key-value pairs. In PHP
array is used to store multiple values in single variable,
Commonly used terms in array are explained below and shown in Fig. 2.1.
1. Element: Element of an array is the items Element
it contains. An array can contain one or Firstindex (at index 8)

more elements.
2. Value: Each element contains one value. 1 2°93 4 {60 16ayh
\8 9 «— Indices
3. Key or Index: Key or index of an array is a
unique number or a string that is eee eee: 8
associated with each value of an element. ls ' Atay length ts 10 >|
4. Length: The length of an array is the Fig. 2.1: Element of Array
number of elements it contains,
(2.1)

Scanned with CamScanner


Web Based Application Development with PHP 2.2 Arrays, Functions and Graphics

Creating an Array:
* In PHP, the array() function is used to create an array, An array takes any number of comma
separated key => value pairs as arguments.
Syntax:
$array_name = array
(
keyl => valuel,
key2 => value2,
key3 => value3,

);
* The key can either be an integer or a string. The value can be of any type.
For example:
<?php
(
$month = array
@ => "January";
1 => “February>
i
?>

Types of Arrays
* In PHP, there are three types of arrays namely, Indexed array, Associative array and
Multidimensional array.
Indexed Array
« The keys of an indexed array are integers beginning at 0, Indexed arrays are used when
identification of array elements are by their position.
« Anarray having only integer keys is typically referred to as an indexed array. Indexed arrays can
store numbers, strings and any object but their index will be represented by numbers.
For example:
¢city = array( @ => “Pune”, 1 => “Mumbai”, 2 => “Delhi”, 3 => “Chennai”);
echo $city[1]; // Mumbai
¢ Indexed array can also be created without keys. In this case the key will be started from 0.
For example:
$city = array(“Pune”, “Mumbai”, “Delhi”, “Chennai”);
echo $city[3]; // Chennai
Associative Array
* An associative array has strings as keys. An array having string keys is typically called an associative
array.
For example:
$marks = array(“Maths” => 36, “Physics” => 28, “Chemistry” => 30);
echo $marks[ ‘Physics’ ]; // 28
$v = array(“a” => “one”, “b” => “two%, “c” => “three”);
echo $v[‘a’]; // one
« PHP internally stores all arrays as associative arrays, so the only difference between associative and
indexed arrays is what the keys happen to be. In both cases, the keys are unique-that is, we can’t have
two elements with the same key, regardless of whether the key is a string or an integer.
Web Based Application Development with PHP 24 Arrays, Functions and Graphics

ym ee Multi-Dimensional Arrays
¢ Ina multi-dimensional array each element in the main array can also be an array. And each element
in the sub-array can be an array, and so on.
¢ Values in the multi-dimensional array are accessed using multiple index.
$row@=array(1, 2, 3);
¢rowl=array(4, 5, 6);
$row2=array(7, 8, 9);
$multi=array($row8, $rowl, $row2);
$val=$multi[2][0]; // 2" row, @” column and $val=7
Example: For multi-dimensional array.
<?php
$marks = array
(
"Amar" => array
(
“physics” => 35,
"maths" => 30,
“chemistry” => 39

"Kiran" => array
(
“physics” => 30,
"maths" => 32,
"chemistry" => 29
),
“Deepa” => array
(
"physics" => 31,
“maths” => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for Amar in physics: " ;
echo $marks['Amar'][‘physics'] . "<br />";
echo "Marks for Kiran in maths: ";
echo $marks['Kiran']['maths'] . “<br />";
echo "Marks for Deepa in chemistry: " ;
echo $marks['Deepa'][ ‘chemistry’ ] "<br>"
>>
Output:
Marks for Amar in physics: 35
Marks for Kiran in maths: 32
Marks for Deepa in chemistry: 39
I

* PHP provides two functions extract() and compact(), that convert between arrays and variables. We
can use the extract() function to extract data from arrays and store it in variables. The compact()
values.
function creates an array from variables and their
Web Based Application Development with PHP Arrays, Functions and Graphics
2.4
* The extract() function automatically creates local variables from an array, The in dexes
of the
: arr; y
elements are the variable names.
Example:
<?php
$ice_cream[“good”] = “mango”
$ice_cream[“better”] = “vanila”
tice_cream[“best”] = “butterscotch”
?>
Now we can we extract to create variables whose names will be taken from the keys in the array,
and
those variables will be assigned the values in the array.
<html>
<head>
<title> Extracting variables from arrays </title>
</head>
<body>
<hl>Extracting variables from arrays</
h1>
<?php
$ice_cream[“good”] = “mango” ;
$ice_cream[“better”] = “vanilla”;
$ice_cream[“best”] = “butterscotch”;
extract($ice cream);
echo “\$good = $good<br>”;
echo “\$better = $better<br>”;
echo “\$best = $best<br>”;
?>
</body>
</html>
Output:
Extracting variables from arrays
$good = mango
$better = vanilla
$best = butterscotch
* The compact() function creates
an array from variables and
Example: For their values,
compact() in PHP.
<?php
$n1 = 10;
$n2 = 20;
$n3 = 30;
$arr = array("n1i", Ties; “nia )4
$output = compact ($arr);
Print_r($output);
?>
Output:
The Arra
listoy ({n1] => 19 [n2] => 20 [n3] => 30)
3 ist()
function is an inbuilt func
Variables at a time. maction in PHP which is used to assign arra
y values to multiple
24 Implode
© We use the implode
to "join ele
() function to cony, ;
ments of an array with ‘a
a a
: 7
Sen Nerina ‘mplode function in PHP is
used
Web Based Application Development with PHP 2.5 Arrays, Functions and Graphics

It creates a string from an array of smaller strings. The implode() function returns a string from the
elements of an array.
Syntax: string implode (string $glue, array $pieces)
This function join array elements with a ‘glue’ string. The glue contains the information about
defaults to an empty string while pieces is the array of strings to implode.
It returns a string containing a string representation of all the array elements in the same order,
with the glue string between each element.
Example: For implode().
<?php
$array = array('lastname', ‘email’, ‘phone');
$comma_separated= implode(",", $array);
echo $comma_separated;
?>
Output:
lastname, email, phone
join() i is an alias of implode() function.
Explode
It breaks a string into smaller parts and stores it in an array. To convert a string into an array, we use
the explode() function.
The explode() function splits the string based on the specified delimiter and returns an array that
contains elements, which are substrings produced by the splitting operation.
In short, the explode function is used to "split a string by a specified string into pieces i.e. it breaks a
string into an array".
Syntax: array explode (string $delimiter, string $str [, int $limit ])
Returns an array of strings, each of which is a substring of ‘str’ formed by splitting it on boundaries
formed by the string ‘delimiter’.
If ‘limit’ is set and positive, the returned array will contain a maximum of ‘limit’ elements with the
last element containing the rest of ‘str’.
If the ‘limit’ parameter is negative, all components except the last - ‘limit’are returned. If
the ‘limit’ parameter is zero, then this is treated as 1.
Example: For explode().
<?php
¢str = ‘one|two|three|four';
garr = explode('|', $str);
print_r($arr);
echo "<br>";
garr = explode('|', $str, 2);
print_r($arr);
echo "<br>";
garr = explode('|', $str, -1);
print_r($arr);
?>
Output:
Array ([@] => one [1] => two [2] => three [3] => four)
Array ([@] => one [1] =>two|three| four)
Array ([@] => one [1] => two [2] => three)

Scanned with CamScanner


Web Based Application Development with PHP 2.6 Arrays, Functions and Graphics

* Since, in the second case the limit is two, hence the string will be divided into two parts. In the third
| case since the limit is negative so except the component ‘four’, remaining components will be
| returned. .
* The explode() function breaks a string into an array, but the implode function returns a string from
the elements of an array.
Array Flip
* Thearray_flip() function flips/exchanges all keys with their associated values in an array.
| © PHP array_flip() this function very useful when we have a big/large array, and we want to know if a
1 given value is in the array.
Syntax: array_flip(array)
Example: For array flip().
<?php
$al = array("a"=>"red","b"=>"green", "c"=>"blue","d"=>"yellow") ;
$result = array_flip($a1);
print_r($result);
>>
Output:
Array ([red] => a [green] => b [blue] => c [yellow] => d)

* Traversing an array means to visit each and every element of array using a looping structure and
iterator functions.
¢ There are several ways to traverse arrays in PHP.
1. Using foreach Construct:
* PHP provides a very special kind of looping statement called foreach that allows us to loop over
arrays. The foreach statement only works with arrays and objects.
Example: For foreach construct to traversing arrays.
$a = array(‘aaa’, ‘bbb’, ‘ccc’);
foreach($a as $value)
{
echo “$value\n”;
}
Output:
aaa

bbb
ccc
* In the above foreach loop, the loop will be e
; ;
| for each iteration Sralue will store the iatt Sater vot en sleinaat at ee = mes. And
| Example:
$a = array(‘one’ = 1, ‘two’ => 2, ‘three’ => 3);
foreach ($A as $k => $v)
{
echo “$k is $v \n”;
| }
Output:
one is 1
two is 2
three is 3

Scanned with CamScanner


a
Web Based Application Development with PHP 27 Arrays, Functions and Graphics

In this case the key for each element is stored in $k and the corresponding value is stored in $v. The
foreach operates on copy of array, not on array itself.
2. Using for Loop:
The for loop operates on the array itself, not ona copy of the array.
Example: For ‘for’ construct to traversing arrays
$a = array(1, 2, 3, 4);
for($i=®; $i<count($a); $i++)
{
echo $A[i] . “<br>”;
}
Output:
1
2
3
4
Iterator Functions:
Every PHP array keeps track of the current element. The pointer to the current element is known as
the iterator. PHP has functions to set, move, reset this iterator.
The iterator functions are:
current(): Returns the currently pointed element.
vPyNe

reset(): Moves the iterator to the first element in the array and returns it.
next(): Moves the iterator to the next element in the array and returns it.
prev(): Moves the iterator to the previous element in the array and returns it.
end(): Moves the iterator to the last element in the array and returns it.
each(): Returns the key and value of the current element as an array and moves the iterator to
=

the next element in the array.


7. key(): Returns the key of the current element.
Example: For interator functions,
<?php
$transport = array('foot', ‘bike’, ‘car’, ‘plane');
¢tmode = current($transport); // $mode = 'foot';
ul

$mode = next($¢transport); // ¢mode = 'bike';


$mode = current($transport); // $mode = 'bike';
¢mode = prev($transport); // tmode = ‘foot’;
$mode = end($transport); // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
2
* After executing each() the iterator moves to the next element.
<?php
$a = array(10, 20, 30, 40, 5@);
reset ($a) ;
while (list($key, $val) = each($a))
{
echo “$key => $val<br>";

}
7
Web Based Application Development with PHP 2.8 Arrays, Functions and Graphics
Output:
@=> 10
1 => 20
2 => 30
3 => 48
4 => 50
Calling a Function for each Array Element:
The array_walk() function apply a user defined function to each element of an array.
Syntax: bool array walk (array &$arr, callable $function_name) 2
This function takes two parameters, first is the input array and second is the user defined function
name.
The user defined function takes two arguments, first contains arr’s value and second contains arr’s
key. Returns True on success or False on failure.
Example:
<?php
functionprint_row($v, $k)
{
echo “$v $k <br>";
}
$a = array(1@, 26, 30, 40);
array_walk($a, ‘print_row');
?>
Output:
ip 68
26 #1
38 2
49 3
In the above program the ‘print_row’ function will be called four times (4) i.e.
for each elements of
the array $a. The ‘print_row’ function then displays the values along
with the keys.
Reducing an Array:
The array_reduce() function apply a user defined function to each
element of an array, so as to
reduce the array to a single value.
Syntax: mixed array_reduce(array $array, callable $callback
}) [, mixed $initial = NULL
The function takes two arguments namely, the running total, and
the current value being processed.
It should return the new running total.
Example: For reducing array.
<?php
function add($sum, $value)
{
$sum += $value;
return $sum;
J
$n = array(2, 3, 5, 7);
$total = array_reduce($n, ‘add');
echo $total;
ie
Output:
7
ee
Web Based Application Development with PHP 29 Arrays, Functions and Graphics
e The function ‘add’ will be called for each element, ie. 4 times. The function then finds the sum and
returns it.
¢ Ifthe optional initial is available, it will be used at the beginning of the process.
$total = array reduce($n, ‘add’, 10);
cho $total; // 27 (i.e. 10 + 17)
Searching for Values:
e The in_array() function searches if a value exists in an array or not.
Syntax: bool in_array (mixed $to find, array $input [, bool $strict = FALSE])
¢ The in_array() function returns true or false, depending on whether the element ‘to_find’ is in the
array ‘input’ or not.
Example: For searching values.
<?php
$os = array("Mac", "NT", SERINE SELAUXS>
if (in_array("Irix", $os))
{
echo "Got Irix";
}
if (in_array(“mac", $os))
{
echo “Got mac";

?>
* The second condition is false because in_array() is case-sensitive, so the program above will display:
Got Irix
* Ifthe third parameter strict is set to True then the in_array() function will also check the types of the
$value.
Example:
<?php
$a0= array(25-3, "47, “55
if (in_array('3', $a, true))
{
echo "'3' found with strict check\n";
}
if (in_array('4', $a, true))
{
echo "'4' found with strict check\n";

} )
?>
Output:
"4" found with strict check
* Inthe above program the type of ‘3’ which we are searching is string but in the array ‘a’, 3 is integer.
Hence first condition is false.
array_search():
* The array_search() function search an array fora value and returns the key.
Syntax: mixed array_search (mixed $to_find, array $input [, bool $¢strict = FALSE])
Web Based Application Development with PHP 2.10 Arrays, Functions and Graphice
* The in_array() function returns the key of the element ‘to_find’ if it is found in the array ‘input’,
otherwise returns False.
Example: For array search.
<?php
$a=array("a"=>"5","b"=>5,"c"=>"5")5
echo array_search(5,$a,true);

2.4 er e ee ee F Mgr pair => a A - = ——

* A function is an independent named block of code that is defined to perform a specific task. A
function can be called from another part of the program, and may or may not return a value. Code
inside a function are not executed until the function is called.
* There are two types of functions i.e., built-in functions and user defined functions.
1. Built-in Functions are also called as pre-defined functions or library functions that perform a
wide range of operations and they can be retrieved by the programmer directly. PHP is very rich
in terms of built-in functions.
2. User Defined Functions are defined by user.
* Functions are useful because they contribute to rapid, reliable, error-reducing coding. A function
can be called many times in a page but it is compiled only once.
* Asa function is written only once and removes the need to write the codes for the same task every
time it requires, it reduces number of bugs. As functions separate codes that perform a specific task,
it improves readability.
Advantages of using Functions:
1. PHP Functions reduces the memory and complexity of the program.
2. Functions make PHP script modular - by using functions, a big script is divided into many
functions that are easier to build, test and maintain.
3. Functions mainly helps in code re-usability.
4. PHP functions reduces the bugs and saves the time of programmer.
5. Information hiding is possible by functions.
y2-%e Defining and Calling a Function
* We already know that a function is a named block of code that performs a specific task, in this
section we discuss defining and calling functions.
yee Defining a Function
° A function is a self-contained block of code that performs a specific task. A function
is created in a
PHP script simply by stating its name, after the ‘function’ keyword, followed by parentheses and
curly brackets (braces { }) containing the statements to be executed each time that function gets
called.
* Todefine a function following syntax is used:
function [&] function_name( [parameter[, ...]])
{
statement list
}
* A funct
inc ion starts with the keyword function and isi
followed b i i i al
and if it is used then function returns reference.
SO
¢ A function name can be any strin g that begin
i s with
i a letter or unde
more letters, underscores and numbers. ;
eo

ila a i
Scanned with CamScanner
Web Based Application Development with PHP 2.11 Arrays, Functions and Graphics

Function names are case-insensitive. It means count(), Count()and COUNT() refer to the same
function. By convention, PHP built-in functions are in lowercase.
Example: For function.
<?php
function writeMseg()
{
echo "Hello world!";
}
writeMsg() ; // call the function
?>
Output:
Hello world!

Calling a Function
Calling a function is simple - just write the name of the function followed by a pair of parentheses.
We can calla function by using following syntax:
$some_value = function_name([parameter, ...]);
After calling a function, the statements inside it are executed. After the function execution is
completed, the program control returns to the point where the function was called.
Fig. 2.2 shows how caller and receiver functions work together.
<?php
function welcome(){
echo “Hi, welcome to Schools of Web.";

ng the
poe > a me,
ee tarts
con 08
Fig. 2.2: How Caller and Receiver Functions Work Togetehr
Example: For calling a function.
<?php
Function welcome()

{
echo “Hi, Welcome to PHP.”;

}
welcome(); // Function welcome() is called here.
?>
Output:
Hi, Welcome to PHP.
Explanation of Above Program: The function welcome() is defined. In this stage nothing happens.
When the function is called, the interpreter finds it and enters into it, executes the statement(s)
inside it. Here, it prints the sentence “Hi, Welcome PHP.".
Function Arguments
Information can be passed to functions through arguments. Inside the brackets () after the function
name, we specify one or more parameters (or arguments).
If a function accepts more than one parameter, each parameter has to be separated by a comma(,).
The arguments are evaluated from left to right.
| Web Based Application Development with PHP 2.42 purey: s, Functions and G
aGraphicsj

Example:
function strceat($left, $right)

$combined_string = $left.$right;
echo $combined_string;
}
* PHP supports passing arguments by value (the default), passing by reference, and default argument
values, Variable-length argument lists are also supported,
i * By default, function arguments are passed by value (so that if the value of the argument within the
function is changed, it does not get changed outside of the function). To allow a function to modify
its arguments, they must be passed by reference.
* When an argument to a function passed by reference, always prepend by ampersand (&) to the
argument name in the function definition.
Example: For function with arguments.
<?php
function doubler(&$value)
{
$value = $value * 2;
}
$a
= 3;
doubler($a);
echo $a; // Outputs 6
?>

Returning Values
} * Values are returned by using the return statement. Any type may be returned, including arrays and
objects.
« A function typically processes the arguments and returns a value to the caller, which may be another
function or script. To return a value from a function, we use the return statement.
* When PHP encounters the return statement, it terminates the function immediately and returns the
value back.
Example:
<?php
function square($¢num)
{
return $num * $num;
}
echo square(4);
// Outputs 16
?>
* _A function can not return multiple values, but similar results can be obtained by returning an
array.
Example: For function returning values,
- <?php
function day_name()
{
| $day1 = ”Monday”;
fl $day2 = ”Tuesday”;
$day3 = “Wednesday”;
return array($day1, $day2, $day3);
Web Based Application Development with PHP 2.13 Arrays, Functions and Graphics

}
$days = day_name();
echo $days[@] . 7” . $days[i] ." ” . Sdays[2];
?>
Output:
Monday Tuesday Wednesday
Function day_name() creates an array that has three elements in it and returns to its caller. When
the function is called, the function returns the array to the caller assigns it in the $days variable.
The
next line prints the values of the array elements.
Function Body
The code inside the curly brace{ } is a function body. We can put PHP code, HTML code or mixed PHP
and HTML code inside its body.
« For example, the following function displays the header of a web page:
function display_header($header)
{
echo “<hl>” . $header . “</h1>”;
}
Ea Function Types
* Inthis section we study various types of functions in PHP.
User Defined Functions
Besides the built-in PHP functions, it is possible to create our own functions, according to
requirements known as user defined functions.
Auser defined function is a block of statements that can be used repeatedly in a program.
A user-defined function declaration starts with the key word ‘function’ followed by name as the
function.
Syntax:
function functionName()
{
code to be executed;
}
Example: For user defined functions.
<?php
function writeMsg()
|
echo "Hello world!";

writeMsg();
p>
Output:
Hello world!

2.4.2.2 | Variable Function


* PHP supports the concept of variable functions means that we can call function based
on value of a
variable. If a variable name has round parentheses appended to it, PHP will look for a function with
the same name as whatever the variable evaluates to, and will attempt to execute it.
The variable function does not work with echo(), print(), unset(), isset(). PHP allows us to store a name
of a function in a string variable and use the variable to call the function.

Scanned with CamScanner


Web Based Application Development with PHP 2.14 Arrays, Functions end Oraphicg
* Variable functions are useful in cases that we want to execute functions dynamically at run-time
* The following example demonstrates how to use variable functions.
<?php
Function find_max($a,
$b)
{
return $a > $b? $a: $b;
}
Function find_min($a,
$b)
{
return $a < $b? $a: $b;
}
$f = 'find_max';
echo $f(10,20); // Outputs 2e
$f = 'find_min';
echo $f(10,20); // Outputs 10
?>
s First, we defined two functions namely, find_min() and find_max(). Then, we called those function
based on the value of string variable $f. Notice that we need to put parentheses after the variable in
order to call the function specified by the value of the variable.
Anonymous Function (Lambda Function)
We can define a function that has no specified name. We call this function is an anonymous
function or a closure. Also called as lambda function. We often use anonymous functions as values
of callback parameters.
The anonymous function is created using the create_function(). It takes two parameters. First
parameter is the parameter list for anonymous functions and second parameter contains
the actual
code of the function. The function name is randomly generated and returned,
$f_name = create_function(args string, code_string);
Example: For lambada function.
<?php
$add = create_function('$a,$b', "return($a+$b);');
$r = $add(2,3);
echo $r;
?>
Output:
5

¢ PHP string is a sequence of characters i-e., used to store and manipu


late text. String is one of the data
types supported by PHP. In this section we study String
operations and functions.
Concept of String:
* A “string” of text can be stored in a variable in much the
Same way as a numeric value but the
assignment must surround the string with quote marks ( +»
OF ‘..’) to denote its beginning
“a ” a ¥ . * s

end like "Hello world!”, and


Strings are very useful to store names, passwords,
address, and credit -card number and so on. For
that reason, PHP has large number of functions for
working with strings.
There are three different ways to write string in
PHP as explained below:
1. Single Quoted String:
In this method, string is enclosed with single quotation mark (02).
For example: ‘Hello World’ ‘Fred’ ‘Pune’ etc.

Scanned with CamScanner


Web Based Application Development with PHP 2.15 Arrays, Functions and Graphics

¢ The limitation of single quoted string is that variables are not interpolated.
Example: For single quoted string.
<?php
$name = ‘Amar;
$str = “Hello $name’; // Single-quoted string
echo $str;
?>
Output:
Hello $name
¢ Inthe above output the value of variable $name is not
printed.
2. Double-Quoted String:
* It is the most commonly used quote to express string. Here charac
ters are enclosed with double
quotation marks (“....”).
For example: “Hello World”,
“Pune”. “fred”,
* PHP interpreter interprets variables and special characters inside double quotes. In
the following
example, the above example is re-written using double
quotes.
Example: For double quoted string.
<?php
$name = ‘Amar’;
$str = “Hello $name”; // Double-quoted string
echo $str;
?>
Output:
Hello Amar

3. Here Documents (heredoc):


* Single quoted and double-quoted strings allows string in single line.
To write multiline string intoa
program ‘heredoc’ is used.
* Rules of using heredoc:
(i) heredoc syntax begins with three less than signs (<<<) followed by identifier
(a user defined name). The identifier can be any combination of letters, numbers,
underscores
but the first character must be a letter or an underscore.
(ii) The string begins in the next line and goes as long as it requires.
(iii) After the string, the same identifier that is defined after the (<<<) signs in
the first line should
be placed at the end. Nothing can be added in this last line except a
semicolon after the
identifier and it is optional.
(iv) Space before and after <<< is essential.
Syntax:
$var_name = <<< identifier
string statement
string statements
identifier;
Example: For heredoc string.
<?php
$str = <<< EOD
Web Based Application Development with PHP 2.17 Arrays, Functions and Graphics

\t tab
\\ Backslash
\$ Dollar sign
M left brace
\} right brace
\ left square bracket
\] right square bracket
\o through \777 ASCII character represented by octal value.
\xo through \XFF ASCII character represented by hex value.
String Functions/String Operations
* Inthis section we study various string operations in PHP.
str_word_count()
* The str_word_count() is in-built function of PHP. It is used to return information about words used in
a string or counts the number of words in a string.
Syntax: str_word_count(string, return, char)
Parameters:
string specify the string to check.
return specify the return value of the function. It is an optional.
Values:
0 is by default and returns number of words found
lreturns an array with the words.
2 returns value is the actual word.
char specify characters. It is an optional.
Example:
<?php
$str="PHP JAVA";
echo “Your string is:".$str;
echo "<br>";
echo "The total word is: ".str_word_count($str);
?>
Output:
Your string is: PHP JAVA
The total word is: 2

strlen()
* The strlen() function is predefined function of PHP. It is used to find the length of string or returns
the length of a string including all the whitespaces and special character.
Syntax: strlen(string);
Example:
<?php
$str = ‘Java';
echo “Your String is:".$str;
echo "<br>";
echo "The length of String is: ".strlen($str);
?>
Output:
Your String is:Java
The length of String is:4
= oie parepe Secheet Wd emp
Web Based Application Development with PHP AI
BEER] stcrev
* This function takes a string and returns a reversed copy Of It
Syntax: string strrev(string $string)
Example:
<?php
echo strrev("Hello World!");
?>
Output:
!dlroWolleH

strpos
Find the position of the first occurrence of a substring in 4 string.
Syntax: mixed strpos(string $str, mixed Sind(, int Soffset « )) _—
* Find the numeric position of the first occurrence of ‘find’ in the ‘ste ring, Vined means any v7
data type. If ‘find’ is not a string, it is converted to an integer and applied as the ordina ios "8
character, ‘offset’ specifies that, search will start this muriber of characters commtad from
beginning of the string.
* The function returns the position of where the ‘find’ existe relative to the beprnny
the‘str’ string (independent of offset), Also note that string positions start # 0 #hé
not 1, Returns False if the ‘find’ was not found, ——

Example:
<?php
echo strpos("I am a PHP programmer”, “am");
echo “<br>”;
echo strpos("I am a PHP programmer”, “am”, 5);
?>
Output:
2
16
¢ In the above program the position (index) of character ‘I’ is 0, hence it Aleplays position A ‘ai is 2
In the second case, searching starts from 5” character, hence ‘arn’ is at position 14,

*
strpos
The syntax of this function is same
as strpos() function. This function finds the last occurrence of9
substring in the main string.
Example: . a4
<?php
echo strrpos("I am a PHP programmer”, “ am”);
echo “<br>”;
echo strrpos("I am a PHP programmer”, “am”, $);
?>
Output:
16

BREW sis repiaceg ——


16

* ofThe
thestr_replace()
string with function
otherc is a case-sensit ive, built-in function of PUP which replaces some character
Web Based Application Development with PHP 2.19 Arrays, Functions and Graphics

¢ Itis used to replace all the occurrences of the search string with the replacement string.
Syntax: str_replace($search, ¢replace, $string, $count)
Parameters:
The $search parameter contains the value which is going to be searched for the replacement in the
$string.
The $replace parameter holds that value which will replace the $search value in the $string.
The $string is an array or string in which search and replace value is searched and replaced.
The $count is the last and optional parameter. This variable stores the total number of replacement
performed on a string $string.
Example:
<?php
$string = "Hii everyone!";
$search = 'Hii';
$replace = 'Hello';
echo ‘<b>'."String before replacement:".'</br></b>'
echo $string.'</br>';
$newstr = str_replace($search, $replace, $string, $count);
echo '<b>',"New replaced string is:".'</br></b>';
echo $newstr.'</br>';
echo ‘Number of replacement ='.$count;
?>
Output:
String before replacement:
Hii everyone!
New replaced string is:
Hello everyone!
a Number of replacement = 1

ucwords()
* The ucwords() is an in-built function of PHP, which is used to convert the first character of each
word to uppercase in a string.
Syntax: ucwords($string, $separator)
Parameters:
The $string (required) is a mandatory parameter of this function, which specifies the input string
that needs to be converted.
The $separator (optional) is an optional parameter of this function, which contains the words
separator characters. It specifies a character that uses a separator for the words in the input string.
Example:
<?php
$input_str = “hello, my name is ravi.";
echo ucwords($input_str);
$input_stri = "hellomy name is ravi.";
echo ucwords($input_str1,”|”);
?>
Output:
Hello, My Name Is Ravi.
= Hello|My|Name|Is|Ravi.

a Scanned with CamScanner


Arrays, Functi
and ons
Graphic.
Web Based Application Development with PHP 220

EERE} strtoupperd
* The strtoupper() is one of the most popular functions of PHP, which is widely used to convert the
string into uppercase.
Syntax: strtoupper ($string)
Example:
<?php
$input_str = “all is well";
$result_str = strtoupper($input_str);
| echo $result str;
>>
Output:
ALL IS WELL

strtolower()
* The strtolower() is one of the most popular functions of PHP, which is widely used to convert the
string into lowercase.
Syntax: strtolower($string)
Example:
<?php
$input_str = "ALL IS WELL";
$result_str = strtolower($input_str);
echo $result_str;
?>
Output:
all is well

*
stremp()
stremp() is a string comparison function in PHP.
It
sensitive, means it treats capital and the small case separis a built-in function of PHP, which is case
ately.
This function compares two strings and
tells whether a string is greater, less, or
string. equal to another
Syntax: strcmp($stri, $str2);
* This function returns integer value randomly
Return 0 returns 0 if both strings are equal
based on the comparison.
, Le., $st= r1 $str2
Return < 0 returns negative value
if string] is less than string2, i.e, $stri
Return >0 returns positive value < $str2
if string] is greater than string
2, Le., $stri> Sstr2
Example
<?php
$stri1 = “hello php";
$str2 = “hello php";
echo stremp($stri, $str2).
" because both strings
?> are equal. “ .
a

Output:
® because both strings are equal.

Scanned with CamScanner


hics
Arrays, Functions and Graphics
Web Based Application Development with PHP 2.21

Creating Images
Before creating images in PHP, we need to understand some basic image - related concepts.
Computers usually create colors using a color theory model called the RGB model.
» RGB stands for Red, Green, and Blue, the three basic colors that are combined to create the colors
that we see on the computer display (screen). ;
+ Computers typically work with two types of images namely raster and vector. Raster images (also
known as bitmap images) are made up of pixel data; in a 20 - pixel - wide by 20 - pixel - high color
image there are 400 individual pixels making up the image, and each of these pixels has its own RGB
color value.
* The vector image uses mathematical equations to describe the shapes that make up the image. The
SVG (Scalable Vector Graphics) format is a good example of a vector image.
* Vector images are great for diagrams that include lines, curves, and blocks of color, but are not
suitable for photographs or images.
* The image functions that PHP uses are based on the GD image library that is developed by Tom
Boutell (www.boutell.com). PHP’s GD image functions let us work with four main raster image
formats JPEG, PNG and GIF for desktop Web browsers and WBMP images for mobile browsers.
* The imagecreate() function is used to create a new image. It is preferred to use
imagecreatetruecolor() to create an image instead of imagecreate().
* This is because the image processing occurs on the highest quality image possible which can be
created using imagecreatetruecolor().
Syntax: imagecreate($width, $height)
Parameters:
width is width of image.
height is height of image.
return: imagecreate() function returns an image resource identifier on success or False on errors.
Example:
<?php
$img = imagecreate(50@, 380);
$bgcolor = imagecolorallocate($img, 15@, 20@, 18@);
$fontcolor = imagecolorallocate($img, 120, 60, 200);
imagestring($img, 12, 15@, 126, "Demo Texti", $fontcolor);
imagestring($img, 3, 150, 108, "Demo Text2", $fontcolor);
imagestring($img, 9, 150, 88, "Demo Text3", $fontcolor);
imagestring($img, 12, 158, 68, “Demo Text4", $fantcolor);
header("“Content-Type: image/png”);
imagepng($img);
imagedestroy($img);
?>
Output:

* Use the imagecolorallocate() function to create the color. This function takes four arguments: the
image resource created by imagecreate(), and the red, green, and blue components of the color that
we like to create.

Scanned with CamScanner


Arrays, Functions and Graphics
Web Based Application Development with PHP 2.22

Images with Text


is used to write text to the image using
* The imagettftext() function is an inbuilt fuction in PHP which
TrueType fonts.

imagettftext i , $angle
floatstrin , int$x
i intty, ,
, int$y int$color :
(resource i e,
$imag float $size g sfontfile; string
vee $text) : array

Parameters: : Be
Image is a image resource, returned by one of the image cr jon functions, such as
imagecreatetruecolor().
size is the font size in points. . !
The angle in degrees, with 0 degrees being left-to-right reading text. Higher Sores Mas ig : a :
counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top re g i .
x is the coordinates given by x and y will define the basepoint of the first Sea ae nly the
lower-left corner of the character). This is different from the imagestring(), where x and y define the
upper-left corner of the first character. For example, "top left" is 0, 0.
y is the y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.
color is the color index. Using the negative of a color index has the effect of turning off antialiasing.
fontfile is the path to the TrueType font we wish to use.
Text is the text string in UTF-8 encoding.
Example:
<?php
// Set the content-type
header('Content-Type: image/png’);
// Create the image
fim = imagecreatetruecolor(4@@, 30);
// Create some colors
. $white = imagecolorallocate($im, 255, 255), 255),
| $grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, @, @, @);
imagefilledrectangle($im, @, @, 399, 29, $white);
// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = ‘arial.ttf';
// Add some shadow to the text
imagettftext($im, 20, @, 11, 21, $grey, $font, $text);
// Add the text
] imagettftext($im, 26, @, 10, 20, $black » $font,
$text);
// Using imagepng() results in clearer
text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
Output:

Testing...
Scaling Images
* givenimage
The newscale
wi()enfunctaay
ion is an inbuilt functionion j
In PHP whicich h isi used to scale an imag
i e using
i the
Syntax: imagescale($image, $new_width, $new_height =
Parameters: ~1, $mode = IMG _BILINEAR FIXED)
$image is returned
: by one of the image creation fi i -
: unctions, im
to create size of image. such as imagecreatetruecolor(). It is: used

Scanned with CamScanner


yr
Web Based Application Development with PHP Arrays, Functions and Graphics
2.23
oe parameter holds the width to scale the image.
$new_ = parameter holds the height to scale the image. If the value of this parameter is negative
or omitted then the aspect ratio of image will preserve.
ae ee the mode. The value of this parameter is one of IMG_NEAREST_NEIGHBOUR,
3 EAR | ,IMG_BICUBIC, IMG_BICUBIC_FIXED or anything else.
Example: For scaling an image.
<?php
// Assign image file to variable
$image_name= ‘https://i2.cdn.t
logo-782x439.png’; n. turner. com/money/dam/assets/150901123238-google-new-
// Load image file
$image : imagecreatefrompng(timage_name);
// Use imagescale() function to scale the image
$img = imagescale( $image, 500, 400 );
// Output image in the browser
header("Content-type: image/png”);
imagepng($img);
?>
Output:

Creation of PDF Document


pure PHP
FPDF is a PHP class which allows generating PDF (Portable Document Format) files with
that is to say without using the PDFlib library. F from FPDF stands for Free, we may use it for any
kind of usage and modify it to suit we needs.
FPDF has following features:
ns.
Choice of measure unit, page format and margi
OPN AM PWN Pp

Page header and footer management.


Automatic page break.
Automatic line break and text justification.
Image support, (JPEG, PNG and GIF).
Colors and Links.
rt.
TrueType, Type 1 and encoding suppo
. Page compression.
(http://www.fpdf.org/)
The FPDF library is free and can be downloaded from the official website's on
along with some tutorials
download section. The download package contains all necessary files,
fj
how to use it.
We must download and extract the FPDF package in the folder where the PHP file with the code is
located to run this example.
file.
Example: PHP Script to create a PDF
ateppdf.php
cre<?Ph
require(‘fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont( ‘Arial’,
*B’,16)3

Scanned with CamScanner


Web Based Application Development with PHP 2.24 Arrays, Functions and Graphics 7
$pdf->Cell(8@,10,'Prof. Somwanshi P. D.'); !
$pdf->Output('my_file.pdf',‘I'); // Send to browser and display
?>
Output:

* Ifonce PDF file is created download it and save as “ my_file.pdf”.

t Be Mert
+ hore + 6 ‘eethFern &
Seamer= New tae a- @

Fleace SEDEE]
Seen Spe Adobe Korsbet Cecumene
ne toa) SS Sid Toe

ote a ea
Jo ueteele-m ej i tals)
What is an array?
Pp

How to create an array? Explain with example.


an sh wn

What is string?
won

What is function?
How to extract data from array? Explain with example,
Enlist types of arrays. Describe with example.
Write the difference between index and associative array with example,
How to add image in PHP? Explain with example,
Define the terms:
(i) Array (ii) String (iii) Function.
10. How to create a function? Explain with example.
11. State advantages of functions in PHP.
12. Compare string and array.
13. With the help of example describe traversin gof array.
14, How to convert arrays into variables and vice-versa,
15. Which operations performed on string in PHP?
16. Enlist four string related function with syntax and example,
17. Explain the following types of functions with example:
(i) User defined functions (ii) Variable function (iii) Anonymous
function.
18, How to create PDF in PHP? Describe with example.
19. How to scaling an image in PHP?
20, Explain array_flip() function with example.

Scanned with CamScanner


pplication Development with PHP 2.18 Arrays, Functions and Graphic ,
leg

strrev()
of it.
netion takes a string and returns a reversed copy
G string strrev(string $st ring)

dle:
2php
echo strrev("Hello World!");
>
it:
lroWolleH

| strpos() g.
he position of the first occurrence of asubstring ina strin
$str, mixed $find[, int $offset = @])
x: mixed strpos(string
means any PHP
he numeric position of the first occurrence of ‘find’ in the ‘str’ string. Mixedordinal value of a
the
‘find’ is not a string, it is converted to an integer and applied as
rs counted from the
‘offset’ specifies that, search will start this number of characte

returns the position of where the ‘find’ exists relative to the beginning of
offset). Also note that string positions start at 0 and
(independent of
> if the ‘find’ was not found.

PHP programmer", "am", 5);

is 2
) of character ‘I’ is 0, hence it displays position of ‘am’
character, hence ‘am’ is at position 16.

() function. This function finds the last occurrence of

Scanned with CamScanner


Write constructor and Bett functions for the given evobient' in PHP.
_o| ©

Implement inheritance to extend the given base class.


Use overloading/overriding to solve the given problem,
Clone the given object.

i tas 2
Y
To understand Basic OOP Concepts in PHP
®®

To learn Classes, Objects, Constructor and Destructor with Example


To study Concept of Inheritance, Method or Function Overloading and Function Overriding
=

To understand Cloning Object, Introspection and Serialization in PHP


=

3.0
_ Object Oriented is an approach to software development that models application around real world
_ objects such as employees, cars, bank accounts, etc. A class defines the properties and methods of a
Teal world object. An object is an occurrence of a class.
PHP is an Object Oriented Programming Language (OOPL). Object-Oriented Programming (OOP), is a
type of programming language principle added to PHP, that helps in building complex, reusable web

P, refers to the method of programming that invokes the use of classes to organize the data and
‘Structure
of an application.
OOP, we take whole different approach. We model our problems and processes using objects.
iented application consists of related objects that collaborate with each other

mming, everything will be around the objects and class. By using OOP in
r web application. By using OOP in PHP we can perform any activity in the

ems to have a different set of terms for the same old concepts. This
PHP uses, but be warned that in other languages these terms may

sand functions. Class contains the actual code that defines


nes how an object will behave.

Scanned with CamScanner


Web Based Application Development with PHP 4.2 Apply Object Oriented Concepts in Pp

* Aclass itself is made up of parts called properties and methods.


strings, nulls, and Booleans.
1. The properties are different types of data objects like numbers,
Generally, the data are stored as abstract data types known as variables,
constants, and arrays,
data.
2. Methods, on the other hand, are functions that operate on the
etc. Those are its
¢ For example: A bike has a colour, a weight, a manufacturer, and a petrol tank
and sound the horn. Those are jts
characteristics. A bike can accelerate, stop, signal for a turn, Us to
bikes. OOP enables
behaviours. Those characteristics and behaviours are common to all
describes the
establish those characteristics through the use of a construct known as a Class. A class
characteristics and behaviour of all the members of a set. In OOP, characteristics of a class are
known as its ‘properties’. Properties have a name and a value.
Concept of Object: p . .
is an instance or occurrence of a class. Anything in the world is an object like laptop, books,
« Anobject
car etc. even object has two thing properties and behaviors.
e The data associated with an object are called its properties. The functions associated with an object
and behaviors in
are called its methods. We can group similar objects with the same characteristics
into one class. ;
* For example, a class is the blueprint for a house. A blueprint defines characteristics of the house on
paper. From the blueprint, we can build as many houses as we want. We say an object is an instance
of the class, or a house is an instance of the blueprint.

(a) Blueprint (Class) (b) House (Objects)


Fig. 3.1: PHP OOP Objects vs. Classes

= =
in PHP is a programmer/user-defined data type. A class as a template
for making many
nee gf paeme kind (or class) of object. A class is a template for objects, and an object
is an

ting Classes
| by using the ‘class’ keyword, followed by the name of the cl i rl
Properties and methods goes inside the braces. meen

Scanned with CamScanner


Web Based Application Development with PHP 33 Apply Object Oriented Concepts in PHP

« The sore are defined with class keyword, followed by the name of the class that we want to define.
A set of braces enclosing any number of variable declarations and function definitions. Both variable
declaration and function definition are optional. We can also create empty class in PHP.
e a, declarations start with the special formvar, 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
access the variable (object data) declared inside the class.
Example: For class creation in PHP.
<?php
class Student
{
// property declaration
var $roll_no= 1; // 1 is the default value
function showRollNo() // method definition
{
echo $this->roll_no;

}
tS

Creating Object
« Tocreate an object of a given class, use the ‘new’ keyword.
Syntax: $object = new classname;
For example: $s1 = new Student;
Here, s1 is the object of class Student.
Accessing Properties and Methods:
¢ Once, we have an object, we can use the -> (object operator) to access properties and methods of the
object.
Syntax:
$object->property_name;
tobject->method_name([{arg, .-- ]);
Example: For accessing properties and methods of an object.
<?php
class Student
{
var $roll_no;
var $name;
function display()
4
echo “Roll No: ” . $this -> roll_no . “<br>”;
echo “Name: ” . $this -> name;

}
}
$s1 = new Student;
// Properties and methods are public by default
$s1 -> roll_no = 10;
$s1 -> name = “Amar”;
$s1 -> display();
?>
Output:
Roll No: 10 a
—__ Name: Amar
Web Based Application Development with PHP 3.4 Apply Object Oriented CONES in Pap p Y
* $this is a reference to the calling object. $this is available inside any class method when that Meth,
od
is called from within an object context.
may be accesse d by using ->. Static properties =
* Within class methods non-static properties
accessed by using the :: (Double Colon). object of class, Py
directly accessible without creating
* Static methods and properties in PHP can B
prope rties of the class are static.
class will be static class if all methods and
Concept of Visibility: May be
and methods), relates to how that member
¢ The visibility of class members (i.e. properties
manipulated within, or from outside the class.
a member vari able or method can have i.e,, pubji,
There are three different levels of visibility that
private and protected.
phiccitly declared
chis not expli i te or protecteg
c as priva
4. Public Members:Any property or method whi method from inside or outside the class.
is a public method. We can access a public
private are not allowed to be called from
2. Private Members:Properties or methods declared as m,
outside the class. However any method inside the same class can access them without a proble
available to class itself and
3. Protected Members:Properties or methods declared as protected are
to classes that inherited from it.
* Public is the default visibility level. _
Brie esti te 2h 5 ees =

called automatically whenever there is


Constructor refers to a special type of function which will be
on called_ _construct() to
an object formation/creation from a class. PHP provides a special functi
define a constructor.
automatically whenever an object
e Destructor refers to a special type of function which will be called
on using function __destruct().
is deleted or goes out of scope. We can define a destructor functi
_ ERE Constructor
provides us, with a special
«+ When we create a new object, it is useful to initialize its properties. PHP
method to help initialize object's properties called constructor.
class, we simply
Constructors initialize objects at the time of its creation. To add a constructor to a
a special method with the name __construct() or use same name as that of class for constructor.
r, we create a new object, PHP searches for this method and calls it automatically.
For constructor.

' // var is not needed if visibility is used

function _ _construct() // or function student()

* $this-> roll_no = 10;


; [ee $this-> name = “Aman”;

/ Spite function display()


{
echo “Roll No: ” . $this->roll_no . “<br>”;
echo “Name: ” , $this->name;

$s1 = new Student;


-> display();

Scanned with CamScanner


; Web Based Application Development with PHP 3.5 Apply Object Oriented Concepts in PHP

Output:
Roll No: 16
Name: Amar

. PHP have not yet supported constructor overloading. Fortunately, we can achieve the same
5 F 7
constructor overloading effect by using several PHP functions.
Example:
<?php
class BankAccount
{
private $accountNumber;
private $totalBalance;
public function _ _construct()
{
fargs = func_get_args();
$num = func_num_args();
if(method_exists($this,$f = ‘init_' . $num))
{
call_user_func_array(array($this,$f),$args) ;
}
}
public function init_1($accountNo)
{
$this->accountNumber = $accountNo;
}
public function init_2($accountNo, $initialAmount)
{
$this->accountNumber = $accountNo;
$this->totalBalance = $initialAmount;
} //... other methods in the below section
}
$al = new BankAccount('121412324', 20000);
| var_dump($a1) ;
| $a2 = new BankAccount( '232321242');
var_dump($a2);
?>
Output:
object (BankAccount)[1]
private 'accountNumber' => string '121412324' (length=9)
private 'totalBalance' => int 20000
object (BankAccount) [2]
Private ‘accountNumber’ => string '232321242' (length=9)
—___ Private ‘totalBalance’ => null
How the Constructor Works?
First, we get constructor’s arguments using the func_get_args() function and also get the number of
arguments using the func_num_args() function.
Second, we check if the init_1() and init_2() method exists based on the number of constructor’s
arguments using the method_exists() function. If the corresponding method exists, we call it with
an array of arguments using the call_user_func_array() function.

Scanned with CamScanner


bins J
Oriented
3.6
with PHP
wee
Eyaws Destructor e. The destructor method wij) be
* PHP S introduces a destructor concep
re
called as soon as there are no other resources before PHP releases the object
from
it in the
to clean up (destroy) we close
* PHP destructor allows us create a file handle in the constructor and
we may
memory. For example, on,
destructor.
add a spe cia l me th od called _ _destruct() functi
we just simpl y
° Toadda destructor toa class, regarding to the
destructor:
There are following some important
points '
* acc ept an y argument.
4. Unlike aconstructor, a
destructor cann ot
d. It ha pp en s wh en there is no reference ty
is delete
called before the obj ect function.
2. Object’s destructor is of the scrip t is stopped by the exit()
the object or when the execution

Example: For destructor.


<?php
class Test
{
function _ _construct()
{
"Constructor called...<br>"5;
print
iad:
function _ _destruct()

print “Destructor called...";

class
cept. In inheritance, the new
fablished programming con
the new class is the
called as parent class or super class, and
or sub class.
class.
and methods plus variables and methods from the base
wa tit ——

Scanned with CamScanner


ESE
Web Based Application Development with PHP 3.7 Apply Object Oriented Concepts in PHP

+ An extended class is always dependent on the single base class, multiple inheritance is not
supported. We can create object of Employee class as follows:
gobj_emp = new Employee;
« Then,obj_emp -> name, obj_emp -> age, obj_emp -> salary // is allowed.
« Create object of person class.
gobj_per = new Person;
$obj_per -> name, obj_per -> age // is allowed.
$obj_per -> salary // is not allowed.
~~ Example:
<?php
class Cat
{
public $weight;
public $maxspeed;
function eat()
{
echo “Eating <br>";
}
function sleep()
{
echo "Sleeping <br>";
}
}
class Lion extends Cat
{
public $maneLength;
function roar()
{
echo “Roarrrrrr<br>";

“new Lion();

mame as the base class then the method in the derived

ability to create multiple functions of the same


types of their arguments.
soa.

Scanned with CamScanner


ly Object Oriented Son in Pip >
Application Development with PHP 3.8
Web Based

Example: For method overloading.


<?php
class Base

function show( )

{
echo “Display base <br>"5

}
}
class Derived extends Base

{
function show( )
{
echo “Display Derived”;

}
}
gob = new Derived();
gob -> show( );
P>
Output:
Display Derived when we inherit, the derived
show(), but
s define the same method
e Inabove program, both the classe sio n of sho w(). When we call show/()
method, it always calls
des the base ver
version of show() overri
the derived show() method. tion operator (::) is
hod we can use par ent::method(). The scope resolu
* To call base class show() met e clas s or to refe r functions in classes that hav
e not yet
iab les in bas
used to refer functions and var
any instances. fied as:
version of show() method can be modi
In the above program, the derived
ction show()

+ show(); // Display base


Ss ay Derived" f

tructor in the derived class is


automatic chain of constructor. Only cons

In order to run 4
‘called implicitly if the child class defines a constructor. d. If the
ts _construct() within the child constructor is require
as final, that method may not be overridden.
ding
d child classes should have same function name with and
s with
or of parent class method. The two method

le same name and same parameter is called

Scanned with CamScanner


wen Based Application Development with PHP 3.9 Apply Object Oriented Concepts in PHP |
// This is parent class
classP {
y/ Function geeks of parent class
function geeks() {
echo"Parent";
}
}
f/ This is child class
classC extendsP
{
// Qverriding geeks method
function geeks()
{
echo"\nchild";

}
/?/ Reference type of parent
Sp= newP;
// Reference type of child
$c= newC;
// print Parent
$p->geeks();
#7 Print child
$c->geeks();

the process in PHP to create a copy of an object. An object copy


is created by using
ord (which calls the object’s _ _clone() method if possible). An object's
_ _clone()
lied directly.
cloned, PHP will perform a shallow copy of all of the object's properties. Any
es to other variables will remain references.
= clone $object_to_be_ copied

Scanned with CamScanner


Web Based Application Development with PHP Apply Object Oriented Concepts in Pap 1

// Creating clone or copy of object


$copy= clone$obj;
// Set values of $obj object
$obj->datal = "PHP";
$obj->data2 = “with";
$obj->data3 = “Web";
// Set values of copied object
$copy->datal = "Computer";
$copy->data2 = "IT ";
$copy->data3 = "Portal";
// Print values of $obj object
echo "$obj->datal$obj->data2$obj->data3\n";
// Print values of $copy object
echo "$copy->datal$copy->data2$copy->data3\n";
>>
Output:
PHP with Web
Computer IT Portal

Introspection is the ability of a program to examine an object's characteristics, such as its name,
R

parent class (if any), properties and methods,


ion allows us to:

debuggers, serializers, profilers etc.


PHP offers the useful ability to examine classes, interfaces, properties, and
pection, we can write code that operates on any class or object.

the ie eective functions provided by PHP are class exist(),

fined class, FALSE otherwise.


a

Scanned with CamScanner


3.11 Apply Object Oriented Concepts in PHP
web pased lication Development with PHP

syntax: gmethods = get_class_methods (classname) ;


For example,
<?php
class myclass
{
function myclass(){}
function myfunci(){}
}
$my_class = new myclass();
$class_methods = get_class_methods('myclass');
print_r($class_methods); // Array ( [@] =>myclass [1] => myfunc1 )
?>
3. get_class_vars():
» This function returns an array of default properties of the class. It returns an associative array with
property's name value pairs.
Syntax: $properties = get_class_vars(classname);
For example,
<?php
class myclass
{
var $v1; // $v1 is not set, NULL value is set by default
| var $v2 = 100;
}
$my_class = new myclass();
$class_vars = get_class vars('myclass');
var_dump($class vars); // array(size=2)'v1' => null'v2' =>int 100
?>
arent_class():
either an object or class name as parameter. It returns the name of the parent class, or false if
parent class.
class = get_parent_class (classname);
g an Object
ject the introspection uses following functions:
» if passed parameter is an object.
object(var);
he name of the class of an object.
get_class($object);
1ame passed as the parameter is not an object.

. $method_name);

representation that can be stored into a


sessions automatically save and restore

ae oa

Scanned with CamScanner


ly Object Oriented Conce J
Wed Based Application Development with PHP oe 3.12 Eee |
= ; i ,
r own form o F Persisten
* We can use two functions serialize() and unserializeQ) to implement 00
objects.
For example,
$encode = serialize (somedata);
$somedata = unserialize (encode); :
r epresentationas of any: value that can be
e serialize() method returns a string containing a byte-stream the original variable values,
in PHP. unserial ize() method can use this string to recreate
stored
Syntax: string serialize(mixed $value) f : ‘
but the functions will not be
* While saving an object, all the variables of the object will be saved,2 a file. |
be stored
saved, After serialization of an object the byte version can
must be defined in that file. This can be done
* Tounserialize() an object in another PHP file , the class
by including file where the class has been defined.
Syntax: mixed unserialize(string $string)
then the object js
© The followi ng program shows how object is serialized and stored in a text file,
‘alized

<?php
_ €lass Student
nt
_ var Sage = 10;
_ functionshow_Age()

ize ($stud); // $stud is serialized, converted to string


"w")5
341 storing serialized obj into the file

y objects that they are being serialized or unserialized.

s that they are being serialized or unserialised. serialize()


magic name __sleep(). If so, that function is executed

M an array with the names of all variables of that


return anything then Null is serialized. The -
fhich do not need to be saved completely:
the magic name __wakeup)(). If present, this

Scanned with CamScanner


web 84 lication Development with PHP 3.13 Apply Object Oriented Concepts in PHP

private $name;
private $credit_card_no;
public function __construct($name, $credit_card_no)
{
$this->name = $name;
$this->credit_card_no = $credit_card_no;
}
public function _ sleep()
{
echo "Sleep calling <br>";
return array('name', ‘credit_card_no');
}

public function _ wakeup()

{
echo "Wakeup calling <br>";

}
$c = new Customer("Amar", 1234567890);
$data = serialize($c);
echo $data . "<br>";
print_r(unserialize($data));

"Customername";s:4:"Amar“;s:24:"Customercredit_card_no”;i:1234567890; }

Scanned with CamScanner


il
a = ar c Ye ee

ants men ; rT?wae ie re i i et pe = yi

Use the relevant form controls to get user's input.


Design web pages using multiple forms for the given problem.
=

Apply the given validation rules on form.


=

Set/modify/delete cookies using cookies attributes.


=

Manage the given session using session variables.


i.

oe a Webpage using GUI Components


g with Multiple Forms in PHP
m and Web Page Validation in PHP
1 Basic Concepts in Cookies with its Types

a standard in the world of a programming with | its simplicity,


ibility and speed. One of the most powerful feature of PHP is the way it

Authenticate user
Add data to database

Scanned with CamScanner


Web Based Application Develo Creating and Validatin
pment with PHP 4.2
att
* A form is an HTML ta
boxes, radio buttons g the contains Graphileal UBee Hatgete 17 )
etc. The basic adva 4, ditomnatical
ce lytifieshythe
form element, ntage of using PHP scrip
* The form is defined usin g the <form>...</form> tags and ‘
such as input, GUI item s are defined using 8 f form lemen, |
4.1 ic)

A aga that containing blank fields, at the user can fill the data or user can select the data :
own as Form,
* Generally, the data will store in the database. We can
we need to use PHP superglobals $ GET
create and use forms ini PHP. To get form data
and $_POST.
* The form request may be get or post. To retrieve data
request $ POST.
from get request, we need to use $_GET, fo, Post
mata Browser Role GET and POST Methods j

* There are two HTTP meth


ods that a client can use to pass form data
ie., GET and POST. The method is specified with the meth to
od attribute to the <form> tag,
the Server
1. GET Method:
* The GET method sends the encoded user information
appended to the page request (to the URL), The |
Page and the encoded information are separate
d by the ? character.
http://www.test.com/ index.htm?name1=valu
e1&name2=value2
* The GET method produces a long strin
g that appears in our server logs, in the
Location: box. The GET method is restricted to browser;
send up to 1024 characters only,
* Never use GET method if we have pass
word or other sensitive information to be
GET cannot be used to send binary data, like sent to the server,
images or word documents, to the server,
* The data sent by GET method can
be accessed using QUERY_STRING envi
provides $_GET associative array to acces ronment variable. The PHP
s all the sent information using GET
Example: For putting the source code in method.
test.php script,
<?php
if (isset($_GET["s1” }) )
{
echo “Welcome ", $_GET['name']. "<br fees
echo “You are ", $_GET['age'].
“ years old.";
>

— kbody>
orm action="<?php $ PHP_SELF?>" method="GET"s
<input type="text" name="name" /><brs
: <input type="text” name="age" /><br>
ut type="submit” name="51" value="0k"/>

Scanned with CamScanner


wed B sed lication Development with PHP 43 and V: Forms

enter name and age and submit the form. Now PHP will process the form and we will get the
following output:
[y http://localh...&age=258s1=Ok * Veale

\€2@ locathost/te:t php?name=BiancaBiage=256s1= Ok


Welcome Bianca
You are 25 years
old.

After submitting the form the URL in the address bar is as follows:
http://localhost/test.php?name=Bianca&age=25&s1=Ok
It shows all the three form parameter’s name/value pairs.
After
In the program, the isset() method is used to check whether the “Ok” button is pressed or not.
the
entering name and age submitting the form will store the entered value of the text field into
¢ GET array, and that can be displayed.
_ POST Method:
The information is
The POST method transfers information via HTTP headers, not through the URL.
encoded as described in case of GET method and put into a header called QUERY_STRING.
used
The POST method does not have any restriction on data size to be sent. The POST method can be
to send ASCII as well as binary data.
. By
The data sent by POST method goes through HTTP header so security depends on HTTP protocol
using Secure HTTP we can make sure that our information is secure. The PHP provides $_POST
associative array to access all the sent information using POST method.
Example: For putting the source code in test.php script.
<?php
if(isset($ POST["s1"]) )
{
echo "Welcome ". $ POST[’name']. "<br />";
echo "You are ". $ POST['age']. " years old.";
}
?>
<html>
_ <body>
<form action="<?php $_PHP_SELF?>" method="POST">
Name: <input type="text” name="name" /><br>
/ <input type="text" name="age" /><br>
type="submit" name="s1" value="0k"/>

oi ail

Scanned with CamScanner


Web Based Application Development with PHP 44 Creating and Validatin — ’
The output of the above program is same, except URL, the URL in the address
bar will not get changeq
after submitting the form.
GET vs. POST Methods:
Both GET and POST create an array (example, array( key => value, key2 => value2, key3 => value3, ~))
This array holds key/value pairs, where keys are the names of the form controls and values
are the
input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they
are always accessible, regardless of scope - and we can access them from any function, class or fj),
without having to do anything special.
The biggest difference between GET and POST requests is that, GET requests are idempotent i.e, one
GET request for a particular URL, including form parameters, is the same as two or more requests for
that URL. Thus, web browsers can cache the response pages for GET requests, because the responsa
page does not change regardless of how many times the page is loaded. Because of idempotence, Grr
requests should be used only for queries such as splitting a word into smaller chunks or multiplying
numbers, where the response page is never going to change.
POST requests are not idempotent. This means that they cannot be cached, and the server js
recontacted every time the page is displayed. We have probably seen the web browser prompt us
with “Repost form data?” before displaying or reloading certain pages. This makes POST requests the
appropriate choice for queries whose response pages may change over time-for example, displaying
the contents of a shopping cart.
When
to use GET?
Information sent with the GET method is visible to everyone (all variable names and values are
displayed in the URL). GET also has limits on the amount of information to send. The limitation is
about 2000 characters. However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information.
When to use POST?
Information sent with the POST method is invisible to others (all names/values are embedded within
the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while
uploading files to server.
t
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
| Server Role
PHP is a server-side scripting language. Using PHP we can create dynamic web sites. That means its
processing happens in the server by consuming server's resources and sends only the output to the
client.
In a client-side scripting language like JavaScript, processing happens in the client’s computer
consuming its resources.

Request for
welcome.himl
| welcome.html
and send itas ©
_ the response

Server

Response for welcome.htm|

Client
Fig. 4.2: Cycle ofa Normal Web Request

Scanned with CamScanner


Web Based Application Development with PHP 4.5 Creating and Validating Forms
ee i

Request for
welcome.php

PHP Engine

Server

Response for welcome.php

Client

Fig. 4.3: Cycle of a Web Request that involves PHP

Example:
welcome.php
<html>
<head>
é<title>Welcome to Our Web Site</title>
</head>
<body>
<hl>
<?php
if (date('G') < 12)

echo ‘Good Morning!';


}
else
{
echo 'Welcome!';
}
te
</hi>
<p>Rest goes here...</p>
</body>
</html>
Output:
€ > © OD lecalhost/welcome,php

Good Morning!

ant types of form controls that we can use to collect data using form namely,
x, Radio button, and so on.

user to enter
a single line of text.
(input Bom), text field (input field) or text entry box is a graphical control
D
ie Lio aput text information to be used b the program
r- ODE S'SI UT
Web Based with PHP s6
<form action="welcome.php” met hod="get ">
<input type="text" name="user />
:
MIT” />
i <input type="submit" value="SUB
</form> : z
</body>
' e folder as above welc
hae
Name the following script as welcome.php and put it eee. omeh

eee
file. It accepts the value from the text field by using field
3
Me

+ "e/b><br/>
.
srry
echo "Welcome <b>" . $ GET [‘user']
? 7
|

Output:
:

hitp://local...vitSomwanshi x |
a)
c : + 1D localhost/welcome.php7user=Ray:.<.

Welcome Ravi Somwanshi

lines of tex.
* Atextarea field is similar to a text input field, but it allows the user to enter multiple
i * Unlike most other controls, an initial value is placed between the <textarea> ... </textareas tags
_ father than in a value attribute.
a Example: Name the following script as textarea.html. It has a text area and a submit button.
a _ thtmi>
<body>
P a me <form action="textareal.php" method="get">
<textarea name="address" rows="5" cols="40"></textarea>
ae <input type="submit” value="SUBMIT" />
</form>
pilot?
= : ’
: ‘ > the following script as textareai.php. It reads the value from the textarea
from the form

“Your address is: <br/><b>" . $ GET ['address*] . "</p>".


. 2

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
444
yon Based Aoplation
ication Development with PHP Creating00 Vesting Foxes
output: > © socathost/mutipletorms.php
—Form 1:

ficana Publication
Write message here: a

{ Send Ema
Form
2 is Calling

Form having Multiple Submit Buttons


+ First let we know, how to use multiple submit buttons in a HTML form and how PHP handle it.
Usually a HTML form has only one submit button but there are situations when we might need to use
more than one submit buttons and PHP check which button has been pressed and an action to be
done according to the button pressed.
¢ Having multiple submit buttons and handling them through PHP is just a matter of checking the
name of the button with the corresponding value of the button using conditional statements.
Example:
<html>
<head><title> Button Demo </title></head>
<body>
<h4> Form having multiple submit buttons </h4>
<?php
switch($ REQUEST['btn_submit'])
{
case "Button 1":
echo "<h4>You pressed Button 1</h4>";
break;
case "Button 2”:
echo "<h4>You pressed Button 2</h4>";
break;
case "Button 3":
echo “<h4>You pressed Button 3</h4>";
break;

form method="post» 1" /><input


2="submit” name="btn_submit" class="button” value="Button
class="button" value="Button Fn be s
mit" name="btn_submit” [>
type="submit” name="btn_submit” class="button” value="Button 3

Scanned with CamScanner


TE
Web Based Application Development with PHP 4.12 —— NSE |

Output:
© > S_ O bocathost/outtont
Form having multiple submit buttons
You pressed Button 2
| Button 1, || Button 2 | Button 3 | Se

of <

* Validation means check the input submitted by the user. There are two types of validation, ate
; available in PHP,
oa Two types of validations are:
1. Client-Side Validation: Validation is performed on the client machine os browsers.
2. Server Side Validation: After submitted the data, the data has sent to a server and Perfor,
validation checks in server machine.
* Some of Validation Rules for fields:

a Name Should ers and


ti 3 Email Should ed @ and.
7 ite: as | Website a valid URL.
¢? Must be selectable at least once.
2) Check Box Must be checkable at once.
1p Down menu Must at least once.

ine variables and set to empty values


= $emailerr = $genderErr = $websiteErr =".
ee il = $gender = $comment = twebsite an ame
RVER["REQUEST_METHOD"] == "POST") { ,
OST["name"])) {
Name is required";

—input($_POST[“name"])
;

di

Scanned with CamScanner


Scanned with CamScanner
} Based Creating and Vaj; .
Web Based Application Development with PHP ee

</table>
</form>
<?php
echo "<h4>Your given values are as:</h4>"3
echo $name,"<br>";
echo $email."<br>";
echo $website. "<br>";
echo $comment."<br>";
echo $gender."<br>";
?>
</body>
</html>
Output:

isSalallbcg © locathost/validationphp
I Somwanshi Sir Classes Registration Form
= * required field.

a Bema: [|* valid email format

‘Classes:

Py Gender: @ Female @ Male*

d by the browser on the client machine.


tion is used by the application running on the server side to custom
ize the web page
the past history of transactions from that client machine.
send one or more cookies to a browser in the headers of a response, Some of
the cookies
2 the pages for which the browser should send
the cookie as part of the request.
y data they like in the value field of the coo
er, preferences, etc.
kie (within limits), such as a unique
of information
ine Wealso which is stored at cli ent bro i } used
$ are knownas web cookies, HTTP wa
cookies or browser cookies.

ee
. : cookie
way, ser. Each time when client sends request
can be received at the server side:
nequest + Cookie

Scanned with CamScanner


job Based Applica! ion Development with PHP 4.15
short, cookie can be created, sent ——Creating and Validating Forms
and received at Server end. Use the
’ as e to the browser. Like header(), set i ‘
setcookie() mus be called before oe
client browser because cookies are set in the HTTP headt ers, which must be sent befoae s eas
re Soe ee the
: The setcookie() function can be
; used to delete a cookie. For deleting a cook
: ed by passing the cookie name and ie, the se i
other argument s or em tri
i Paptation date is required to be set in the past. eee
Types of Cookies
The types of cookies are explained below:
session Cookies:
session cookies also called a transient
cookie, a cookie that is erased when
The session cookie is stored in temporary we close the Web browser
memory and is not retained after the
Session cookies do not collect information from browser is closed
the computer.
+
Session cookies, are temporary means they y
are stored temporarily in memory and are
removed when the browser closes or the sess automati
ion ends.
+ Session cookies expire at the end of the oe
session, This means, when we close our
session cookie is deleted. This website only browser window, the
uses session cookies,
2. Persistent Cookies: A
« Persistent cookies do not expire at the
end of the session, Persistent cookies
cookie, or a stored cookie. A cookie that also called a permanent
is stored on the hard drive until it expires
are set with expiration dates) or until we dele (persistent cookies
te the cookie,
* Persistent cookies are used to collect identify
ing information about the user, such as Web
behavior or user preferences fora specific Web surfing
site.
Use of Cookies
A cookie is often used to identify a user. A cooki
e is a small file that the server embeds on the user's
computer.
* Each time the same computer requests a page with
a browser, it will send the cookie too. With PHP,
we can both create and retrieve cookie values.
* HTTP is a stateless protocol; cookie
s allow us to track the state of the application using small
Stored on the user’s computer. The path were the cookie files
s are stored depends on the browser. Internet
Explorer usually stores them in Temporal Internet Files folder.
* Personalizing the user experience - this is achieved by allowing users
to select their preferences. The
page requested that follow are personalized based on the set preferences in the cookies
.
* Cookies are used for tracking the pages visited by a user,

* To read data from a cookie, we first have to check if the cookie actually exists. This is achieved
through the isset() function. .
* The isset() function is used to check for the existence of a variable, in this case, a cookie variable
through the use of the $_COOKIE associative array which stores an array of existing cookies.

isset($ COOKIE['nameOfCookie' ]); —


_* Tf the cookie specified in the isset() function exists, then the function will return true, otherwise it
—Wwill return false.

Scanned with CamScanner


Ap plic ition Develop: with PHP
: of a cookie named cookie1, i¢
above example, an if statement checks for the eee ae not, then it will remain empanit
en its value will be passed to the variable $cookiel- The
function checks for this.
tribute of Cookies
syntax shows attributes of cookies: :
httponly)
E
value, expire, path, domain, secure,
detail o¢al th
arameter isEe ired: All other parameters are optional. Here, is the
in above syntax: :
called $_COOKIE. This Variabie
lame of the cookie, stored in an environment variable
accessing cookies.
ue of the named variable. : |
UNIX timestamp denoting the time at which the cookie will expire.
bs the directories for which the cookie is valid. A single forward slash characte,
kie to be valid for all directories.
yser will return the cookie only for URLs within this domain. The default js ¢,
fy that the cookie should only be sent by secure transmission
oh mean cookie can be sent by regular HTTP. |

€ value, time() + (86408 * 39), "l")3 // 86400 =

the value of t#

Scanned with CamScanner


Scanned with CamScanner
Web Based lication Development with PHP and Vy,
4,18

Advantages of Cookies ;
a Ho dat Cookies are easy to ee The fact that cookies are SUPPorteg Ont,
Occupies Less Memory: Cookies de not require any server resources and Ae stored ont, Mee

4.
ec
Peirce cn eee
sta pe re al
easier to use. This is the reason why they
enabled and disabled from the client's side.
5. Fast Speed: The cookies make browsing the Internet faster
Disadvantages of Cookies;
1, Not Secured: As mentioned previously, cookies are not secure as they a a in the clear te,
they may pose a possible security risk as anyone can open and ASS ones:
2. Difficult to Decrypt: We can manually encrypt and decrypt cookies, but it requires extra ¢,;- :
ra can affect application performance because of the time that is required for encryptio, and
ecryption.
Limitations in Size: Several limitations exist on the size of the cookie text (4kb in general), 4,
number of cookies (20 per site in general). Each site can hold only twenty cookies.
4. Can be Disabled: User has the option of disabling cookies on his computer from the
browser,
Setting. This means that the user can decide not to use cookies on his browser and it will stijj
work.
5. Users can Delete Cookies: The fact that users can delete cookies
from their computers gives
them more control over the cooki:

i
{ A session is a way to store information (in variables) to be used across multiple
| p
us to store data on the web server that associated with a session ID. Once we create
a session, PHP
sends a cookie that contains the session ID to the web browser.
In the subsequent requests, the web browser sends the session ID cookie back
4 to the web server so
that PHP can retrieve the data based on the session ID and make the data
available in our script.
e An alternative way to make data accessible across the v arious pages of an entire
website is to usea
PHP Session. ;
i * Asession creates a file in a temporary directory on the server where registered
session variables and
4 their values are stored. This data will be available to all pages on the site
*
during that visit.
The location of the temporary file is determined by a setting in the php.ini file called
session.save_path.
Use of Session
In general, 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 ey j sion based
environment. The SID is used to link the user with his informati On Seeaeay seri
on the serve r olikes'sct
posts, € i

Scanned with CamScanner


4.19
web Based Application Development with ERP
Creating and Validating Forms

why shoulda session be maintained?


when there is a series of continuous request and response from a same client toa server, the server
cannot identify from which client it is getting requests.
Because HTTP is a stateless protocol. When there is a need to maintain the conversational state
session tracking is needed.
Start Session
. Asession is started with the session_start() function, The session_start() function first checks if a
session is already started and if none is started then it starts one.
session variables are set with the PHP global variable $_SESSION. The $_SESSION[ ] variables can be
accessed during lifetime of a session.
Example: For start session.
demo_sessioni.php
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
/{ Set session variables
$ SESSION["favcolor"] = "green";
$ SESSION["favanimal"] = "cat";
echo “Session variables are set.";
?>
</body>
</html>
Output:
Session variables are set.
¢ Makeuse of isset() function to check if session variable is already set or not.
_a-e% Get Session Variables
* Next, we create another page called "demo_session2.php". From this page, we will access the session
information we set on the first page ("demo_session1.php").
* Note that session variables are not passed individually to each new page, instead they are retrieved
from the session we open at the beginning of each page (session_start()). Also notice that all session
variable values are stored in the global $ SESSION variable.
Example: For get session variables.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// echo session variables that were set on previous page
echo “Favorite color is " . $ SESSION["favcolor"] . ".<br>";
_ @cho “Favorite animal is " . $ SESSION["favanimal"] . ".";
| ESE
Creating and Va)
Web Based Application Development
with PHP 4.20 ——
Erez |
Destroy Session
* To remove all global session variables and
jon, use session_unset()
S€ssion_destroy() functions destroy the sess an
.
° The Session_destroy() function does not need any argument and a single call can destroy all th


Session variables, ie

Example: For destroy sessio


n.
<?php

SS
session_start();
2>
<!DOCTYPE html>
<html>
<body>
<?php
|
// remove all session variables
session_unset();
// destroy the session

ee
session_destroy();
?>
</body>
</html> |
Difference between Session and Cookie: _ a
a
i fe Gaett Moet ont]
—) a. i eA = Sis
A e
Game teuSension”:—
= — A
- . | k

| i: Cookies are stored in browser as text | Sessions are stored in server side. i
, file format. f
2: The cookie is a client-side resource. The session is a server-side resource. |
ae It is stored limit amount of data. It is stored unlimited amount of data. |
4, Itis only allowing 4kb [4096bytes]. It is holding the multiple variable in ;
| , sessions. |
| 5. It is not holding the multiple variablein | It is holding the multiple variable in i
tl cookies. sessions.
We can accessing the cookies values in | We cannot accessing the session values in
= easily. So it is less secure. easily. So it is more secure.
Setting the cookie time to expire the | using session_destory(), we will destroyed
| cookie. the sessions.
a The setcookie() function must appear | The session_start() function must be the
- before the <html> tag. very first thing in your document. Before
any HTML tags.
Usually contains an id string. Usually contains more _ complex
information.
Specific identifier links to user
.

—— eB Se e2
using PHP we must configure the php.ini file with the details of how the system se"

Scanned with CamScanner


squnene sensing orien PHP 481 Cr Val fi
me configuration for Linux should look something like this;
* mtp *
Spndnail_ from -
» forunix only
/usr/sbin/sendmall «t <1
sendmail_path =
Function:
ae mol
PHP use function to send an e-mail, This function requires three mandatory arguments that
the recipient's e-mail address, the subject of the message and the actual message,
. dditionally there are other two optional parameters.
*
Syntax: bool mail(string $to, string $subject, string $message
[, string fadditional_headers [, string $additional_parameters }})
. Here, is the description for each parameters,

(seno to Required, Specifies the receiver / receivers of the email.


2 subject Required, Specifies the subject of the email, This parameter cannot contain
any newline characters.
r3, | message Required, Defines the message to be sent, Each line should be separated with
a LF (\n), Lines should not exceed 70 characters,
a headers Optional, Specifies additional headers, like From, Cc, and Bec. The additional
headers should be separated with a CRLF (\r\n).
5 parameters Optional. Specifies an additional parameter that can be used to pass
additional flags as command line options to the program configured to be
used when sending mail, as defined by the sendmail_path configuration
setting.
Return Values:
« Returns True if the mail was successfully accepted for delivery, False otherwise.
Following example will send an email message to 'name ® company .com’,
Example:
<?php
Function sanitize_my_email($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
$to_email = ‘name @ company .com';
$subject = ‘Testing PHP Mail';
$message = 'This mail is sent using the PHP mail '; 4
$headers = 'From: noreply @ company. com';
//check if the email address is invalid $secure_check
$secure_check = sanitize _my_email($to_email);
if ($secure_check == false) {
echo "Invalid input";
} else { //send email
mail($to_email, $subject, $message, $headers);
cho "This email is sent using PHP Mail”;

Scanned with CamScanner


EE

Mb Based Application Development with PHP 4.28


te
How to configure XAMPP to send mail from localhost using y PHP?
fol der
Fiteak
Wom 2o08 | my
, il
:
10a gov The
gord 170 fila foldet
ioe

in
are
File Folder sendmail.ini
Homan 129
OF 122000 4 file folder
11.00.2000 1029 Vile folder
webal
1)-0H-2008 1701 File folder

Step 11 Go to €:\xampp\sendmail: open sendmail.ini file in notepad or any text editor and m ake the
~

changes as follows:
smtp_server=smtp.gmail.com

5 auto = use SSL for port 465, otherwise try to use TLS
3 6 $81 = alway use SSL
3 tls = always use TLs
5) None = never try to use SSL

smtp_ssl=tls
ep:2 Go to C:\xampp \php: open php.ini file
ke the changes as follows. in notepad or any text editor goto [mai
l function] part and
: on (mad function]
_ i /

i SMTP=localhost
php. net/smtp-port
Gintp_ports25 }smtp_porte25

J For Wina2 only.


i _http://phosn ndmail- from
Riduail_
= me@exanp
from le. emp ; sendmall_froms
[email protected]
J For Unix only. You may Supp
net/sendmail-path ly arguments as wel) (default: "sendmaiy -t <i"),
*endmall_path=C:\xampp\sendmail\sendmail
,exe en cag
8x8

m? How to create it?


control?

Scanned with CamScanner


Insert data in the given database using PHP script.
(™ Apply the specified update operation in database record using PHP script.
™@ Delete the given record from the database using PHP script.

#) Tounderstand Concept of Database and DBMS


™ To study Basic Concepts in MySQL
® To learn Connectivity to MySQL Database
™ Tounderstand Database Operations

* Adatabase is a collection of related data. A database is a collection of informa


tion that is organized
so that it can easily be accessed, managed and updated. With PHP, we can
connect to and manipulate
databases.
* A DataBase Management System (DBMS) is system software for creatin
g and managing databases.
The DBMS provides users and programmers with a systematic way to create,
retrieve, update and
Manage data.
* Nowadays, we use Relational Database Management Systems (RDBMS) to
store and manage huge
volume/amount of data. PHP will work with virtually all database software
, including Oracle,
PostgreSQL and Sybase but most commonly used is freely available MySQL database.

Sa ee ee eee ki
* A PHP is very flexible with MySQL database compared with other databases. The data transfers
n the PHP script and MySQL database very smoothly and flexibly.
Nowadays MySQL is the most popular open source Relational Database Management System
(RDBMS), The data in the MySQL database is stored in the form of tables.
* MySQL works very well in combination of various programming languages like PERL, C, C++, Java
and PHP. Out of these languages, PHP is the most popular one because of its web application
development capabilities.
PHP provides various functions to access the MySQL database and to manipulate the data records
inside the Mysql database.

ive and powerful database packages. It uses standard SQL i.e mn”
‘same as SQL. It deals with C, C++, PHP, Java and so on and o

Scanned with CamScanner


Web Based Application Development Database
with PHP ba
MySQL works quick and handle even with tremendous information sets. It is neighborly to Py
Most section on dialect for web improvement. P, the

Unix/Linux

Windows/ MySQL
vee PHP
255 = — ~ _ = 4 =

SQL Query

7 Result Set |
Client =
|
rmei Server
' Fig. 5.1: Working of MySQL Database with PHP
s MySQL
- PHP Syntax:
* PHP provides various functions to access
the MySQL database and to manipulate
the data recor4;
ir inside the MySQL database. We would require to call the PHP functions in the same way we cal] any
other PHP function,
* The PHP functions for use with MySQL have the following general format/syntax:
Syntax: mysql_function(value, value,...);
* The second part of the function name is specific to the function, usually a word that describes what
_ the function does. The following are two functions, which we will use in this
a7 chapter
mysqli_connect ($connect);
mysqil
so i_query($connect,"SQL statement");
e ie following example shows a generic syntax of PHP to call any MySQL function.

31 = mysql _function(value, [value,., his


!$retval )
ae ea

di
Scanned with CamScanner
ae p 5.4
pplication Development with PHP Database Operstions
wep Based AP

createa Database
seisa collection of data. MySQL allows us to store and retrieve the data from the database in
5 A databa ‘ay
+ n * . 7 ~“) an
an
4
al we can create a database using the CREATE DATABASE :statement. But, if database already
| T
. InMy ; ro r. To avoid the error, we
po can use the IF NOT EXISTS option with the CREA
rows an er |
exits, it th
staternent.
DATABASE Line Client. Open the MySoL cons
ole and
se by using MySQL Command 2
can create a MySQL databa
e wh il e in st al la ti on . W e wi ll get the following:
wat vown password, if we set on Coert TS hepa eea
BB 42058 Conard ure
ee ee e |
a CQL connection id 4
veer ee ee

Copyright (c> 2088, 2011, Oracle and/or ite UeOU PC Pe ee |

i a a ee ee
. Other nanos nay be tradenarks of their respective

eM

Now we are ready to create database.


Syntax: CREATE DATABASE database_name;
Example: CREATE DATABASE employees;
as ard Line Chant
_
De e
Lae eee rd
Ae ee ee

Copyright (c) 2088, 2011, Oracle and/or its affiliates. All rights reserved.

a registered tradenark of Oracle Corporation and/or its


ee) ee ee eee ey

ee ee | ee eS ee

ee ae ere

* Wecan check the created database by the following query:


SHOW DATABASES;
Output:

hs ies

De Scanned with CamScanner


_—iil
Ol
Web Base
Sedd Application Development with
Database
PHP 54 QL database.
Note: PHP also uses mysql_query() function This function takes
S
Parameters and returns True on success or False
to create a * Wig
on failure.
Syntax: bool mysql_query(sql, connection);
PHP provides function mysql _select_db() to selec It returns True on success or False of
t a database.
failure.
Syntax: bool mysql_select_db(db_name, connection);

* PHP will work with virtually all database soft


ware, including Oracle and Sybase but most
used is freely available MySQL
database.
ommonly
PHP 5 and later can work with a MySQL data
base using:
1. MySQLi extension (the "i" stan
ds for improved), and
2. PDO (PHP Data Objects).
waza MySQL Database Server fro
m PHP
* There are two functions of PHP
to connect MySQL database namely,
PDO::__construct(). mysqli_connect() ang
weaned Mysqli_connect() Function
The mysqli_connect() function is used to conn
ect with MySQL database. It returns resource
connection is established or null. if
| Syntax: resource mysqli_connect(server » username,
password)
Example: For welcome.html file and it
has a text field and submit button.
<?php
$host = ‘localhost: 3306';
$user = '';
$pass = '';
$conn = mysqli_connect($host,
$user, $pass);
if(! $conn )
{
die('Could not connect: ' + mysqli _error() ye
}
echo ‘Connected successfully...';
mysqli_close($conn);

d successfully

€ to switch our project


to use another q
€ the connection string and a few queries PDO makes the process easy. We om

array $o tions IJ]

Scanned with CamScanner


Scanned with CamScanner
echo "Record inserted successfully...”
Jelse{ gconn)5
w, mysql i_erron(
echo "Could not insert record:
}
mysqli_close($conn);
?>
Output:
Connected successfully...
I) a
Record inserted OT, a
Mysq. table
Retrieving the Query Result pa ta can be fetched from
ute select query:
* PHP mysql_query() function is used to exec ne ct ion mysql _query()-
emen t thro ugh PHP fu
by executing SQL SELECT stat
functions used in select query-
¢ There are two other MySQLi of rows.
whi turns number y
t) sociative array. Each ke of
$re sul ic h re
1, mysqli_num_rows(mysql i_result h re tu rn s ro w as an as
c(mysqli_result $result) whic
2. mysqli fetch_asso table. It return NU
LL if there are no more row
s,
the
ts the column name of
=,

the array represen


all Example: For retrieving data.
“4: <?php
; ghost = ‘localhost:3306';
- $user = '";
oe

$pass = ''5
omen $dbname = ‘test’;
$conn = mysqli_connect($host, $user, tpass, $dbname) ;
if(!$conn){
die('Could not connect: ' mysqli_connect_error());
}
echo ‘Connected successfully...<br/>';
$sql = ‘SELECT * FROM emp4';
$retval=mysqli_query($conn, $sql);
if (mysqli_num_rows($retval) > 0){
Saat w= mysqli_fetch_assoc($retval)){

"EMP NAME : {$row['name']} <br> ",


"EMP SALARY : {$row['salary']} <br> ",
i» me e@eeee ese een eee eee ee
ge ie ic <Dp>"s
ie

Scanned with CamScanner


Scanned with CamScanner
Web Baseq D "
~——=S8e Application Development with PHP 5.8 ——S—
$dbname = ‘test’;
$conn = mysqli_connect(¢ho $user,
$pass, $dbname) 3
st,
if(!$conn){
) die('Could not connect: ' smysqli_connec
t_error());
}
echo ‘Connected successfully...<br
/>'s
$id=2;
; $sql = “delete from emp4 where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record deleted successfully...
"}
felse{
echo "Could not deleted record: ". mysqli_error($conn);
5
mysqli_close($conn);
: ?>
Output:
Connected successfully...
Record deleted successfully...

so u=Ceela-me]il- ale) its


1. What is database?
2. What is DBMS?
3. What is MySQL? How it is used in PHP?
4, How to create and delete a database in MySQL?
5. Explain mysqli_connect() function with example.
_ 6. ‘Explain PDO::__construct()function with example.
~ 7. Write a program to create an employee table to perform insert, delete and update operations.
_ 8. How toconnect database to MySQL? Explain with example.
_ 9. Howto insert a record in table in MySQL with PHP?
_ 10. How to update a record in table in MySQL with PHP?
1 How to retrieve a record in table in MySQL with PHP?

Scanned with CamScanner


<— program for Math function.
. ehtml>
<head>
<title> Using the math functions </title>
</head>
<body>
<hi> Using the math functions </hi>
<?php
echo "tan(deg2rad(40)) = ", tan(deg2rad(4e@)), Ssope"
echo "pow(4,4) = ", pow(4,4), "<br>";
echo "floor(3.14159) = ", floor(3.14159), "<br>";
?>
</body>
</html>

aeoe

Using the math functions


tan(deg2rad(40))= 0.83909963117728
gow a= cal

2. Program for = operator precedence.


<html>
<head>
<title>Setting Operator Precedence</title>
</head>
<body>
een

<hi> Setting operator precedence </h1>


<?php
echo "5 +3*10=", 5+ 3 * 10, "<br>";
echo "(5 + 3) * i@ =", (5 + 3) * 16, "<br>";

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
= $factorial * $x;

orial of $num is $factorial”;

can calculate factorial of any number.

in PHP</title>

Scanned with CamScanner


Scanned with CamScanner
r pplication Developme
withnt
PHP P.6
Program checks whether given number is Armstrong or not input
should be

<head>
<title> To find number is Armstrong or not <title>
</head>
<body>
<form method = “post”>
a Enter the Number: <br>
_———s <input type = “number” name = “number”>
ar <input type = “submit” value = “submit”>
a. </form>
Ty </body>
, </html>

; oe

eect he number entered


= $_POST[ ‘number '];
core entered number in a variable
$number;
= 6;
loop till the quotient is 9

a % 18; //find reminder


um + ( $rem * $rem * $rem ); //cube the reminder and add it to the
till the loop ends
10; //find quotient. if @ then loop again

j number and $sum value matches then it is an armstrong number

yer an Armstrong Number";

Armstrong Number";

="
Scanned with CamScanner
Scanned with CamScanner
a jon Development with PHP pb
a oe return 0;
a jelse Af ( $num wm 1){
return 1;
} else {
return (series($num-1) + series($num-2))5
2
/* Call Function, */
for ($1 = 0; $1< $num; $14+){
echo series($i);
ls echo "\n";

ba v }

ra >

gram to find reverse


of a number.
<?php
$num = 1234;
2 $revnum = 9;
“ while ($num> 1)

4 m = ($revnum * 10) + $rem;


um = ($num / 18);

Scanned with CamScanner


Scanned with CamScanner
Development with PHP C—O

The sum of 45 and 14is: 59

21, Program to calculate area of rectangle.


<html>
<body>
i <form method = "post">
Width: <input type="number" name="width">
<br><br>
_ Length: <input type="number" name="length"><br> 2
<input type = "submit" name = “submit” value="Calculate >
_ </form>
</body>
</html>

if(isset($_POST['submit']))

= $_POST[ 'width'];
gth = $_POST['length'];
rea = $width*$length;
echo "The area of a rectangle with $width x $length is $area";

Scanned with CamScanner


lic
eb
lowing triangle pattern:
print the f°

- range('A’, 'Z');
<?php

galpha © gic5; $it+){


-05 $3coS8is S3++){
echo($igalpha[ $i];
for
= "<br>"3
}

a
print the triangle pattern:
— ocatom <?php Alero
galpha = range( Ags Zz )3
for($i=O; $i<5; $it+){
for($j=0; $3<=$i; $5++)1
echo $alpha[$j];
}
echo "<br>";

<?php
$alpha = range('A’, ‘Z');
for($i=0; $i<5; $i++){
for($j=4; $j>=$i; $j--){
écho $alpha[$3];
}
echo "<br>" 3

———

Scanned with CamScanner


—OO —————
lll
Web Baseq lication Develo nt with PHP
Peta
26. Program to Print th
e following triangle pa ‘
55555 ttern.
4444
333
22
2,
<?php
For($i=5;$i>=1
;$1--){
for($3=$1;$5>=13$3
echo
--){
$i." "s
A
echo "<br>";
ae
27, Progratom print the foll
54321 owing triangle pattern: aa
4321
321
21

for($i=0;$ic=5;$i+
For ($5=5-$i;$5>=15$+)5-{
-){
echo $3;

Scanned with CamScanner


Scanned with CamScanner
Based Application Development with PHP eerie eee

33. Emagen to calculate the length of the string.


<?php
: // PHP program to find the
; // length of a given string
$str = "A vanishPokharkar"; |
// prints the length of the string
// including the space
echo strlen($str);
P>

am to count the number of words in the string without using the string function, at
i php
// PHP program to count no of

e = $OUT;
8; // word count

Scan all characters one by one


len($str))

Scanned with CamScanner


To count the number of words in the string with string function.
ee str = ‘Good Morning.';
echostr_word_count($my_str);

36, Program to print the given string in uppercase.


<?php ——..
# PHP code to convert to Upper Case
functiontoUpper ($string) {
return(strtoupper ($string) );
}
// Driver Code
$string="Hello Good Mornin
g";
echo (toUpper($string));

37, Prune print the given string in


the lowercase.
<fphp
# PHP code to conver
t to Lower Case
functiontoLowen( $strin
g) {
y rn(strtolowen ($stri
ng);
// Driver Code
$string="Hello Good Mor
echo
ning";
(tolLower($string));

ctionfirstUpper ($string){
re en(ucfirst(sstring) );
' ne to PHP”;

‘ per($string));

ill
Scanned with CamScanner
r Web Based Application Devel with PHP PAG

39. Program to convert the first letter in the lowercase.


<?php ower Case
a PHP code to convert the first letter to L
functionfirstLower ($string) {
return(lcfirst($string)
);
}
// Driver Code
$string="WELCOME TO PHP";
echo (firstLower($string));

40. Program to convert the first letter of each word to Upper Case.
<?php
functionfirstUpper ($string) {
return(ucwords($string) );
}
// Driver Code
$string="hello good morning";
echo (firstUpper($string));

;->name = $name;
>color = $color;

is {$this->name} and the color is {$this->color}."


;2

// OK. __construct()
is public
.) as public and it calls intro() (wich ©

Scanned with CamScanner


ent with PHP PAT ee
ypweb sad
Ba
Apleston oes eisPrograme
>>
</body>
</html>

42. PHP cookie program.


; retcookie(“user
? hn uw
» "
Rese “
93 .

if(lisset($_COOKIE["user"])) {
P P " uw

echo "Sorry, cookie is not found!";


} else {
echo "<br/>Cookie Value: " , $_COOKIE["user"];
}
>>
</body>
</html>
Output:
First we run it we will get output as sorry, cookie
is not found.
But when we refresh we willwil get: _ get:

43. PHP script to lower-case and


upper-case, all elements in an arra
<?php y.
$colors = array ( "Red",
"Green", "Black", "White");
print_r($colors);
echo "<br>";
$lower_colors = array_map('strtolower' , $colors);
print_r($lower_colors);
echo "<br>";
$upper_colors = array_map('strtoupper’,
print_r($upper_colors 3 $colors);
>
Output:
Array ([@] => Red [1] => Green [2] => Black [3] rs White)
Array ([@] => red [1] => green [2] => black [3] => ae
Array ([@] => RED [1] => GREEN [2] => BLACK [3] =>
44. PHP script us g nested for ai that creates a chess board as shown below. Use table
width="27 " and take 30px as cell height and width.

ell
Scanned with CamScanner
<html>
<head>
<title></title>
; <meta http-equive"Content-Type" content="text/html; ; aT kas
</head> charset
<body> vie
<h3>Chess Board using Nested For Loop</h3>
oer.
<table width="27@px" cellspacing="@px" cellpadding="@px" ="4px"
<I-- cell 270px wide (8 columns x 6@px) --> border="1px">
<?php
for($row=1;$rowc=8; $row++)

echo "<tr>";
for($col=1;$col<=8;$col++)
{
$total=$row+$col;
if ($total%2==9)
echo "<td height=3epx width=3@px bgcolor= #FFFFFF></td>";
}
else
- {
.* th echo “<td height=3epx width=3@px
. <j FF
bgcolor=#0@0000></td>";
}
echo "e/tro";

ariables and set to empty values


= $emailerr = $genderErr = $websiteErp - ne
1 = $gende r = $comment = $website = "™,
R["REQUEST_METHOD"] == "post) ,
_POST[“name"])) {
Name is required";

-_input($_POST(“nane"});
"email"})) {
1 is required";
a.

Scanned with CamScanner


Scanned with CamScanner
Web Based Application wane P.20
<?php
echo “<h2>Your given values are as:< ph2>"s
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo “<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

Absolute classes registration


* required field.

‘Name: —— 1°
— ———)

7 46, Program for session management.


<?php
// Start the session
: session_start();
a P>
<!DOCTYPE html>
ml>

/ Set session variables


$ SESSION["favcolor"] = "green";
SESSION["favanimal"] = “cat”;
"Session variables are set.";
"Favorite color is “ . $ SESSION ["favcolor™ ] : .<br>":
“Favorite animal is " . $ SEssto 3 -
N[ favanimal"] , « oo
or

Scanned with CamScanner


t with PHP P.21
p seston
in =
at.
<html>
ad> g HTML email using PHP</title>
cpitlersendin
</head>
<body?
oT = "xyz@somedomain. com ae
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message -= "chioThis is headline.</h1>";
in.com \r\n";
$header = "Erom:abc@somedoma
$header .= "Cc:[email protected] \r\n";
$header .= “MIME-Version: 1.6\r\n";
$header .= “Content-type: text/html\r\n";
$retval = mail ($to,$subject, $message, $header) ;
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
>>
</body>
</html>
Output:
Message sent successfully...
48. Program to check that emails are valid.
<html>
<head>
<style>
-error {color: #FF@@@@;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr
= "";
oe: $email = $gender = $comment = $website = “";
($_SERVER["REQUEST_METHOD"] == “POST") {
if (empty($ POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name”]);
check if name only contains letters and whitespace
ifMW (Ipreg match("/*[a-zA-Z ]*$/",$name)) {
ameErr = "Only letters and white space allowed";

-y($_POST["email"])) {
= "Email is required";

input($_POST["email"]);
e-mail address is well-formed
ar($email, FILTER _VALIDATE_EMAIL)) {
“Invalid email format";

p43): <
Scanned with CamScanner
Web Based Apptioation Development with PHP pas 7
check
Swebsite = test_input($_post] "website’])5
if URL "address syntax is Va
AF (ipreg_match(*/\b(?: (Pshetps? |ftp)s VW [www Care
-9-20-9+8QHW\/%Pa~
[ts
1 tase {
S$websiteErr = “Invalid URL";
}
if (empty($_POST["comment"])) {
Scomment t = °*; !
} else { !
Scomment = test_input($_PosT[ "comment" ]);
if (empty($_POST["gender"])) {
rErr = “Gender is required";
} else {
| ; Sgender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
2>
<h2>PHP Form Validation Example</h2>
_ <p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[ "PHP_SELF"]);?>">
Name: <input type="text" name="name">
_ <span class="error">* <?php echo $nameErr;?></span>
- ¢br><br>
i: _ E-mail: <input type="text" name="email">
<span class="error™>* <?php echo $emailErr;?></span>

Website: <input type="text" name="website">


Ps n class="error"><?php echo $websiteErr; ?></span>
<br>
: <textarea name="comment" rows="5" cols="40"></textarea>

name="gender” value="female">Female
name="gender” value="male">Male
="radio” name="gender” value="other
">0ther
“"“error">* <?php echo $genderE
rr 3?></span>
“submit” name="submit" value="Submit">

—e

Scanned with CamScanner


P.23

Canes CNemale Cidade Crluen*

Your Input;
mest

aieDeve
eelop a simple application to enter data in
database.
1. Creating PHP file,
INDEX.PHP
chtml>
<body>
<hlyA small example page to inse
rt some data in to the
<form action=" insert .php” me MySQL database uSing
thod="post"> PHP</hi>
Firstname: <input type="
text” name="fname" /><br>
Lastname: <input type=" <br>
text" name="name" /><b
<input type="submit” /»> r> <b r>
</form>
</body>
</html>

A small example page to insert


in to the MySOL database usi some data
ng PHP
4
| }
Ceesae
2 To connect to MySu.
We can access your MySQL database, we must
fc contact the system administrators to request
an
Once the administrators have notified we
the following instructions, that the account has been created, we may
connect using
—__Seseq
9S Now et ttleement win > =
ate ™
'
OW enter th, ; p
“new table name “nametable”, number of fields in that table as “2” and hit go, . ;
_ | 8 Serves: convene » lh Outabese: santdh ay

4. Enter the fiel


d —_= €s to be “firs
both the fields. The default type oftname” and “lastname” and keep the length attributes to be “29"¢
VARCHAR is kept as it is. lor
ED Server: convene » @ Database: suntZk » Table: mametable
-

—— |
a ae a
SSSe |

* I ield type be. “eowen” or “set”, please enter the values i format: 's,
you everPsneed topulaput « backslash
a gy) A SeIHE avete ‘Came
(-) amangat thoseme
i
@ eatns, pracond & with a | iy

* Far defo values, please eater ost» ingle volvo, thot backolash escaping ot uctes, using te fommat
| a =
. J
|
e

5. After the table field are being created the following screen will be shown below:

A Ent Tate OM Bory aie Ost sons BIG)

connection to the MySQL database and shell send

CO
te a new PHP page “insert.php” and use the foll

Scanned with CamScanner


“ goo

COMP aysqi_connect("mysql.cis.ksu.edu”
,"cis id" “password”.
4f (1$60n)
{ a(‘could not connect: » mysql_error());
or _select_db("cis_id", $con);
$sql="INSERT INTO nametable (fname, Iname)
VALUES
(‘$_POST[fname}’ ,"$ POST(1name]’)”;
if (Imysql_query($sql,$con))
die('Error: ‘ , mysql_error());
}
echo “1 record added”;
7s41_close($con)
>
</body>
</html>
7, mNorw ty:pe the nit Pete
: URmLain ou
- r browser and
enter some d
e ta ini to the tex
=
tboxes Submit the
;

Frttcene

Scanned with CamScanner


Scanned with CamScanner
PITTI Cae uuu ela Reds
TR nud ae alate De
ADVANEED SY t ye Me LL
AG PER VSBTE's
ee aA M aa els ie ila
BL a el ele Lae uae ele SALIENT FEATURES
MTTYYTTT els HOOK alimnsé al CaLering
§ FREI ARAII WITH PYTHON
to 1 the

thal, Mire lvoe hana (Ai pede) needs of Third Year Diploma student:
Vijay | Mati, MewrabalilA
an jel DASH TE’ fe (Meg "| Schien 7

6 MICE AR PLICATION DEVELORIARAT wNlahus effective from 7018


til
Wave. PAavilolinA. Meviehiay lead, Hrmabiarit (1. Qevirinemria
E FINE eCOMpAle GUNG aller has bees
WE HADEN APMLICATION DEVELOIMENT L101H
igare; coyered Keeping in view the feyised
Prashant 0 Samwarelil Mr Miruiial if Paban
Syllahus
Mie MarielaA. Makharka
POIYée explanation is given in each
6 NETWORK AND INFORIAATION SECIHITY Lopic for @ase of gludy
of the relevant
bare, Mrinal Be Ratanigare Me Oi ner
chappley
6 DATA WAREHOUSING WITH PAINING (EC HAIOUES
Lr MawnakelitA Talat, Mraehant D. Sannmarall
Pat / Previaus Examination
Questions have heen incorporates in
6 WIKELESS AND MONILE HEI WORKS each chapter. This will be extremely
Karnihle
frotik & Tawde, Anjurn Mujawat, Mr, Miniala Ni
Useful 16 students Community
§ CLOUD COMPUTING helpful to the
Cv, Kohan & Ving, Pare, Sharmila b. Wiawhi This book will also be
students preparing for AMAlt

(Studentship), Par-time Diploma ang


fel
HOOKS AVAILAMI : AT
Correspondence diploma courses

CONT Email phoned pragationiineg can


Hath, Opp, Hakan Talkies, Ment to Balaji Mandir, N [ R A I
59657709148
' Lawenhvaiarl PAandir, Mune 411007 PRAKASHA
96477049147 [ 9657704149 as
PKreone
Abhyudaya Pragati, 1417 Shiva) Nager
Maids, Pane 411004
Off JM. Road, Pune 411006
19, Anya Balwant Chowk, ee
"n,
F
(O40)
ex 2
20)
Z99
an6it
sabi tl
18
s79
Mobile 965//09142

a.
|
| | j |
| ii i |
|
i
|
| |
1 H a ‘i

f m4oGe
L ceeneneengeperee

—— |
Scanned with CamScanner

You might also like