PHP Unit-I
PHP Unit-I
Introduction
PHP Features:
Performance: Script written in PHP executes much faster than those scripts
written in other languages such as JSP & ASP.
Open Source Software: PHP source code is free available on the web, you can
developed all the version of PHP according to your requirement without paying any
cost.
Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed
in other OS also.
Compatibility: PHP is compatible with almost all local servers used today like
Apache, IIS etc.
Embedded: PHP code can be easily embedded within HTML tags and script.
Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software
stack. It is available for all operating systems. There are many AMP options
available in the market that are given below:
XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some
other components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.
1
If you are on Windows and don't want Perl and other features of XAMPP, you
should go for WAMP. In a similar way, you may use LAMP for Linux and MAMP for
Macintosh.
PHP Variables
$variablename=value;
A variable starts with the $ sign, followed by the name of the variable
Variable names consist of letters ,digits and underscore symbol (A-z, 0-9,
and _ )
Variable names are case-sensitive ($vaag and $VAAG are two different
variables)
PHP Echo
PHP echo is a language construct not a function, so you don't need to use
parenthesis with it. But if you want to use more than one parameters, it is
required to use parenthesis.
PHP echo statement can be used to print string, multi line strings, escaping
characters, variable, array etc.
File: echo1.php
<?php
?>
2
PHP echo: printing multi line string
File: echo2.php
<?php
text printed by
?>
Output:
Hello by PHP echo this is multi line text printed by PHP echo statement
File: echo3.php
<?php
?>
Output:
PHP Operators
Types of operators.
1. Arithmetic operators.
2. Assignment Operators
4. Comparison operators
5. Conditional operators
6. Logical Operators.
3
7. Bitwise Operators.
8. String Operators.
1. Arithmetic operators.
Example:
<?php
$x=100;
$y=60;
?>
Output:
4
Division of x and y : 1.6666666666667
Modulus of x and y : 40
2. Assignment Operators
Assignment operators allow writing a value to a variable. The first operand must
be a variable and the basic assignment operator is "=".
The following table discussed more details of the assignment operators.
$a-= $b $a = $a -$b Subtracts 2 numbers and assigns the result to the first.
$a*= $b $a = $a*$b Multiplies 2 numbers and assigns the result to the first.
$a/= $b $a = $a/$b Divides 2 numbers and assigns the result to the first.
5
Output:
200
0
90000
1
0
Value of x & y is : 20 11
PHP supports C-style pre and post increment and decrement operators. The
Increment/decrement operators operate only on variables and not on any value.
List of increment/decrement operators
Example Name Effect
++$x Pre-increment Increments $x by 1, then returns $x.
$x++ Post-increment Returns $x, then increments $x by 1.
--$x Pre-decrement Decrements $x by 1, then returns $x.
$x-- Post-decrement Returns $x, then decrements $x by 1.
Example:
<?php
$a=12;
$b=++$a;
echo"a value is".$a;
echo "b value is".$b;
$c=14;
$d=$c++;
echo"c value is".$c;
echo "d value is".$d;
$e=11;
$f=--$e;
echo"e value is".$e;
echo "f value is".$f;
$g=13;
$h=$g--;
echo"g value is".$g;
echo "h value is".$h;
?>
Output:
a value is13
b value is13
c value is15
6
d value is14
e value is10
f value is10
g value is12
h value is13
4.comparison operators
7
Example for identical
<?php
$x = 300;
$y = "300";
?>
Output:
bool(false)
<?php
$x = 150;
$y = "150";
?>
Output:
bool(true)
5. Conditional operators
Example:
<?php
$a = 10;
$b = 20;
6.Logical Operators.
The standard logical operators and, or, not, and xor are supported by PHP. Logical
operators first convert their operands to boolean values and then perform the
respective comparison.
xor xor $x xor $y is true if either $x or $y are true, but not both.
Example:
<?php
var_dump($a);
var_dump($b);
var_dump($c);
9
var_dump($d);
$a = true || false;
var_dump($a);
$b = false || true;
var_dump($b);
$c = true || true;
var_dump($c);
$d = false || false;
var_dump($d);
?>
Output:
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
7. Bitwise operators
Bitwise operators allow operating on the bitwise representation of their
arguments.
& And $x & $y Bits that are set in both $x and $y are set.
^ Xor $x ^ $y Bits that are set in $x or $y but not both are set.
~ Not ~$x Bits that are set in $x are not set, and vice versa.
<< Shift left $x << $y Shift the bits of $x $y steps to the left.#
>> Shift right $x >> $y Shift the bits of $x $y steps to the right.*
10
8. String Operators.
There are two string operators : concatenation operator ('.') and concatenating
assignment operator ('.=').
<?php
$x = "Good";
$y = $x ." Morning";
echo $y;
?>
Output:
Good Morning
<?php
$x = "Good";
echo $x;
?>
Output
11
2.if..else
3.nested..if
4.else…if ladder
Simple if: In a simple if statement, a condition is tested if the condition is true, a
set of statements are executed: if the condition is false, the statements are not
executed and the program control goes to the next statement that immediately
follows if block.
Syntax:
if(condition)
{
Statement(s);
}
Next statement;
Example:
<?php
$number=15;
if($number<50)
{
echo "$number is less than 50";
}
?>
Output: 15 is less than 50
If-else:
In case of if-else, acondition is tested,if it is true the statement part followed by “if”
will be executed.If it is false the statement part followed by “else” will be
executed.any one of the statement part will be executed but not both.
Syntax:
if(condition)
{
Statement-1;
}
else
{
Statement-2;
}
Next statement;
12
Example:
<?php
$num=10;
if($num%2==0)
{
echo "$num is even number";
}
else
{
echo "$num is odd number";
}
?>
Output: 10 is even number
Nested-if:
If an “if” statement is enclosed within another “if” statement, then it is called
“nested-if”.
Syntax:
if(condition1)
{
if(condition2)
Statement-1;
else
Statement-2;
}
else
{
if(condition3)
Statement-3;
else
Statement-4;
}
else-if ladder:
A sequence of conditions is tested followed by a sequence of actions to be
performed to form an else-if ladder.
Syntax:
if(condition1)
Statement-1;
else
if(condition2)
Statement-2;
13
else
if(condition3)
Statement-3;
----
----
if(condition4)
Statement-4;
else
Next statement;
Example:
<?php
$m=45;
$p=45;
$c=45;
$total=$m+$p+$c;
echo"total is".$total;
$avg=$total/3;
echo"average is".$avg;
if(($m>=35)&&($p>=35)&&($c>35))
{
if($avg>=70)
echo"distinction";
else
if(($avg>60)&&($avg<70))
echo"first class";
else
if(($avg>50)&&($avg<60))
echo"second class";
else
if(($avg>40)&&($avg<50))
echo"Third class";
else
echo"pass division";
}
else
{
echo"Fail";
}
?>
Output:
total is135
average is 45
Third class
14
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions.
It works like PHP if-else-if statement.
Syntax:
switch(expression)
{
case label1:
//code to be executed
break;
case label2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Example:
<?php
$num=20;
switch($num)
{
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
number is equal to 20
Iterative statements:
Iterative statements enable program execution to repeat one or more statements.
15
While:
The while statement will be executed repeatedly as long as the expression remains
true.
Syntax:
while(test-condition)
{
//body of the loop
}
Do-while:
It is similar to that of while loop except that it always executes at least once. It is
an exit control structure. The test of expression for repeating is done after each
time body of loop is executed.
Syntax:
do
{
//body of loop
}
while(Expression);
Example:
<?php
$n=1;
16
do
{
echo $n;
$n=$n+1;
}while($n<=5);
?>
Output: 1 2 3 4 5
for loop:
It is another entry controlled statement.
Syntax:
for(initialization;condition;increment/decrement)
{
//body of loop;
}
2. The value of control variable is tested using test condition. If the condition is
true body of the loop is executed otherwise loop is terminated.
3. After the body of loop is executed, the control is transferred back to for
statement. The value of control variable is incremented depending on statement
given.
Example:
<?php
for($n=1;$n<=5;$n++)
{
echo $n;
}
?>
Output:1 2 3 4 5
Example2:
<?php
for($i=1;$i<=4;$i++)
{
for($j=1;$j<=$i;$j++)
{
echo"*";
17
}
echo"<br>";
}
?>
Output:
*
**
***
****
Break:
It is a key word used to terminate loop or to exit from switch statement.
Syntax:
Statements;
Break;
Example:
<?php
for($i=1;$i<=50;$i++)
{
if($i==10)break;
echo $i;
}
?>
Output: 123456789
Continue:
it is used to skip some of the statements in a loop
Syntax:
Continue;
Example:
<?php
for($i=1;$i<=10;$i++)
{
if($i%2==0)continue;
echo $i;
}
?>
Output: 13579
18
Arrays
An array stores multiple values in one single variable:
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
File: array2.php
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
19
Traversing PHP Indexed Array
We can easily traverse array in PHP using foreach loop. Let's see a simple example
to traverse all the elements of PHP array.
File: array3.php
<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
Output:
Size is: Big
Size is: Medium
Size is: Short
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
Output:
3
PHP allows you to associate name/label with each array elements in PHP using =>
symbol. Such way, you can easily remember the element because each element is
represented by label than an incremented number.
Definition
There are two ways to define associative array:
1st way:
1.
$salary=array("Sachin"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
$salary["Sachin"]="550000";
$slary["Vimal"]="250000";
$salary["Ratan"]="200000";
20
Example
File: arrayassociative1.php
<?php
$salary=array("Sachin"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
echo "Sachin salary: ".$salary["Sachin"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
Output:
Sachin salary: 550000
Vimal salary: 250000
Ratan salary: 200000
File: arrayassociative2.php
<?php
$salary["Sachin"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
echo "Sachin salary: ".$salary["Sachin"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
Output:
Sachin salary: 550000
Vimal salary: 250000
Ratan salary: 200000
21
PHP Multidimensional Array
Id Name Salary
1 sachin 400000
2 john 500000
3 rahul 300000
File:
multiarray.php
<?php
$emp = array
(
array(1,"sachin",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
22
}
echo "<br/>";
}
?>
Output:
1 sachin 400000
2 john 500000
3 rahul 300000
Syntax
1. array array ([ mixed $... ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
Syntax
1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )
Example
<?php
$salary=array("Sachin"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
Output:
Array ( [SACHIN] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
23
<?php
$salary=array("Sachin"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_LOWER));
?>
Output:
Array ( [sachin] => 550000 [vimal] => 250000 [ratan] => 200000 )
Syntax
1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
Example
<?php
$salary=array("Sachin"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_chunk($salary,2));
?>
Output: Array (
=> Array ( [0] => 550000 [1] => 250000 )
=> Array ( [0] => 200000 )
)
4) PHP count() function
PHP count() function counts all elements in an array.
Syntax
1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>
Output:
4
24
Example
<?php
$season=array("summer","winter","spring","autumn");
sort($season);
foreach( $season as $s )
{
echo "$s<br />";
}
?>
Output:
autumn
spring
summer
winter
Example
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
Output:
autumn spring winter summer
Syntax
1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )
Example
<?php
25
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
Output:
2
<?php
$name1=array("sachin","john","vikas","smith");
$name2=array("umesh","sachin","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
Output:
sachin smith
PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text.
There are 4 ways to specify string in PHP.
single quoted
double quoted
heredoc syntax
newdoc syntax (since PHP 5.3)
Single Quoted PHP String
We can create a string in PHP by enclosing text in a single quote. It is the easiest
way to specify string in PHP.
<?php
$str='Hello text within single quote';
echo $str;
?>
Output:
Hello text within single quote
26
We can store multiple line text, special characters and escape sequences in a
single quoted PHP string.
<?php
$str1='Hello text multiple line text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string Using escape
sequences \n in single quoted string
Note: In single quoted PHP strings, most escape sequences and variables
will not be interpreted. But, we can use single quote through \' and
backslash through \\ inside single quoted PHP strings.
<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
trying variable $num1
trying backslash n and backslash t inside single quoted string \n \t Using
single quote 'my quote' and \backslash
27
Output:
Hello text within double quote
Now, you can't use double quote directly inside double quoted string.
<?php
$str1="Using double "quote" directly inside double quoted string";
echo $str1;
?>
Output:
Parse error: syntax error, unexpected 'quote' (T_STRING) in
C:\wamp\www\string1.php on line 2
We can store multiple line text, special characters and escape sequences in a
double quoted PHP string.
<?php
$str1="Hello text multiple line text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Hello text multiple line text within double quoted string
Using double "quote" with backslash inside double quoted string Using escape
sequences in double quoted string
PHP provides various string functions to access and manipulate strings. A list of
important PHP string functions are given below.
28
Example
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>
Output:
my name is khan
Syntax
1. string strtoupper ( string $string )
Example
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>
Output:
MY NAME IS KHAN
Syntax
1. string ucfirst ( string $str )
Example
<?php
$str="my name is KHAN";
$str=ucfirst($str);
echo $str;
?>
Output:
My name is KHAN
29
4) PHP lcfirst() function
The lcfirst() function returns string converting first character into lowercase. It
doesn't change the case of other characters.
Syntax
1. string lcfirst ( string $str )
Example
<?php
$str="MY name IS KHAN";
$str=lcfirst($str);
echo $str;
?>
Output:
mY name IS KHAN
Syntax
1. string ucwords ( string $str )
Example
<?php
$str="my name is Sachin tendulkar";
$str=ucwords($str);
echo $str;
?>
Output:
My Name Is Sachin Tendulkar
Syntax
1. string strrev ( string $string )
Example
<?php
$str="my name is Sachin tendulkar";
$str=strrev($str);
echo $str;
?>
30
Output:
lawsiaj oonoS si eman ym
Example
<?php
$str="my name is Sachin tendulkar";
$str=strlen($str);
echo $str;
?>
Output:
24
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input
as argument list and return value. There are thousands of built-in functions in
PHP.
Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many
times. By the use of function, you can write the logic only once and reuse it.
31
PHP User-defined Functions
We can declare and call user-defined functions easily. Let's see the syntax to
declare user-defined functions.
Syntax
function functionname()
{
//code to be executed
Note: Function name must be start with letter and underscore only like
other labels in PHP. It can't be start with numbers or special symbols.
File: function1.php
<?php
function sayHello()
{
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
Hello PHP Function
File: functionarg.php
<?php
function sayHello($name)
{
32
echo "Hello $name<br/>";
}
sayHello("Sachin");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sachin
Hello Vimal
Hello John
Let's see the example to pass two argument in PHP function.
File: functionarg2.php
<?php
function sayHello($name,$age)
{
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sachin",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Hello Sachin, you are 27 years old Hello Vimal, you are 29 years old Hello
John, you are 23 years old
Value passed to the function doesn't modify the actual value by default (call by
value).
But we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a
reference, you need to use ampersand (&) symbol before the argument name.
Let's see a simple example of call by reference in PHP.
File: functionref.php
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
33
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello Call By Reference
We can specify a default argument value in function. While calling PHP function if
you don't specify any argument, it will take the default argument. Let's see a
simple example of using default argument value in PHP function.
File: functiondefaultarg.php
<?php
function sayHello($name="Sachin")
{
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh Hello Sachin Hello John
<?php
function cube($n)
{
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
34
PHP Parameterized Function
PHP Parameterized functions are the functions with parameters. You can pass any
number of parameters inside a function. These passed parameters act as variables
inside your function.
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the
function.
PHP Parameterized Example 1
<html>
<head>
<title>Parameter Addition and Subtraction Example</title>
</head>
<body>
<?php
function add($x, $y)
{
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
function sub($x, $y)
{
$diff = $x - $y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>
</body>
</html>
Output:
35
PHP Parameterized Example 2
Addition and Subtraction with Dynamic number
In this example, we have passed two parameters $x and $y inside two functions
add() and sub().
<?php
//add() function with two parameter
function add($x,$y)
{
$sum=$x+$y;
echo "Sum = $sum <br><br>";
}
//sub() function with two parameter
function sub($x,$y)
{
$sub=$x-$y;
echo "Diff = $sub <br><br>";
}
if(isset($_POST['add']))
{
add($_POST['first'],$_POST['second']);
}
if(isset($_POST['sub']))
{
sub($_POST['first'],$_POST['second']);
}
?>
<form method="post">
Enter first number: <input type="number" name="first"/><br><br>
Enter second number: <input type="number" name="second"/><br><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
</form>
Output:
36
We passed the following numbers,
37
PHP Call By Value
PHP allows you to call function by value and reference both. In case of PHP call
by value, actual value is not modified if it is modified inside the function.
Example 2
Let's understand PHP call by value concept through another example.
<?php
function increment($i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output:
10
38
PHP Call By Reference
In case of PHP call by reference, actual value is modified if it is modified inside
the function. In such case, you need to use & (ampersand) symbol with formal
arguments. The & represents reference of the variable.
Let's understand the concept of call by reference by the help of examples.
Example 1
Example 2
Let's understand PHP call by reference concept through another example.
<?php
function increment(&$i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output:
11
39
Example 1
<?php
function sayHello($name="Ram")
{
echo "Hello $name<br/>";
}
sayHello("Sachin");
sayHello();//passing no value
sayHello("Vimal");
?>
Output:
Hello Sachin
Hello Ram
Hello Vimal
Since PHP 5, you can use the concept of default argument value with call
by reference also.
Example 2
<?php
function greeting($first="Sachin",$last="Tendulkar")
{
echo "Greeting: $first $last<br/>";
}
greeting();
greeting("Rahul");
greeting("Michael","Clark");
?>
Output:
Greeting: Sachin Tendulkar
Greeting: Rahul Tendulkar
Greeting: Michael Clark
Example 3
<?php
function add($n1=10,$n2=10)
{
$n3=$n1+$n2;
echo "Addition is: $n3<br/>";
40
}
add();
add(20);
add(40,40);
?>
Output:
Addition is: 20
Addition is: 30
Addition is: 80
PHP supports variable length argument function. It means you can pass 0, 1 or
n number of arguments in function. To do so, you need to use 3 ellipses (dots)
before the argument name.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
Let's see a simple example of PHP variable length argument function.
<?php
function add(...$numbers)
{
$sum = 0;
foreach ($numbers as $n)
{
$sum += $n;
}
return $sum;
}
echo add(1, 2, 3, 4);
?>
Output:
10
PHP also supports recursive function call like C/C++. In such case, we call
current function within function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level
because it may smash the stack and may cause the termination of script.
41
Example 1: Printing number
<?php
function display($number)
{
if($number<=5)
{
echo "$number <br/>";
display($number+1);
}
}
display(1);
?>
Output:
1
2
3
4
5
Output:
120
42
Reading data from web form controls
We can create and use forms in PHP. To get form data, we need to use PHP
super globals $_GET and $_POST.
The form request may be get or post. To retrieve data from get request, we need
to use $_GET, for post request $_POST.
Get request is the default form request. The data passed through get request is
visible on the URL browser so it is not secured. You can send limited amount of
data through get request.
Let's see a simple example to receive data from get request in PHP.
File: form1.html
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>
The data passed through post request is not visible on the URL browser so it is
secured.
You can send large amount of data through post request.
Let's see a simple example to receive data from post request in PHP.
File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/>
</td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
43
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in
$password variable
echo "Welcome: $name, your password is: $password";
?>
Output:
PHP allows you to include file so that a page content can be reused many
times. There are two ways to include file in PHP.
include
require
Advantage
Code Reusability: By the help of include and require construct, we can reuse
HTML code or PHP script in many PHP scripts.
44
PHP include example
PHP include is used to include file on the basis of given path. You may use
relative or absolute path of the file. Let's see a simple PHP include example.
File: menu.html
<a href="http://www.google.com">Home</a> |
<a href="http://www.ncmkit.com/php-tutorial">PHP</a> |
<a href="http://www.ncmkit.com/java-tutorial">Java</a> |
<a href="http://www.ncmkit.com/html-tutorial">HTML</a>
File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>
Output:
File: menu.html
<a href="http://www.vivekit.com">Home</a> |
<a href="http://www.vivekit.com/php-tutorial">PHP</a> |
<a href="http://www.vivekit.com/java-tutorial">Java</a> |
<a href="http://www.vivekit.com/html-tutorial">HTML</a>
File: require1.php
<?php require("menu.html"); ?>
<h1>This is Main Page</h1>
Output:
45
1.Handling Text Fields
tfdemo.html
<html>
<body>
<form method="post" action="tfdemo.php">
enter your name:<input type="text" name="t1"><br>
enter your marks:<input type="text" name="t2"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
tfdemo.php
<html>
<body>
<?php
echo"sum is ".$c;
?>
</body>
</html>
Output:
46
2. Handling Text Areas
Text fields are fine if you only want a single line of text, but if you want
multiline text input, you have to go with text areas.
tademo.html
<html>
<body>
<form method="post" action="tademo.php">
enter your Suggestions:<textarea name="ta1" rows="6" cols="6">enter some
text here</textarea>
<input type="submit" value="submit">
</form>
</body>
</html>
tademo.php
<html>
<body>
<?php
echo "ëntered data is".$_REQUEST["ta1"];
?>
</body>
</html>
Output:
47
3. Handling Check Boxes:
cbdemo.html
<html>
<body>
<form action="cbdemo.php" method="post">
select course/s<br>
<input type="checkbox" name="c[]" value="C/C++"><label>C/C++</label><br/>
<input type="checkbox" name="c[]" value="Java"><label>Java</label><br/>
<input type="checkbox" name="c[]" value="PHP"><label>PHP</label><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
cbdemo.php
<?php
echo"selected course/s </br>";
foreach($_REQUEST['c'] as $value)
{
echo $value."</br>";
}
?>
Output:
48
Connecting to database (MySQL as reference)
1) HostName: The DB and PHP may (or) may not exist on the same
system. If they exist then the term localhost is used for the host name. If
not PHP must be provided with the address of the DB which might be a
domain name or an IP address.
Connection steps:
mysql_select_db(“database name”);
ex: mysql_select_db(“cse”);
3.Execute a query
mysql_query(“Query name”);
mysql_close(connection name);
ex:mysql_close($conn);
49
Handling results
PHP mysql_fetch_array() function retrieves only one row of data and the
row is stored in an array. In order to retrieve multiple rows of data use
while loop. The syntax to retrieve all the rows of data from a table in the
database is as follows.
Syntax:
while($row=mysql_fetch_array($result))
{
//statement(s);
}
Example:
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("tpo") or die(mysql_error());
50
Handling File Uploads
PHP allows you to upload single and multiple files through few lines of code
only.
PHP file upload features allows you to upload binary and text files both.
Moreover, you can have the full control over the file to be uploaded through
PHP authentication and file operation functions.
PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of
$_FILES global, we can get file name, file type, file size, temp file name and
errors associated with file.
returns temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
returns error code associated with this file.
move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location.
The move_uploaded_file() function checks internally if the file is uploaded
thorough the POST request. It moves the file if it is uploaded through the POST
request.
Syntax
bool move_uploaded_file ( string $filename , string $destination )
51
Example:
fileupload.html
<html>
<body>
<form action="fileupload.php" method="post"
enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"> <br>
<input type="submit" value="Upload Image">
</form>
</body>
</html>
fileupload.php
<?php
$target_path = "d:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path))
{
echo "File uploaded successfully!";
}
else
{
echo "Sorry, file not uploaded, please try again!";
}
?>
Syntax:
setcookie(name, value, expire, path, domain, secure)
Here
Name is Name of the cookie(it’s mandatory) and
Value is the value of the cookie.
Expire: It is optional, it can be used to set the expire time for the cookie. The
time is set using the PHP time function i.e., time+3600 for 1 hour.
52
Path: It is optional, it can be used to set the cookie path on the server.The
forward slash(/)means that the cookie will be made available on the entire
domain.
Domain: It is optional, it can be used to define the cookie hierarchy
i.e.,www.abc.com means it is available to entire domain.
Secure: It is optional, this can be set to one(1) to specify that the cookie should
only be sent by secure transmission using https otherwise set to zero(0) which
means cookie can be sent by general http.
Accessing cookies:
$_COOKIE[ ] function is used to access a cookie.
<?php
setcookie("name", "abc", time()+3600, "/","", 0);
setcookie("age", "20", time()+3600, "/", "", 0);
?>
<?php
echo $_COOKIE["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
?>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the
past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
53