Php Noteees
Php Noteees
1.1 History
Advantages Of PHP
Syntax of PHP
1.2 Variables
Data Types
Expressions
Operators
Constants
1.3 Decision Making Control Statements :
if
if-else
nested if
switch
break
continue
1.4 Loop Control Structures :
while
do-while
for
foreach
Unit I
Expressions and Control Statements in PHP Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Where
Server-side means that PHP scripts execute on the Web server, not
within the browser on your local machine.
Cross-platform means that PHP scripts can run on many different
operating systems and Web servers. PHP is available for the two
most popular Web server configurations IIS and Apache.
HTML embedded scripting language means that PHP statements and
commands are actually embedded in your HTML documents.
(i)
History of PHP :
Unit I
Expressions and Control Statements in PHP Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
2. Platform Independence:
3. Easy loading:
One can load the PHP-based applications easily and connect them to a
database. People mainly use it since it has a fast rate of loading even if
it is over a slow internet connection and speed than other
programming languages.
4. User-friendly:
It has a less learning curve, and one can learn it quickly. The language
is straightforward to use, and if one knows about C programming, they
can catch on to PHP language quickly for application development.
5. Stable:
Unlike other scripting languages, PHP is very stable over the years
and can provide one with assistance and continuous support. They can
get help over various versions as well.
Unit I
Expressions and Control Statements in PHP Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
7. Flexible:
9. Database connection:
PHP has strong library support using which one can utilize the various
function modules for data representation.
a) Default syntax
b) Short open Tags
c) Omit the PHP closing tag at the end of the file.
Unit I
Expressions and Control Statements in PHP Page 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
a) Default Syntax
The default syntax starts with "<? php" and ends with "?>".
Example:
<?php
?>
The short tags starts with "<?" and ends with "?>". Short style tags are only
available when they are enabled in php.ini configuration file on servers.
Example:
<?
?>
Example:
<?php
Unit I
Expressions and Control Statements in PHP Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
The syntax for PHP variables is similar to C and most other programming
languages. There are
three primary differences:
1. Variable names must be preceded by a dollar sign ($).
2. Variables do not need to be declared before being used.
3. Variables are dynamically typed, so you do not need to specify the type
(e.g., char, int, float, etc.).
A variable can have a short name, like x, or a more descriptive name, like
carName. The rules for PHP variable names:
• Variables in PHP starts with a $ sign, followed by the name of the variable
• The variable name must begin with a letter or the underscore character
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• A variable name should not contain spaces
• Variable names are case sensitive (y and Y are two different variables).
Example :-
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
output :
9
Variable Variables
You can reference the value of a variable whose name is stored in another
variable.
For example:
$foo = 'bar';
$$foo = 'baz';
After the second statement executes, the variable $bar has the value "baz".
Unit I
Expressions and Control Statements in PHP Page 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Variable References
In PHP, references are how you create variable alternatives. To make $black
an another name for the variable $white, use:
$black =& $white;
The old value of $black is lost.
Scope of Variable
1) Local Scope :
A variable declared within a PHP function is local and can only be
accessed within that function. (the variable has local scope):
<?php
$a = 5; // global scope
function myTest()
{
echo $a; // local scope
}
myTest();
?>
The script above will not produce any output because the echo
statement refers to the local scope variable $a, which has not been
assigned a value within this scope.
You can have local variables with the same name in different
functions, because local variables are only recognized by the function
in which they are declared.
Local variables are deleted as soon as the function is completed.
2) Global Scope :
Global scope refers to any variable that is defined outside of any
function. Global variables can be accessed from any part of the script
that is not inside a function. To access a global variable from within a
function, use the global keyword:
Unit I
Expressions and Control Statements in PHP Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
<?php
$a = 5;
$b = 10;
function myTest()
{
global $a, $b;
$b = $a + $b;
}
myTest();
echo $b;
?>
Output:
15
3) Static Scope :
When a function is completed, all of its variables are normally
deleted. However, sometimes you want a local variable to not be
deleted.
To do this, use the static keyword when you first declare the
variable:
<? php
function add()
{
static $a=10;
$b=20;
$a++;
$b++;
echo $a;
echo "<br>";
echo $b;
echo "<br>";
}
add();
add();
?>
Output :
11
21
12
21
Unit I
Expressions and Control Statements in PHP Page 8
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Then, each time the function is called, that variable will still have
the information it contained from the last time the function was
called.
The variable is still local to the function.
Output-
int(55)
Output-
float(15.36)
Output-
bool(true)
bool(false)
Unit I
Expressions and Control Statements in PHP Page 9
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Output-
string(12)
Output
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
Unit I
Expressions and Control Statements in PHP Page 10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Output –
Mango is king of fruits...
object(fruits)#1 (0) { }
<?php
class fruits {
function mango() {
$weight=50;
$desc = "Mango is king of fruits...";
$this->weight=$weight;
echo $desc."It has weight ".$weight." gms.";
echo "<br>";
}
}
$obj = new fruits($weight);
$obj->mango();
var_dump($obj);
?>
Output :
Mango is king of fruits...It has weight 50 gms.
object(fruits)#1 (1) { ["weight"]=> int(50) }
Null - special data type which can have only one value i.e. NULL.
Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output –
NULL
Unit I
Expressions and Control Statements in PHP Page 11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Expressions :
Operators :
Operators are used to perform operations on variables and values. PHP
divides the operators in the following groups:
1) Arithmetic operators
2) Assignment operators
3) Comparison operators
4) Increment/Decrement operators
5) Logical operators
6) String operators
7) Array operators
1) Arithmetic operators :
Unit I
Expressions and Control Statements in PHP Page 12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
2) Assignment operators :
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
3) String Operator :
Unit I
Expressions and Control Statements in PHP Page 13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
5) Logical Operators:
Unit I
Expressions and Control Statements in PHP Page 14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
6) Comparision Operators :
7) Array Operators :
Unit I
Expressions and Control Statements in PHP Page 15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Constants are like variables except that once they are defined they
cannot be changed or undefined.
A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign
before the constant name).
Note: Unlike variables, constants are automatically global across the
entire script.
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false.
Example :
Unit I
Expressions and Control Statements in PHP Page 16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
PHP If Else
PHP if else statement is used to test condition. There are various ways to use
if statement in PHP.
1) if
2) if-else
3) if-else-if
4) nested if
(i)
PHP If Statement
PHP if statement allows conditional execution of code. It is executed
if condition is true.
If statement is used to executes the block of code exist inside the if
statement only if the specified condition is true.
Syntax
if(condition){
//code to be executed
}
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Output:
12 s less than 100
(ii)
PHP If-else Statement
PHP if-else statement is executed whether condition is true or false.
If-else statement is slightly different from if statement. It executes
one block of code if the specified condition is true and another block
of code if the condition is false.
Syntax
if(condition){
Unit I
Expressions and Control Statements in PHP Page 17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
(iv)
PHP nested if Statement
The nested if statement contains the if block inside another if block.
The inner if statement executes only when specified condition in
outer if statement is true.
Syntax
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
Example
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
Unit I
Expressions and Control Statements in PHP Page 19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
else {
echo "Not eligible to give vote";
}
}
?>
Output:
Eligible to give vote
Output:
number is equal to 20
statements;
break;
Example
Let's see a simple example to break the execution of for loop if value
of i is equal to 5.
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output:
1
2
3
4
5
Unit I
Expressions and Control Statements in PHP Page 21
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Syntax
The syntax for the continue statement is given below:
Statements;
Continue;
Example
In the following example, we will print only those values of i and j
that are same and skip others.
<?php
//outer loop
for ($i =1; $i<=3; $i++) {
//inner loop
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue; //skip when i and j does not have same values
}
echo $i.$j;
echo "</br>";
}
}
?>
Output:
11
22
33
Unit I
Expressions and Control Statements in PHP Page 22
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
PHP while loop can be used to traverse set of code like for loop. The
while loop executes a block of code repeatedly until the condition is
FALSE. Once the condition gets FALSE, it exits from the body of
loop.It should be used if the number of iterations is not known.
The while loop is also called an Entry control loop because the
condition is checked before entering the loop body. This means that
first the condition is checked. If the condition is true, the block of
code will be executed.
Syntax
while(condition){
//code to be executed
}
Alternative Syntax
while(condition):
//code to be executed
endwhile;
PHP While Loop Flowchart
PHP While Loop Example
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
Unit I
Expressions and Control Statements in PHP Page 23
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
PHP do-while loop can be used to traverse set of code like php while
loop. The PHP do-while loop is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the
program several times. If you have to execute the loop at least once
and the number of iterations is not even fixed, it is recommended to
use the do-while loop.
It executes the code at least one time always because the condition is
checked after executing the code.
The do-while loop is very much similar to the while loop except the
condition check.
The main difference between both loops is that while loop checks the
condition at the beginning, whereas do-while loop checks the
condition at the end of the loop.
Syntax
do{
//code to be executed
}while(condition);
Flowchart
Example
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
Output:
1
2
3
4
5
6
7
8
9
10
Unit I
Expressions and Control Statements in PHP Page 24
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example
<?php
for($n=1;$n<=10;$n++)
{
echo "$n<br/>";
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
Unit I
Expressions and Control Statements in PHP Page 25
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
Output
red
green
blue
yellow
******END *******
Unit I
Expressions and Control Statements in PHP Page 26
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Important Questions :
1) Write Any five Advantages of PHP.
2) State the use of “$” sign in PHP.
3) Write the syntax of PHP.
4) Explain the term :
a) Variable
b) Expression
5) Explain any Four data types in PHP.
6) List different types of operators in PHP.
7) Write a program using foreach loop.
Unit I
Expressions and Control Statements in PHP Page 27
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Unit II
Arrays, Functions and Graphics Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
2.1 Array
Definition:
An array is an ordered collection of elements. The elements are of same data type or
different data type. Each element has a value, and is identified by a key. Each array
has its own unique keys. The keys can be either integer numbers or strings.
In Numeric array each elements are assigned a numeric key value starting
from 0 for first elements and so on.
Example:
<?php
$name=array(“Archana”, “Sanket”, “Helisha”);
print_r($name);
?>
Output:
Array([0] => Archana [1] => Sanket [2]=>Helisha)
Syntax:
$ArrayName [ ] = “value”;
Example:
<?php
$name[ ] = “Mohan”;
$name[ ] = “Helisha”;
Unit II
Arrays, Functions and Graphics Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
print_r($name);
?>
Output:
Array([0] =>Arpan [1] =>Mohan [2]=>Helisha)
Example:
<?php
$name = array(19=> “Arpan”, “Charmi”, “Reshma”);
print_r($name);
?>
Output:
Array ([19]=> Arpan [20]=>Charmi [21]=>Reshma)
Example:
<?php
$name=array(“Arpan”, “Sohan”, “Helisha”);
print_r($name);
echo “<br>”;
$name[ ] = “Sagar”;
print_r($name);
?>
Output:
Array([0] =>Arpan [1] =>Sohan [2]=>Helisha)
Array([0] =>Arpan [1] =>Sohan [2]=>Helisha [3]=>Sagar)
Unit II
Arrays, Functions and Graphics Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
1. Indexed Array
These arrays can store numbers, strings and any object but their index will be pre
presented by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array()function to create array. This function is explained in
function reference.
<html>
<body>
<?php
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
echo"<pre>";
Print_r($numbers);
echo"</pre>";?>
</body>
</html>
Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Unit II
Arrays, Functions and Graphics Page 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
2. Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality
but they are different in terms of their index. Associative array will have their
index as string so that you can establish a strong association between key and
values.
Example
<html>
<body>
<?php
$salaries = array(
"mohammad" => 2000, "Dinesh" => 1000, "Surabhi" => 500
);
echo "Salary of Arjun is ". $salaries['Arjun'] . "<br />";
echo "Salary of Dinesh is ". $salaries['Dinesh']. "<br />";
echo "Salary of Surabhi is ". $salaries['Surabhi']. "<br />";
echo "<pre>";
print_r($salaries);
echo "</pre>";
?>
</body>
</html>
Output
Salary of Arjun is 2000
Salary of Dinesh is 1000
Salary of Surabhi is 500
Array
(
[Arjun] => 2000
[Dinesh] => 1000
[Surabhi] => 500
)
Unit II
Arrays, Functions and Graphics Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
3. Multidimensional Arrays
A 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 soon. Values in the multi-
dimensional array are accessed using multiple indexes.
Example
In this example we create a two dimensional array to store marks of three students
in three subjects:
<html>
<body>
<?php
$marks = array(
"Arjun" => array
(
"physics" => 35, "maths" => 30, "chemistry" => 39
),
"Dinesh" => array
(
"physics" => 30, "maths" => 32, "chemistry" => 29
),
"Surabhi" => array
(
"physics" => 31, "maths" => 22, "chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for Arjun in physics : " ;
echo $marks['Arjun']['physics'] . "<br />";
echo "Marks for Dinesh in maths : ";
echo $marks['Dinesh']['maths'] . "<br />";
echo "Marks for Surabhi in chemistry : " ;
echo $marks['Surabhi']['chemistry'] . "<br />";
echo "<pre>";
print_r($marks);
echo "</pre>";
?>
</body>
</html>
Output:
Marks for Arjun in physics : 35
Marks for Dinesh in maths : 32
Marks for Surabhi in chemistry : 39
Unit II
Arrays, Functions and Graphics Page 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Array
(
[Arjun] => Array
(
[physics] => 35
[maths] => 30
[chemistry] => 39
)
)
2.2 In-Built Functions of Array
1) sizeof($arr)
This function returns the number of elements in an array. Use this function to
find out how many elements an array contains; this information is most
commonly used to initialize a loop counter when processing the array.
Example:
<?php
$data = array("red", "green", "blue");
echo "Array has " . sizeof($data) . " elements";
?>
Output
Array has 3 elements
2) array_values($arr)
This function accepts a PHP array and returns a new array containing only its
values (not its keys). Its counterpart is the array_keys() function. Use this
function to retrieve all the values from an associative array.
Example
<?php
Unit II
Arrays, Functions and Graphics Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
3) array_keys($arr)
This function accepts a PHP array and returns a new array containing only its
keys (not its values). Its counterpart is the array_values() function. Use this
function to retrieve all the keys from an associative array.
Example
<?php
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>
Output:
Array
(
[0] => hero
[1] => villain
)
4) array_pop($arr)
This function removes an element from the end of an array.
Example
<?php
$data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>
Output
Array
(
[0] => Donald
[1] => Jim
)
5)
array_push($arr, $val)
This function adds an element to the end of an array.
Example
Unit II
Arrays, Functions and Graphics Page 8
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
<?php
$data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>
Output
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
6)
array_shift($arr)
This function removes an element from the beginning of an array.
Example
<?php
$data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>
Output
Array
(
[0] => Jim
[1] => Tom
)
7) array_unshift($arr, $val)
This function adds an element to the beginning of an array.
Example
<?php
$data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>
Output:
Array(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
Unit II
Arrays, Functions and Graphics Page 9
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
8) array_flip($arr)
The function exchanges the keys and values of a PHP associative array. Use this
function if you have a tabular (rows and columns) structure in an array, and you
want to interchange the rows and columns.
Example
<?php
$data = array("a" => "apple", "b" => "ball");
print_r(array_flip($data));
?>
Output
Array
(
[apple] => a
[ball] => b )
9) array_reverse($arr)
The function reverses the order of elements in an array. Use this function to re-
order a sorted list of values in reverse for easier processing—for example, when
you’re trying to begin with the minimum or maximum of a set of ordered values.
Example
<?php
$data = array(10, 20, 25, 60);
print_r(array_reverse($data));
?>
Output
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)
10) array_merge($arr)
This function merges two or more arrays to create a single composite array. Key
collisions are resolved in favor of the latest entry. Use this function when you
need to combine data from two or more arrays into a single structure. For
example, records from two different SQL queries.
Example
<?php
$data1 = array("cat", "goat");
$data2 = array("dog", "cow");
Unit II
Arrays, Functions and Graphics Page 10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
print_r(array_merge($data1, $data2));
?>
Output
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow )
11) array_rand($arr)
This function selects one or more random elements from an array. Use this
function when you need to randomly select from a collection of discrete values.
For example, picking a random color from a list.
Example
<?php
$data = array("white", "black", "red");
echo "Today's color is " . $data[array_rand($data)];
?>
Output
Today’s color is red
12)
array_search($search, $arr)
This function searches the values in an array for a match to the search term, and
returns the corresponding key if found. If more than one match exists, the key of
the first matching value is returned. Use this function to scan a set of index-value
pairs for matches, and return the matching index.
Ex-
<?php
$data = array("blue" => "#0000cc", "black" => "#000000", "green" =>
"#00ff00");
echo "Found " . array_search("#0000cc", $data);
?>
Output
Found blue
Unit II
Arrays, Functions and Graphics Page 11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example
<?php
$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));
?>
Output
Array
(
[0] => strawberry
[1] => mango
)
14) array_unique($data)
This function strips an array of duplicate values. Use this function when you
need to remove non-unique elements from an array. For example, when creating
an array to hold values for a table’s primary key.
Example
<?php
$data = array(1,1,4,6,7,4);
print_r(array_unique($data));
?>
Output
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)
15) array_change_key_case()
PHP array_change_key_case() function changes the case of all key of an array. It
changes case of key only.
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_LOWER));
?>
Unit II
Arrays, Functions and Graphics Page 12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
16) array_chunk()
PHP array_chunk() function splits array into chunks. By using array_chunk()
method, you can divide array into many parts.
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_chunk($salary,2));
?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
17) array_intersect()
PHP array_intersect() function returns the intersection of two array. In other
words, it returns the matching elements of two array.
Example
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
Output:
sonoo
smith
18)
implode()
The implode() is a built-in function in PHP and is used to join the elements of an
array. It works exactly same as that of join() function.
If we have an array of elements, we can use the implode() function to join them
all to form one string. We basically join array elements with a string. Just like
join() function , implode() function also returns a string formed from the
elements of an array.
Unit II
Arrays, Functions and Graphics Page 13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Syntax :
implode(separator,array)
Parameters:
The implode() function accepts two parameter out of which one is optional and
one is mandatory.
1) separator: This is an optional parameter and is of string type. The values of
the array will be join to form a string and will be separated by the separator
parameter provided here. This is optional, if not provided the default is “” (i.e.
an empty string).
2) array: The array whose value is to be joined to form a string.
Return Type:
The return type of implode() function is string. It will return the joined string
formed from the elements of array.
Example:
<?php
// PHP Code to implement join function
$a= array('I','like','PHP');
Output:
IlikePHP
I-like-PHP
I like PHP
19)
explode()
explode() is a built in function in PHP used to split a string in different strings.
The explode() function splits a string based on a string delimiter, i.e. it splits the
string wherever the delimiter character occurs. This functions returns an array
containing the strings formed by splitting the original string.
Unit II
Arrays, Functions and Graphics Page 14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Syntax :
explode(separator, String, limit)
Parameters:
The explode function accepts three parameters of which two are compulsory and
one is optional.
1) separator : This character specifies the critical points or points at which the
string will split, i.e. whenever this character is found in the string it symbolizes
end of one element of the array and start of another.
2) String : The input string which is to be split in array.
3) limit : This is optional. It is used to specify the number of elements of the
array. This parameter can be any integer ( positive , negative or zero)
Positive (N): When this parameter is passed with a positive value it means
that the array will contain this number of elements. If the number of
elements after separating with respect to the separator emerges to be greater
than this value the first N-1 elements remain the same and the last element
is the whole remaining string.
Negative (N):If negative value is passed as parameter then the last N
element of the array will be trimmed out and the remaining part of the array
shall be returned as a single array.
Zero : If this parameter is Zero then the array returned will have only one
element i.e. the whole string.
Return Type:
The return type of explode() function is array of strings.
Example:
<?php
echo"<pre>";
$OriginalString = "Hello, How can we help you?";
echo"Without optional parameter limit";
print_r(explode(" ",$OriginalString));
print_r(explode(",",$OriginalString));
echo"</br>";
echo"with positive limit";
echo"</br>";
print_r(explode(" ",$OriginalString,3));
echo"</br>";
print_r(explode(",",$OriginalString,1));
echo"</br>";
echo"with negative limit";
echo"</br>";
print_r(explode(" ",$OriginalString,-1));
echo"</br>";
print_r(explode(" ",$OriginalString,-3));
echo"</pre>";
?>
Unit II
Arrays, Functions and Graphics Page 15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Output:
Without optional parameter limitArray
(
[0] => Hello,
[1] => How
[2] => can
[3] => we
[4] => help
[5] => you?
)
Array
(
[0] => Hello
[1] => How can we help you?
)
Array
(
[0] => Hello, How can we help you?
)
Array
(
[0] => Hello,
[1] => How
[2] => can
)
Unit II
Arrays, Functions and Graphics Page 16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
20) Extract()
The extract() Function is an inbuilt function in PHP. The extract() function does
array to variable conversion. That is it converts array keys into variable names
and array values into variable value.
Syntax :
extract($array, $extract_rule, $prefix)
Parameters:
The extract() function accepts three parameters, out of which one is compulsory
and other two are optional.
1) $array: This parameter is required. This specifies the array to use.
2) $extract_rule: This parameter is optional. The extract() function checks for
invalid variable names and collisions with existing variable names. This
parameter specifies how invalid and colliding names will be treated. This
parameter can take the following values:
EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite
the existing variable.
EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the
existing variable.
EXTR_PREFIX_SAME: This rule tells that if there is a collision then
prefix the variable name according to $prefix parameter.
EXTR_PREFIX_ALL: This rule tells that prefix all variable names
according to $prefix parameter.
$prefix: This parameter is optional. This parameter specifies the prefix. The
prefix is automatically separated from the array key by an underscore
character. Also this parameter is required only when the parameter
$extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL.
Return Type:
The return value of extract() function is an integer and it represents the number of
variables successfully extracted or imported from the array.
Example:
<?php
$KR="KARNATAKA";
$state = array("AS"=>"ASSAM", "OR"=>"ORISSA", "KR"=>"KERALA");
echo $KR."</br>";
echo"</br>";
extract($state);
Unit II
Arrays, Functions and Graphics Page 17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
echo"$AS</br>$KR</br>$OR";
echo"</br>";
echo"</br>";
echo"With Extract Rules-Prefix same";
echo"</br>";
extract($state,EXTR_PREFIX_SAME,"key");
echo"$AS</br>$KR</br>$key_KR</br>$OR";
echo"</br>";
echo"</br>";
echo"With Extract Rules-Prefix all";
echo"</br>";
extract($state,EXTR_PREFIX_ALL,"key");
echo"$key_AS</br>$key_KR</br>$key_OR</br>$KR";
?>
Output:
KARNATAKA
21) Compact()
The compact() function creates an array from variables and their values. Any
strings that does not match variable names will be skipped.
Syntax :
compact(var1, var2...)
Parameters: The compact() function accepts any no. of variables. Atleast one
variable is compulsory and others may be optional.
1) var1- Required. Can be a string with the variable name, or an array of
Unit II
Arrays, Functions and Graphics Page 18
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
variables
2) var2,.. - Optional. Can be a string with the variable name, or an array of
variables. Multiple parameters are allowed.
Return Type: Returns an array with all the variables added to it.
Example:
<?php
echo"<pre>";
$firstname = "Akshay";
$lastname = "Deshapande";
$age = "41";
print_r($result);
echo"</pre>";
?>
Output:
Array
(
[firstname] => Akshay
[lastname] => Deshapande
[age] => 41
)
Unit II
Arrays, Functions and Graphics Page 19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
1) sort()
Using the sort() function you can sort easily and simply. The example of the sort()
function is as follows:
Example:
<?php
$name=array ("Anuj","Sanjeev","Manish","Rahul");
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
sort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>
Output:
Before sorting the values are:
Array ( [0] => Anuj [1] => Sanjeev [2] => Manish [3] => Rahul )
2) rsort() function
The rsort() function is used to sort an array in descending (alphabetic) order
Example:
<?php
$name=array ("Anuja","Sanjeev","Manisha","Rahul");
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
rsort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>
Output:
Before sorting the values are:
Array ( [0] => Anuja [1] => Sanjeev [2] => Manisha [3] => Rahul )
Unit II
Arrays, Functions and Graphics Page 20
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
3) asort() function
In the example above you saw that the elements of the array are arranged in
ascending (alphabetically) order. The asort() function sorts an array and also
maintains the index position.
Example
<?php
$name=array
("DSU"=>22317,"DCC"=>22414,"WBP"=>22619,"CSS"=>22519);
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
asort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>
Output
Before sorting the values are:
Array ( [DSU] => 22317 [DCC] => 22414 [WBP] => 22619 [CSS] => 22519 )
4) arsort() function
The arsort() function is a combination of asort() + rsort(). The arsort() function will
sort an array in reverse order and maintain index position.
Example
<?php
$name=array
("DSU"=>22317,"DCC"=>22414,"WBP"=>22619,"CSS"=>22519);
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
arsort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>
Unit II
Arrays, Functions and Graphics Page 21
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Output
5) ksort()
The ksort() function sorts an associative array in ascending order, according to
the key.
Example:
<?php
$name=array
("DSU"=>22317,"DCC"=>22414,"WBP"=>22619,"CSS"=>22519);
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
ksort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>
Output:
Before sorting the values are:
Array ( [DSU] => 22317 [DCC] => 22414 [WBP] => 22619 [CSS] => 22519
)
Unit II
Arrays, Functions and Graphics Page 22
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
6) krsort()
The krsort() function sorts an associative array in descending order,
according to the key.
Example:
<?php
$name=array
("DSU"=>22317,"DCC"=>22414,"WBP"=>22619,"CSS"=>22519);
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
krsort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>
Output:
Before sorting the values are:
Array ( [DSU] => 22317 [DCC] => 22414 [WBP] => 22619 [CSS] => 22519 )
Unit II
Arrays, Functions and Graphics Page 23
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example:
<?php
Output :
$colors = array("red", "green", "blue", "yellow"); Array Elements are
echo"Array Elements are<br>"; red
foreach ($colors as $value) { green
blue
echo "$value <br>";
yellow
} -----------------------------------
echo"-----------------------------------<br>"; Using Iterator Function
echo "Using Iterator Function<br>"; -----------------------------------
current=red
echo"-----------------------------------<br>";
-----------------------------------
echo"current=".current($colors)."<br>"; next=green
echo"-----------------------------------<br>"; -----------------------------------
echo"next=".next($colors)."<br>"; next=blue
-----------------------------------
echo"-----------------------------------<br>"; previous=green
echo"next=".next($colors)."<br>"; -----------------------------------
echo"-----------------------------------<br>"; key=1
echo"previous=".prev($colors)."<br>"; -----------------------------------
reset=red
echo"-----------------------------------<br>"; -----------------------------------
echo"key=".key($colors)."<br>"; key=0
echo"-----------------------------------<br>"; -----------------------------------
echo"reset=".reset($colors)."<br>"; current=red
-----------------------------------
echo"-----------------------------------<br>"; end=yellow
echo"key=".key($colors)."<br>"; -----------------------------------
echo"-----------------------------------<br>"; each=
echo"current=".current($colors)."<br>"; Array
(
echo"-----------------------------------<br>"; [1] => yellow
echo"end=".end($colors)."<br>"; [value] =>
yellow
echo"-----------------------------------<br>"; [0] => 3
echo"each=<pre>"; [key] => 3
)
print_r(each($colors));
echo"</pre>";
?>
Unit II
Arrays, Functions and Graphics Page 24
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
5) end() Moves the iterator to the last element in the array and
returns it
6) 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
2.4 Functions
A function is a block of statements that can be used repeatedly in a program. A
function will not execute immediately when page loads. A function will be executed
by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
functionName(); ----------- Function call
Example
<?php
function writeMsg( )
{
echo "Hello world!";
}
writeMsg(); // call the function
?>
Output
Hello world!
2) Parameterized Function:
PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like. These parameters work like variables inside your
function. Following example takes two integer parameters and add them together
and then print them.
Unit II
Arrays, Functions and Graphics Page 25
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Syntax
function functionName(variable1,variable2…)
{
code to be executed;
}
functionName(variable1,variable2…); ----------- Function call
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
Output
Sum of the two numbers is : 30
3)
Return Type Function:
A function can return a value using the return statement. return stops the
execution of the function and sends the value back to the calling code.
Syntax
function functionName()
{
code to be executed;
return value;
}
Value=functionName(); ----------- Function call
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
Output
Returned value from the function : 30
Unit II
Arrays, Functions and Graphics Page 26
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
4) Variable Function:
PHP supports the concept of variable functions. This means that if a variable
name has 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.
Syntax
function functionName()
{
code to be executed;
}
$variableName=”functionName”;
$variableName(); ----------- Function call
Example
<?php
function add($x, $y){
echo $x+$y;
}
$var="add";
$var(10,20);
?>
Output
30
5)
Anonymous Function:
Anonymous function is a function without any user defined name. Such a
function is also called closure or lambda function. Sometimes, you may want a
function for one time use. Closure is an anonymous function which closes over
the environment in which it is defined. You need to specify use keyword in
it.Most common use of anonymous function to create an inline callback function.
There is no function name between the function keyword and the opening
parenthesis.
There is a semicolon after the function definition because anonymous function
definitions are expressions
Function is assigned to a variable, and called later using the variable’s name.
When passed to another function that can then call it later, it is known as a
callback.
Return it from within an outer function so that it can access the outer function’s
variables. This is known as a closure.
Unit II
Arrays, Functions and Graphics Page 27
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Syntax
$variableName=function ($arg1, $arg2)
{
return $val;
};
$variableName(); ----------- Function call
Example
<?php
$var = function ($x)
{
return pow($x,3);
};
echo "cube of 3 = " . $var(3);
?>
Output
cube of 3 = 27
6)
Function with default Arguments:
If we call a PHP function without arguments, PHP functions takes the default
value as an argument
Syntax
function functionName(variable1, variable2)
{
code to be executed;
}
$variableName=”functionName”;
$variableName(); ------Both arguments default
$variableName(variable1); ------variable2 is default
$variableName( ,variable2); ------variable1 is default
Example
<?php
function weightHeight($defaultweight = 60,$defaultheight = 170) {
echo "The Weight is : $defaultweight <br>";
echo "The Height is : $defaultheight <br><br>";
}
weightHeight(45);
weightHeight();
weightHeight(70,160);
?>
Unit II
Arrays, Functions and Graphics Page 28
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Output
The Weight is : 45
The Height is : 170
The Weight is : 60
The Height is : 170
The Weight is : 70
The Height is : 160
2.5 String
A string is a series of characters. There are exactly 256 different characters
possible.
The string, like a variable, will have to be created first. There are two ways to use
a string in PHP – you can store it in a function or in a variable. In the example
below, we will create a string twice – the first time storing it in a variable, and the
second time – in a function, in our case – an echo
Basic Example
<?php
$myString = "This is a string!";
echo "This is a string!</br>";
echo $myString;
?>
The output of this PHP file will be:
This is a string!
This is a string!
String Functions:
1)
Str_word_count():
The str_word_count() function counts the number of words in a string.
Syntax
str_word_count(string,return,char)
Parameters
1) string - Required. Specifies the string to check
2) return Optional. Specifies the return value of the str_word_count() function.
Possible values:
0 - Default. Returns the number of words found
1 - Returns an array with the words from the string
2 - Returns an array where the key is the position of the word in the
string, and value is the actual word
3) char Optional. Specifies special characters to be considered as words.
Unit II
Arrays, Functions and Graphics Page 29
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example
<?php
echo"<pre>";
print_r(str_word_count("Hello world!"));
echo"</br>";
print_r(str_word_count("Hello world!",1));
echo"</br>";
print_r(str_word_count("Hello world !",2,"!"));
echo"</br>";
print_r(str_word_count("Hello world !",0,"!"));
echo"</br>";
echo"</pre>";
?>
Output
2
Array
(
[0] => Hello
[1] => world
)
Array
(
[0] => Hello
[6] => world
[12] => !
)
Strlen():
The strlen() function returns the length of a string.
Syntax
strlen(string)
Parameters
string - Required. Specifies the string to check
Example
<?php
echo strlen("Hello world!");
?>
Output
Unit II
Arrays, Functions and Graphics Page 30
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
12
Strrev():
The strrev() function reverses a string.
Syntax
strrev(string)
Parameters
string - Required. Specifies the string to check
Example
<?php
echo strrev("Hello world!");
?>
Output
!dlrow olleH
Strpos():
The strpos() function finds the position of the first occurrence of a string inside
another string. The strpos() function is case-sensitive.
strrpos() - Finds the position of the last occurrence of a string inside another
string (case-sensitive)
stripos() - Finds the position of the first occurrence of a string inside another
string (case-insensitive)
strripos() - Finds the position of the last occurrence of a string inside another
string (case-insensitive)
Syntax
strpos(string,find,start)
strrpos(string,find,start)
stripos(string,find,start)
strripos(string,find,start)
Parameters
1) string - Required. Specifies the string to check
2) find Required. Specifies the string to find
3) start Optional. Specifies where to begin the search. If start is a negative
number, it counts from the end of the string.
Example
Unit II
Arrays, Functions and Graphics Page 31
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
<?php
$str="Hello world!!! Good morning World. world is beautiful";
echo strpos($str,Hello)."</br>";
echo strrpos($str,world)."</br>";
echo stripos($str,Is)."</br>";
echo strripos($str,world,3)."</br>";
?>
Output
0
35
41
35
Strstr_replace():
The str_replace() function replaces some characters with some other
characters in a string.
This function works by the following rules:
1) If the string to be searched is an array, it returns an array
2) If the string to be searched is an array, find and replace is performed with
every array element
3) If both find and replace are arrays, and replace has fewer elements than
find, an empty string will be used as replace
4) If find is an array and replace is a string, the replace string will be used
for every find value
Syntax
str_replace(find,replace,string,count)
Parameters
find- Required. Specifies the value to find
replace- Required. Specifies the value to replace the value in find
string- Required. Specifies the string to be searched
count- Optional. A variable that counts the number of replacements
Example
<?php
echo “Search an array for the value RED, and then replace it with pink”;
$arr = array("blue","red","green","yellow");
$arr2=array("RGB");
$arr3=array("blue","red","green");
print_r(str_replace("red","pink",$arr,$i));
echo "<br>" . "Replacements: $i</br>";
print_r(str_replace($arr3,$arr2,$arr));
?>
Unit II
Arrays, Functions and Graphics Page 32
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Output
Search an array for the value RED, and then replace it with pink.
Array ( [0] => blue [1] => pink [2] => green [3] => yellow )
Replacements: 1
Array ( [0] => RGB [1] => [2] => [3] => yellow )
ucwords():
The ucwords() function converts the first character of each word in a string to
uppercase..
Syntax
ucwords(string, delimiters)
Parameters
string -Required. Specifies the string to convert
delimiters-Optional. Specifies the word separator character
Example
<?php
echo ucwords("hello|world", "|")."</br>";
echo ucwords("hello world");
?>
Output
Hello|World
Hello World
Strtoupper():
The strtoupper() function converts a string to uppercase.
Syntax
strtoupper(string)
Parameters
string - Required. Specifies the string to convert.
Example
<?php
echo strtoupper("hello world");
?>
Output
HELLO WORLD
Unit II
Arrays, Functions and Graphics Page 33
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Strtolower():
The strtolower() function converts a string to lowercase.
Syntax
strtolower(string)
Parameters
string - Required. Specifies the string to convert.
Example
<?php
echo strtolower("HELLO WORLD");
?>
Output
hello world
Strcmp():
The strcmp() function compares two strings.
The strcmp() function is binary-safe and case-sensitive.
This function is similar to the strncmp() function, with the difference that you can
specify the number of characters from each string to be used in the comparison
with strncmp().
The strcasecmp() function compares two strings and it is case-insensitive.
This function is similar to the strncasecmp() function, with the difference that you
can specify the number of characters from each string to be used in the
comparison with strncasecmp().
Syntax
strcmp(string1,string2)
strcasecmp(string1,string2)
strncasecmp(string1,string2,length)
Parameters
strcmp:
string1 Required. Specifies the first string to compare
string2 Required. Specifies the second string to compare
strncmp:
string1 Required. Specifies the first string to compare
string2 Required. Specifies the second string to compare
length Required. Specify the number of characters from each string to be
used in the comparison
Unit II
Arrays, Functions and Graphics Page 34
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Return Value:
This function returns:
1) 0 - if the two strings are equal
2) <0 - if string1 is less than string2
3) >0 - if string1 is greater than string2
Example
<?php
echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>
<?php
echo strncmp("Hello","Hello",6);
echo "<br>";
echo strncmp("Hello","hELLo",6);
?>
Output
0
-32
0
-32
lcfirst():
The lcfirst() function converts the first character of a string to lowercase.
Syntax
lcfirst(string)
Parameters
string -Required. Specifies the string to convert
Example
<?php
echo lcfirst("Good Morning");
echo "<br>";
echo lcfirst("good Morning");
?>
Output
good Morning
good Morning
Unit II
Arrays, Functions and Graphics Page 35
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
1. Creating Image
We can create an image in PHP using imagecreate() function.
Syntax
$image=imagecreate(width,height)
2.
imagecolorallocate() function:-
The imagecolorallocate() function is an inbuilt function in PHP
which is used to set the color in an image. This function returns a color which is
given in RGB format.
Syntax:
imagecolorallocate ( $image, $red, $green, $blue )
Example
<?php
header ("Content-type: image/png");
$a = ImageCreate (200, 200);//imagecreate(x_size, y_size);
$bg = ImageColorAllocate ($a, 240, 0,0);
//imagecolorallocate(image, red, green, blue)
$txt_color = ImageColorAllocate ($a, 0, 23, 0);
ImageString ($a, 10, 10, 18, "Vesp Chembur Mumbai", $txt_color);//bool
imagestring( $image,
$font, $x, $y, $string, $color )
imagepng($a);s
?>
3. Scaling Images:-
Scaling an image means making the image either smaller in size or larger in size
than original.
Using PHP we can resize or rescale the image using the function Imagescale()
Syntax:
imagescale($image,$new_width,$new_height=1,$mode=IMG_BILINERA_FIX
ED)
Parameters:
$image is returned by one of the image creation function.
$new_width holds the width to scale the image.
$new_height holds the height to scale the image.
If the value of this parameter is negative or ommitted then aspect ration of
image will preserve.$mode holds the mode. The value of this parameter is
one of IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED,
IMG_BICUBIC, IMG_BICUBIC_FIXED ...
Unit II
Arrays, Functions and Graphics Page 36
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Features of fpdf
1)It is an open source package,hence freely available on internet
2)It provides the choice of measure unit,page format and margins for pdf page
3)It provides page header and footer management.
4)It provides automatic page breaks to the pdf document
5)It provides the support for various fonts,colors,encoding and image formate.
Example
<?php
require('fpdf183/fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(60,10,'Hello PHP World!',1,1,'C');
$pdf->Output();
?>
Function use
2. $pdf->AddPage();
Simple function, just add the page, you can tell the function to create either a
portrait (P) or landscape (L) by giving it as a first value (ex: $pdf-
>AddPage("L"), $pdf->AddPage("P")).
3. $pdf->SetFont('Arial','BIU',38);
font:- Arial,
BIU' simply tells that we want it to be Bold, Italic & Underlined.
38 mm in size (because of the default size unit).
4. $pdf->SetTextColor(0,0,255);
color :- red (r), the second is green (g) & blue (b).
5. $pdf->Cell(60,20,'PDF+PHP Test',0,1,C,0);
mm of width & 20 mm of height,
Unit II
Arrays, Functions and Graphics Page 37
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
6. $pdf->Output();
Output a new colorful PDF file!
Unit II
Arrays, Functions and Graphics Page 38
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Unit III
Apply Object Oriented Concepts in PHP Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Syntax
<?php
class Fruit {
// code goes here...
}
?>
Unit III
Apply Object Oriented Concepts in PHP Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
In a class, variables are called properties and functions are called methods!
3.
Define Objects
Classes are nothing without objects! We can create multiple objects from a
class.
Each object has all the properties and methods defined in the class, but they
will have different property values.
Objects of a class are created using the new keyword.
In the example below, $apple and $banana are instances of the class Fruit:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
Unit III
Apply Object Oriented Concepts in PHP Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
In the example below, we add two more methods to class Fruit, for setting and
getting the $color property:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods we use -> to access
function set_name($name) { properties and methods of
$this->name = $name; class , object and -> is
} used to access properties
and methods of his own
function get_name() {
class
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>
1. Inside the class (by adding a set_name() method and use $this):
Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
?>
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>
5. PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific
class:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit); ?>
this keyword is used inside a class, generally within the member functions to
access non-static members of a class(variables or functions) for the current object.
Unit III
Apply Object Oriented Concepts in PHP Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
In the program above, we have created a private variable in the class with
name $name and we have two public methods setName() and getName() to
assign a new value to $name variable and to get its value respectively.
Whenever we want to call any variable of class from inside a member
function, we use $this to point to the current object which holds the variable.
We can also use $this to call one member function of a class inside another
member function.
If there is any static member function or variable in the class, we cannot refer
it using the $this.
For example:
printf("Ram is %d years old.\n", $ram->age); // property access
$ram->birthday(); // method call
$ram->set_age(21); // method call with arguments
Example:
<?php
class <CLASS_NAME> {
// constructor
function __construct() {
// initialize the object properties
}
// destructor
function __destruct() {
// clearing the object reference
}
}
?>
Constructor can accept arguments, whereas destructors won't have any
argument because a destructor's job is to destroy the current object reference.
1.
PHP Constructor:-
Let's take the example of a class Person which has two properties, fname and
lname, for this class we will define a constructor for initialising the class
properties(variables) at the time of object creation.
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// public method to show name
public function showName() {
echo "The Legend of India: " . $this->fname . " " . $this->lname;
}
Unit III
Apply Object Oriented Concepts in PHP Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
}
// creating class object
$j = new Person("Bhagat", "Singh");
$j->showName();
?>
Output:
Initialising the object...
The Legend of India: Bhagat Singh
While earlier, we were using the -> operator to set values for the variables or
used the setter methods, in case of a constructor method, we can assign
values to the variables at the time of object creation. If a class has a
constructor then whenever an object of that class is created, the constructor is
called.
2. PHP Destructor:-
PHP Destructor method is called just before PHP is about to release any object
from its memory. Generally, you can close files, clean up resources etc in the
destructor method. Let's take an example,
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname; no need to explicitly call a
} destructor as it will be
// Destructor automatically called once
public function __destruct(){ all program ends its
// clean up resources or do something else execution and same with
echo "Destroying Object..."; construct as class name
} is used to pass
parameters when we
// public method to show name
declare a construct
public function showName() {
echo "The Legend of India: " . $this->fname . " " . $this->lname . "<br/>";
}}
// creating class object
$j = new Person("Swami", "Vivekananda");
$j->showName();
?>
Unit III
Apply Object Oriented Concepts in PHP Page 8
<?php <?php
function getName(){
return $this->name; function __destruct(){}
}
function getType(){ }
return $this->type;
} $honda = new car("hero honda","EV");
function __destruct(){}
} $mycarName=$honda->name;
$mycarType=$honda->type;
echo "Name of car is : ".$mycarName;
$honda = new car("hero honda","EV"); echo "</br> Type of car is: ".$mycarType;
echo "Name of car is : ".$honda->getName();
echo "</br> Type of car is: ".$honda->getType();
?>
Output:
Initialising the object...
The Legend of India: Swami Vivekananda
Destroying Object...
As we can see in the output above, as the PHP program ends, just before it
PHP initiates the release of the object created, and hence the destructor method
is called.
The destructor method cannot accept any argument and is called just before
the object is deleted, which happens either when no reference exist for an
object or when the PHP script finishes its execution.
3.3 1. Inheritance
Unit III
Apply Object Oriented Concepts in PHP Page 9
<?php
class student{
public $name;
public $branch;
function __construct($name,$branch){
$this->name=$name;
$this->branch=$branch;
}
Example
<?php
class car {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The car is {$this->name} and the color is {$this-
>color}.<br>";
}
}
class maruti extends car {
public function message() {
echo " Maruti in an Indian company of car<br>";
}
}
$d = new maruti("swift dzire", "red");
$d->message();
$d->intro();
?>
Output:
Maruti in an Indian company of car
The car is swift dzire and the color is red.
The maruti class is inherited from the car class.This means that the maruti
class can use the public $name and $color properties as well as the public
__construct() and intro() methods from the car class because of inheritance.
The maruti class also has its own method: message().
2. Overloading
1. Function overloading or method overloading is the ability to create
multiple functions of the same name with different implementations
depending on the type of their arguments.
2. Overloading in PHP provides means to dynamically create properties and
methods.
3. These dynamic entities are processed via magic methods, one can
establish in a class for various action types.
4. The overloading methods are invoked when interacting with properties or
methods that have not been declared or are not visible in the current scope
5. All overloading methods must be defined as Public. After creating an
Unit III
Apply Object Oriented Concepts in PHP Page 10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
object for a class, we can access a set of entities that are properties or
methods not defined within the scope of the class.
6. Such entities are said to be overloaded properties or methods, and the
process is called overloading.
7. For working with these overloaded properties or functions, PHP magic
methods are used.
8. Most of the magic methods will be triggered in object context except
__call() method which is used in dynamic context.
9. __call() and __callStatic() are called when somebody is calling a
nonexistent object method in object or static context. public __call ( string
$name , array $arguments ) : mixed public static __callStatic ( string
$name , array $arguments ) : mixed
10. __call() is triggered when invoking inaccessible methods in an object
context. __callStatic() is triggered when invoking inaccessible methods in
a static context.
11. The $name argument is the name of the method being called. The
$arguments argument is an enumerated array containing the parameters
passed to the $name'ed method.
function __call($name,$arg){
if($name == 'area')
switch(count($arg)){
case 0 : return 0 ;
case 1 : return 3.14 * $arg[0]**2 ;
case 2 : return $arg[0] * $arg[1];
}
}
}
$circle = new Shape();
echo "Function without parameters retun ".$circle->area()."<br>";
echo "Area of circle=".$circle->area(3)."<br>";
echo "Area of rectangle=".$circle->area(8,6);
?>
Output:
Function without parameters retun 0
Area of circle=28.26
Area of rectangle=48
Unit III
Apply Object Oriented Concepts in PHP Page 11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
3.
Overriding
1. It is the same as other OOPs programming languages.
2. In this function, both parent and child classes should have the same
function name and number of arguments.
3. It is used to replace the parent method in child class.
4. The purpose of function overriding is to change the behavior of the parent
class method.
5. The two functions with the same name and the same parameter are called
function overriding.
Example
<?php
class aicte {
function helloWorld() {
echo "Parent"."<br>";
}
}
class msbte extends aicte {
function helloWorld() {
echo "\nChild";
}
}
$p = new aicte;
$c= new msbte;
$p->helloWorld();
$c->helloWorld();
?>
Output:
Parent
Child
4.
Cloning Object
1. The clone keyword is used to create a copy of an object.
2. If any of the properties was a reference to another variable or object, then
only the reference is copied.
3. Objects are always passed by reference, so if the original object has
another object in its properties, the copy will point to the same object.
4. This behavior can be changed by creating a __clone() method in the class.
5. The clone keyword allows you to perform a shallow copy of an object.
6. By combining the clone keyword and __clone() magic method, you can
perform a deep copy of an object.
Unit III
Apply Object Oriented Concepts in PHP Page 12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
<pre>
<?php
class class1{
public $name; Output:
public $ref_class2;
function setname($n) After change:
{ class1 Object
$this->name=$n; (
} [name] => ABC
} [ref_class2] => class2 Object
class class2{ (
public $roll_no; [roll_no] => 10
public $std; [std] => TYCO
function set_detail($r,$s)
)
{
$this->roll_no=$r;
)
$this->std=$s;
clone object
}
class1 Object
}
(
$c1=new class1();
$c1->name="XYZ"; [name] => ABC
$c1->ref_class2=new class2(); [ref_class2] => class2 Object
$c1->ref_class2->roll_no=50; (
$c1->ref_class2->std="SYCO"; [roll_no] => 10
$c2=$c1; [std] => TYCO
$c1->setname("ABC"); )
$c1->ref_class2->set_detail(10,"TYCO");
echo"After change:<br>"; )
print_r($c1);
echo"clone object<br>";
print_r($c2);
?>
</pre>
In this example, both $c1 and $c2 reference the same object in the memory. When
we change the property of an object, it reflects in both references.
C1
$name: XYZ $roll_no: 10
$ref_class2: ref $std: TYCO
C2
Unit III
Apply Object Oriented Concepts in PHP Page 13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
PHP provides you with the clone keyword that allows you to create a shallow
copy of an object. For example:
<pre>
<?php Output:
class class1{
public $name; After change:
public $ref_class2;
class1 Object
function setname($n)
(
{
[name] => ABC
$this->name=$n;
[ref_class2] => class2 Object
}
(
}
[roll_no] => 10
class class2{
public $roll_no; [std] => TYCO
public $std; )
function set_detail($r,$s)
{ )
$this->roll_no=$r; clone object
$this->std=$s; class1 Object
} (
} [name] => XYZ
$c1=new class1(); [ref_class2] => class2 Object
$c1->name="XYZ"; (
$c1->ref_class2=new class2(); [roll_no] => 10
$c1->ref_class2->roll_no=50; [std] => TYCO
$c1->ref_class2->std="SYCO"; )
$c2=clone $c1;
$c1->setname("ABC"); )
$c1->ref_class2-
>set_detail(10,"TYCO");
echo"After change:<br>";
print_r($c1);
echo"clone object<br>";
print_r($c2);
?> $name: ABC
</pre> C1 $ref_class2: ref
$roll_no: 10
$std: TYCO
C2 $name: XYZ
$ref_class2: ref
Unit III
Apply Object Oriented Concepts in PHP Page 14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Unit III
Apply Object Oriented Concepts in PHP Page 15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
echo"clone object<br>";
print_r($c2);
?>
</pre>
C2
$name: XYZ $roll_no: 10
$ref_class2: ref $std: TYCO
3.4 1. Introspection
Introspection is the ability of a program to examine an object characteristics such
as its name, parent class, properties and method.
(i) class_exists():
This function is used to determine whether a class exists.It takes a string
and return a Boolean value.
Syntax-
$yes_no=class_exists(classname);
This function returns TRUE if classname is a defined class, or FALSE
(ii) get_class_method()
This function returns the names of the class methods.
(iii) get_parent_class():
return the class name of an object parent class
(iv) is_subclass_of():
The is_subclass_of() function returns TRUE if the object “object” belongs
to a class which is a subclass of “class”, FALSE otherwise.
Syntax
is_subclass_of(object, class, string)
Unit III
Apply Object Oriented Concepts in PHP Page 16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
<?php
if(class_exists('parent'))
{
$ob=new parent();
echo "This is parent class";
}
else
{
echo "Not exist";
}
?>
output:
Not exist
<?php
class TYCO
{
function a()
{
echo "hey CO6I";
}}
if(class_exists('TYCO'))
{
$ob=new TYCO();
echo "This is TYCO class…";
echo "<br>";
echo $ob->a();
}
else
{
echo "Not exist";
}
?>
Output:
This is TYCO class…
hey CO6I
Unit III
Apply Object Oriented Concepts in PHP Page 17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
<pre>
<?php
class Rectangle
{
var $dim1 = 2;
var $dim2 = 10;
function Rectangle1($dim1,$dim2)
{
$this->dim1 = $dim1;
$this->dim2 = $dim2;
}
}
function display()
{
echo"This is child class display";
}
}
$a = new area(4,2);
echo"get the class varibale i.e properties<br>";
$class_properties = get_class_vars("Rectangle");
print_r($class_properties);
$parent=get_parent_class(area);
print_r($parent);
Output:
Unit III
Apply Object Oriented Concepts in PHP Page 19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
2.
serialize
The serialize() function converts a storable representation of a value.
Syntax
serialize(value);
To serialize data means to convert a value to a sequence of bits, so that it
can be stored in a file, a memory buffer, or transmitted across a network.
<?php
Example
// Complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);
// Convert to a string
$string = serialize($myvar);
// Printing the serialized data
echo $string;
?>
Output:
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
3.
Unserialize()
The unserialize() is an inbuilt function php that is used to unserialize the
given serialized array to get back to the original value of the complex array,
$myvar.
Syntax:
unserialize( $serialized_array )
Below program illustrate both serialize() and unserialize() functions:
Program:
<?php
// Complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);
// Serialize the above data
$string = serialize($myvar);
// Unserializing the data in $string
$newvar = unserialize($string);
// Printing the unserialized data
print_r($newvar);
Unit III
Apply Object Oriented Concepts in PHP Page 20
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
?>
Output:
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
Unit III
Apply Object Oriented Concepts in PHP Page 21
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
4.5 Cookies :
Use of cookies
Attributes of cookies
Create cookies
Modify Cookies value
Delete cookies
4.6 Session:
Use of session
Start session
Get session variables
Destroy session
Unit IV
Creating and Validating Forms 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
i. GET method:
1. The GET method sends the encoded user information appended to the page
request (to the url). The code and the encoded information are separated by the ?
character.
2. http://www.test.com/index.htm?name1=value1&name2=value2
3. The GET method produces a long string that appears in our server logs, in th
browser’s location:box.
4. Never use the GET method if we have a password or other sensitive information
to be sent to the server. Get cannot be used to send binary data, like images or
word documents, to the server.
5. The data sent by the GET method can be accessed using the QUESRY_STRING
environment variable.
6. PHP provides a $_GET associative array to access all the sent information using
the GET method.
Unit IV
Creating and Validating Forms 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
ii POST Method
1. The POST method transfers information via HTTP headers. The information is
encoded as described in the case of the GET method and put into a header called
QUERY_STRING.
2. The POST method does not have any restriction on data size to be sent.
3. The POST method can be used to send ASCII as well as binary data.
4. The data sent by POST method goes through HTTP header so security depends
on HTTP protocol. By using Secure HTTP you can make sure that your
information is secure.
5. The PHP provides a $_POST associative array to access all the sent information
using the POST method.
GET Method
1. Information sent from a form with the get method is visible to everyone(all variable
names and values are displayed in the URL)
2. GET has limits on the amount of information to send. The limitation is about 2048
characters.
3. $_GET is an array of variables passed to the current script via the URL parameters.
4. Can be bookmarked.
5. Can be cached.
6. Parameters remain in browser history.
POST Method
1. Information sent from a form with the post method is invisible to others(all
names/values are embedded within the body of the HTTP request)
2. Post has no limits on the amount of information to send.
3. $_POST is an array of variables passed to the current script via the HTTP POST
method.
4. Cannot be bookmarked.
5. Not cached.
6. Parameters are not saved in browser history.
3. Server Role
1. Role of PHP in Web Applications.
2. PHP is a server side scripting language. That means its processing happens in the
server by consuming server's resources and sends only the output to the client.
3. In a client side scripting language like JavaScript, processing happens in the client's
compute Consuming its resources.
Unit IV
Creating and Validating Forms 3
See after this u will come across something like
$_POST
$_GET
$_SERVER
$_COOKIE
eg. superglobal
$_COOKIE[“name”] ;
// returns the value of cookie who’s name is specified
Function
Step 4
2. Textarea
Unit IV
Creating and Validating Forms 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
A text area field is similar to a text input field but it allows the user to enter
multiple line of text.
Syntax
<textarea name=name of component row=“some number”cols=“some number”><
/textarea>
Eg<textarea name=”address” rows=“5” cols=“40”>< /textarea>
3.
Checkbox
<form action="#" method="post">
<input type="checkbox" name="gender" value="Male">Male</input>
<input type="checkbox" name="gender" value="Female">Female</input>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
if (isset($_POST['gender'])){
echo $_POST['gender']; // Displays value of checked checkbox.
} ?>
<?php
if(isset($_POST['submit']))
{//to run PHP script on submit
if(!empty($_POST['check_list']))
{
// Loop to store and display values of individual checked checkboxes.
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}
}
}
?>
4. List Box
Unit IV
Creating and Validating Forms 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
<html>
<body>
<div>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<label> Best Engineering College in Maharashtra</label>
<p><select name="products[]" multiple="multiple">
<option>VESIT</option>
<option>VJTI</option>
<option>COEP</option>
<option>PCIT</option>
<option>IIT</option>
<option>AVCOE</option>
<option>DY Patil</option>
<option>BATU</option>
</select></p>
<p><input type="submit" value="Test me!" /></p>
</form>
</div></body></html>
<?php
if (is_array ( $_POST ['products'] )) {
print "<p>Your product choices are:</p>";
print "<ul>";
foreach ( $_POST ['products'] as $value ) {
print "<li>$value</li>\n";
}
print "</ul>";
}?>
<form method="post">
<h3>personal information form</h3>
user name:<input type="text" name="username"/>
<br/><br/>
address:<input type="text" name="address"/>
<br/><br/>
<input type="submit" name="submit_personal_info" value="submit"/>
<br/>
</form>
<form method="post">
<h3>Feedback Form</h3>
<textarea name="feedback" rows="5" cols="50"></textarea>
<br/>
<input type="submit" name="submit_feedback"/>
</form>
<?php
if(!empty($_POST['submit_personal_info']))
{
echo "<h3>welcome user:".$_POST['username']."</h3>";
}
if(!empty($_POST['submit_feedback']))
{
echo "<h3>we value your feedback:</h3>";
echo "your feedback is<br/>".$_POST["feedback"];
}
?>
2.
A form having multiple submit buttons.
<form method="post">
<h3>Simple Arithmetic Calculator</h3>
Number 1: <input type="text" size="5" name="num1"/>
<br/><br>
Number 2: <input type="text" size="5" name="num2"/>
<br/><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
<input type="submit" name="mul" value="MULTIPLICATION"/>
<input type="submit" name="div" value="DIVISION"/>
<?PHP
if(!empty($_POST['add'])) {
$result=$_POST['num1']+$_POST['num2'];
echo "<h3> Addition: ".$result."</h3>";
}
if(!empty($_POST['sub']))
Unit IV
Creating and Validating Forms 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
{
$result=$_POST['num1']-$_POST['num2'];
echo "<h3> Subtraction: ".$result."</h3>";
}
if(!empty($_POST['mul']))
{
$result=$_POST['num1']*$_POST['num2'];
echo "<h3> Multiplication: ".$result."</h3>";
}
if(!empty($_POST['div']))
{
$result=$_POST['num1']/$_POST['num2'];
echo "<h3> Division: ".$result."</h3>";
}
?>
Unit IV
Creating and Validating Forms 8
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example of validation
Use this
1. filter_var()
Valid URL
Below code shows validation of URL
function instead
$weburl = input($_POST["sitename"]); of regex :)
if(filter_var($weburl,FILTER_VALIDATE_URL)){
echo “valid url”;
}
else{
echo “invalid url”;
}
Above syntax will verify whether a given URL is valid or not. It should allow
some keywords as https, ftp, www, a-z, 0-9,..etc..
2.
Valid Email
Below code shows validation of Email address
<?php
$emailid = "tejasnarwadegmail.com";
?>
Predefined function for validation in php are given below:
i) The filter_input() function gets an external variable (e.g. from form input) and
optionally filters it. This function is used to validate variables from insecure sources,
such as user input.
Syntax
filter_input(type, variable, filter)
type Required. The input type to check for. Can be one of the following:
INPUT_GET
INPUT_POST
INPUT_COOKIE
Unit IV
Creating and Validating Forms 9
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
INPUT_SERVER
INPUT_ENV
variable Required. The variable name to check
filter Optional. Specifies the ID or name of the filter to use. Default is
FILTER_DEFAULT, which results in no filtering
Program:
<?php
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) {
echo("Email is not valid");
} else {
echo("Email is valid");
}
?>
ii) The filter_var() function filters a variable with the specified filter.
Syntax
filter_var(var, filtername)
Program:
<?php
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
2.5
Cookie
1. Cookie is a small piece of information stored as a file in the user's browser by the
web server.
2. Once created, cookie is sent to the web server as header information with every
HTTP request.
3. You can use cookies to save any data but it should not exceed 1K(1024 bytes) in
size.
4. Before we move on to how to create, update and delete cookies, let's learn a few real
world uses of cookies.
Unit IV
Creating and Validating Forms
10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Here,
1) A user requests for a page that stores cookies
2) The server sets the cookie on the user’s computer
3) Other page requests from the user will return the cookie name and value
1.
Why and when to use Cookies?
Http is a stateless protocol; cookies allow us to track the state of the application
using small files stored on the user’s computer. The path where the cookies are
stored depends on the browser. Internet Explorer usually stores them in the
Temporary Internet Files folder.
Personalizing the user experience – this is achieved by allowing users to select their
preferences. The page requested that follows are personalized based on the set
preferences in the cookies.
Tracking the pages visited by a user
To store user information like when he/she visited, what pages were visited on the
website etc, so that next time the user visits your website you can provide a better
user experience.
To store basic website specific information to know this is not the first visit of
user.
You can use cookies to store the number of visits or view counters.
I hope this gives you an idea about how you can utilize cookies in your web
application.
2.
Types of Cookies
There are two types of cookies, they are:
1. Session Cookie:
This type of cookies are temporary and expire as soon as the session ends or the
browser is closed.
2. Persistent Cookie:
To make a cookie persistent we must provide it with an expiration time. Then
the cookie will only expire after the given expiration time, until then it will be a
valid cookie.
3. You can use cookies to store number of visits or view counter.
Unit IV
Creating and Validating Forms
11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example
So if we want to create a cookie to store the name of the user who visited your website,
and set an expiration time of a week, then we can do it like this,
<?php
setcookie("username", "Shika", time()+60*60*24*7);
?>
To access a stored cookie we use the $_COOKIE global variable, and can use the
isset() methods to check whether the cookie is set or not.
Let's have a complete example where we will set a cookie and then retrieve it t
show its value in the HTML page.
<?php
// set the cookie
setcookie("username", "Ramkra", time()+60*60*24*7);
Unit IV
Creating and Validating Forms
12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
So by providing the name of the cookie inside the square brackets with the global
variable $_COOKIE[] we can access the cookie.
setcookie() function must be placed before the starting HTML tag(<html>).
4.
Updating Cookie in PHP
To update/modify a cookie, simply set it again. For example, if we want to update
the username
stored in the cookie created above, we can do it using setcookie() method again,
<?php
// updating the cookie
setcookie("username", "Ambarish", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
We just update the value of the username cookie.
Unit IV
Creating and Validating Forms
13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
5.
Delete a Cookie in PHP
To delete/remove a cookie, we need to expire the cookie, which can be done b
updating the cookie using the setcookie() function with expiration date in past.
<?php
// updating the cookie
setcookie("username", "Dhruv", time() - 3600);
?>
<html>
<body>
<?php
echo "cookie username is deleted!";
?>
</body>
</html>
And with this, we now know how to create a cookie, how to update it and how to
delete it when we no longer need it.
2.6 Session
1. A session is a way to store information (in variables) to be used across multiple
pages. Unlike a cookie, the information is not stored on the user's computer.
2. When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session.
3. The computer knows who you are. It knows when you start the application and
when you end. But on the internet there is one problem: the web server does not
know who you are or what you do, because the HTTP address doesn't maintain
state.
4. Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc). By default, session variables
last until the user closes the browser.
5. So Session variables hold information about one single user, and are available to
all pages in one application.
6. If you need permanent storage, you may want to store the data in a database.
1.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a
new PHP session and set some session variables.
ExampleGet your own PHP Server
<?php
// Start the session
session_start();
?>
Unit IV
Creating and Validating Forms
14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
The session_start() function must be the very first thing in your document. Before
any HTML tags.
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
3.
Modify a PHP Session Variable
To change a session variable, just overwrite it:
Example
<?php
session_start();
Unit IV
Creating and Validating Forms
15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
4.
Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset()
and session_destroy().
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
4.7
Sending E-mail
PHP mail is the built-in PHP function that is used to send emails from PHP scripts.
The mail function accepts the following parameters;
1. Email address
2. Subject
3. Message
4. CC or BCC email addresses
Unit IV
Creating and Validating Forms
16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Use of Mail()
1. It’s a cost effective way of notifying users on important events.
2. Let users contact you via email by providing a contact us form on the website that
emails the provided content.
3. Developers can use it to receive system errors by email
4. You can use it to email your newsletter subscribers.
5. You can use it to send password reset links to users who forget their passwords
6. You can use it to email activation/confirmation links.
7. This is useful when registering users and verifying their email addresses Sending
mail using PHP.
HERE,
“$to_email_address” is the email address of the mail recipient
“$subject” is the email subject
“$message” is the message to be sent.
“[$headers]” is optional, it can be used to include information such as CC, BCC
CC is the acronym for carbon copy. It’s used when you want to send a copy to
an interested
person i.e. a complaint email sent to a company can also be sent as CC to the
complaints board.
BCC is the acronym for blind carbon copy. It is similar to CC. The email
addresses included in the
BCC section will not be shown to the other recipients.
1. File :-Php.ini
//email function
smtp_port=465
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
mail.add_x_header=on
2. File:- sendemail.ini
smtp_server=smtp.gmail.com
smtp_port=465
Unit IV
Creating and Validating Forms
17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
smtp_ssl=auto
error_logfile=error.log
[email protected]
auth_password=
1.Configure SMTP settings on your localhost Assuming you are using xampp on
windows, locate the “php.ini” in the directory “C:\xampp\php”.
● Open it using a notepad or any text editor. We will use a notepad in this example.
Click
on the edit menu
Unit IV
Creating and Validating Forms
18
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Unit IV
Creating and Validating Forms
19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Unit IV
Creating and Validating Forms
20
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Unit V
Database Operations Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
1.Create database
<?php
$servername = "localhost";
$username = "root";
$password = "";/* Put your password here*/
/* Create connection*/
$conn = mysqli_connect($servername, $username, $password);
/* Check connection*/
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/* Create database*/
$sql = "CREATE DATABASE stud";
if (mysqli_query($conn, $sql)) {
echo " $sql created successfully";
}else{
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Parameter Description
1. host Optional. Specifies a host name or an IP address
2. username Optional. Specifies the MySQL username
3. password Optional. Specifies the MySQL password
4. dbname Optional. Specifies the default database to be used
Unit V
Database Operations Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
The die():-
It is an inbuilt function in PHP. It is used to print message and exit from the
current php script. It is equivalent to the exit() function in PHP.
Syntax :
die($message)
Parameters :
This function accepts only one parameter and which is not mandatory to be
passed.
$message :
This parameter represents the message to be printed while exiting from script.
PHP will work with virtually all database software,including oracle and sybase
but most commonly used is freely available MYSQL database php 5 and later can
work with MYSQL database using:
1. MYSQLi extension(“the “i” stands for improved”),and
2. PDO(php data objects)
Unit V
Database Operations Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
There are 3 ways in which we can connect to MySQl from PHP as listed above
and described below:
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Output:
Connected successfully
Explanation:
We can create an instance of the mysqli class providing all the necessary
details required to establish the connection such as host, username, password
etc. If the instance is created successfully then the connection is successful
otherwise there is some error in establishing connection.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
Unit V
Database Operations Page 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Output:
Connected successfully
Explanation:
In MySQLi procedural approach instead of creating an instance we can use
the mysqli_connect() function available in PHP to establish a connection.
This function takes the information as arguments such as host, username ,
password , database name etc. This function returns MySQL link identifier
on successful connection or FALSE when failed to establish a connection.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Output:
Connected successfully
Explanation:
The exception class in PDO is used to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the
script stops executing and flows directly to the first catch(){ } block.
Unit V
Database Operations Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
2. Closing A Connection
When we establish a connection to a MySQL database from a PHP script , we
should also disconnect or close the connection when our work is finished. Here
we have described the syntax of closing the connection to a MySQL database in
all 3 methods described above. We have assumed that the reference to the
connection is stored in $conn variable.
1. Insert operation
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO co (firstname, lastname, email)
VALUES ('abc', 'xyz', '[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Unit V
Database Operations Page 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
2. Retrieve Data
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname,email,reg_date FROM co";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]."-Email:"."
".$row["email"]."-Time"." ".$row["reg_date"]."<br>";
//print_r($row);
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
3. Update data
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE co SET lastname='XYZ', firstname='ABC' WHERE
id=3";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
Unit V
Database Operations Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
4. Delete Data.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "delete FROM co WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Unit V
Database Operations Page 8