PHP Nirali Publi
PHP Nirali Publi
PHP Nirali Publi
PRASHANT D. SOMWANSHI
Mrs. MANI A. SHPOKHAARKAR
Mrs. MRUN AL
P. FATAN GARE
DiaaKnen an
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.
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.
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.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
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
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.
=
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]
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.
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
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
>]
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
}
assigna();
print "a outside of function is $a. "3
?>
Output:
a inside function is 8.
a outside of function is 4.
= 15;
= 20;
ction addit()
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 .
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
}
$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:
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.
« 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;
{
// 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"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
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
{
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
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
Loop
False
« 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
= array(1,2,3,
4,5);
if($value%2 == @)
continue;
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.
$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
} 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
}
?>
+ 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.
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:
<?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 ®
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)
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)
* 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
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
=
}
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);
* 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!
¢ 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
\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
* 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.
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.
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.
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
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
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.
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.
is 2
) of character ‘I’ is 0, hence it displays position of ‘am’
character, hence ‘am’ is at position 16.
i tas 2
Y
To understand Basic OOP Concepts 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
= =
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
« 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 =
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.
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 ——
+ 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();
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()
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
}
/?/ Reference type of parent
Sp= newP;
// Reference type of child
$c= newC;
// print Parent
$p->geeks();
#7 Print child
$c->geeks();
Introspection is the ability of a program to examine an object's characteristics, such as its name,
R
. $method_name);
ae oa
<?php
_ €lass Student
nt
_ var Sage = 10;
_ functionshow_Age()
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');
}
{
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; }
Authenticate user
Add data to database
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
— 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"/>
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
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
Request for
welcome.himl
| welcome.html
and send itas ©
_ the response
Server
Client
Fig. 4.2: Cycle ofa Normal Web Request
Request for
welcome.php
PHP Engine
Server
Client
Example:
welcome.php
<html>
<head>
é<title>Welcome to Our Web Site</title>
</head>
<body>
<hl>
<?php
if (date('G') < 12)
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:.<.
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
ficana Publication
Write message here: a
{ Send Ema
Form
2 is Calling
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:
—input($_POST[“name"])
;
di
</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.
‘Classes:
ee
. : cookie
way, ser. Each time when client sends request
can be received at the server side:
nequest + Cookie
* 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.
the value of t#
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
—
Session variables, ie
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"
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
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
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.
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
i a a ee ee
. Other nanos nay be tradenarks of their respective
eM
Copyright (c) 2088, 2011, Oracle and/or its affiliates. All rights reserved.
ee ee | ee eS ee
ee ae ere
hs ies
d successfully
$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)){
aeoe
in PHP</title>
<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
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 >
if(isset($_POST['submit']))
= $_POST[ 'width'];
gth = $_POST['length'];
rea = $width*$length;
echo "The area of a rectangle with $width x $length is $area";
- range('A’, 'Z');
<?php
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
———
for($i=0;$ic=5;$i+
For ($5=5-$i;$5>=15$+)5-{
-){
echo $3;
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
ctionfirstUpper ($string){
re en(ucfirst(sstring) );
' ne to PHP”;
‘ per($string));
ill
Scanned with CamScanner
r Web Based Application Devel with PHP PAG
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;
// OK. __construct()
is public
.) as public and it calls intro() (wich ©
if(lisset($_COOKIE["user"])) {
P P " uw
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";
-_input($_POST(“nane"});
"email"})) {
1 is required";
a.
‘Name: —— 1°
— ———)
-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>
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
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 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:
CO
te a new PHP page “insert.php” and use the foll
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
thal, Mire lvoe hana (Ai pede) needs of Third Year Diploma student:
Vijay | Mati, MewrabalilA
an jel DASH TE’ fe (Meg "| Schien 7
a.
|
| | j |
| ii i |
|
i
|
| |
1 H a ‘i
f m4oGe
L ceeneneengeperee
—— |
Scanned with CamScanner