0% found this document useful (0 votes)
19 views53 pages

PHP Unit-I

php unit 1 r18

Uploaded by

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

PHP Unit-I

php unit 1 r18

Uploaded by

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

UNIT - I

Introduction to PHP: Declaring variables, data types, arrays, strings, operators,


expressions, control structures, functions, Reading data from web form controls
like text boxes, radio buttons, lists etc., Handling File Uploads, Connecting to
database (MySQL as reference),executing simple queries, handling results,
Handling sessions and cookies.
File Handling in PHP: File operations like opening, closing, reading, writing,
appending, deleting etc. on text and binary files, listing directories

Introduction

PHP (Hypertext Preprocessor) is an open source, interpreted and object-oriented


scripting language i.e. executed at server side. It is used to develop web
applications (an application i.e. executed at server side and generates dynamic
page). It was developed by Rasmus Lerdorf in 1994.

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:

WAMP for Windows

LAMP for Linux

MAMP for Mac

SAMP for Solaris

FAMP for FreeBSD

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

A variable in PHP is a name of memory location that holds data. A variable is a


temporary storage that is used to store data temporarily.

In PHP, a variable is declared using $ sign followed by variable name. Syntax of


declaring a variable in PHP is given below:

$variablename=value;

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable

 A variable name must starts with a letter or the underscore symbol

 Variable names consist of letters ,digits and underscore symbol (A-z, 0-9,
and _ )

 White spaces are not allowed

 These can be of any length.

 Variable names are case-sensitive ($vaag and $VAAG are two different
variables)

Ex: $abc $_xyz $lmn12

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.

The syntax of PHP echo is given below:

void echo ( string $arg1 [, string $... ] )

PHP echo statement can be used to print string, multi line strings, escaping
characters, variable, array etc.

PHP echo: printing string

File: echo1.php

<?php

echo "Hello by PHP echo";

?>

Output: Hello by PHP echo

2
PHP echo: printing multi line string

File: echo2.php

<?php

echo "Hello by PHP echo

this is multi line

text printed by

PHP echo statement ";

?>

Output:

Hello by PHP echo this is multi line text printed by PHP echo statement

PHP echo: printing escaping characters

File: echo3.php

<?php

echo "Hello escape \"sequence\" characters";

?>

Output:

Hello escape "sequence" characters


PHP echo: printing variable value

PHP Operators

An Operator is a symbol that specifies an operation to be performed on the


operands.

Types of operators.

1. Arithmetic operators.

2. Assignment Operators

3. Incement and decrement Operators

4. Comparison operators

5. Conditional operators

6. Logical Operators.

3
7. Bitwise Operators.

8. String Operators.

1. Arithmetic operators.

These are used to perform basic arithmetic operations

There are five basic arithmetic operators.

+ (addition), - (subtraction), * (multiplication), / (division), % (modulus)

The operators are summarized in the following table.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y.

- Subtraction $x - $y Difference of $x and $y.

* Multiplication $x * $y Product of $x and $y.

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y.

Example:

<?php

$x=100;

$y=60;

echo "The sum of x and y is : ". ($x+$y) ."<br />";

echo "The difference between x and y is : ". ($x-$y) ."<br />";

echo "Multiplication of x and y : ". ($x*$y) ."<br />";

echo "Division of x and y : ". ($x/$y) ."<br />";

echo "Modulus of x and y : " . ($x%$y) ."<br />";

?>

Output:

The sum of x and y is : 160

The difference between x and y is : 40

Multiplication of x and y : 6000

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.

Shorthand Expression Description

$a+= $b $a = $a + $b Adds 2 numbers and assigns the result to the first.

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

$a%= $b $a = $a%$b Computes the modulus of 2 numbers and assigns the


result to the first.
Example:
<?php
$x1=100;
$x2=200;
$x3=300;
$x4=400;
$x5=500;
$x1+= 100;
echo " $x1 <br />";
$x2-= 200;
echo " $x2 <br />";
$x3*= 300;
echo " $x3 <br />";
$x4/= 400;
echo " $x4 <br />";
$x5%= 500;
echo " $x5 <br />";
$x=($y=11)+9;
echo " Value of x & y is : $x $y <br />";
?>

5
Output:

200
0
90000
1
0
Value of x & y is : 20 11

3. Incement and decrement Operators

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

In PHP, comparison operators take simple values (numbers or strings) as


arguments and evaluate to either TRUE or FALSE.

Here is a list of comparison operators.

Operator Name Example Result

== Equal $x == $y TRUE if $x is exactly equal to $y

TRUE if $x is exactly equal to $y,


=== Identical $x === $y
and they are of the same type.

TRUE if $x is exactly not equal to


!= Not equal $x != $y
$y.

TRUE if $x is exactly not equal to


<> Not equal $x <> $y
$y.

TRUE if $x is not equal to $y, or


!== Not identical $x !== $y
they are not of the same type.

TRUE if $x (left-hand argument)


< Less than $x < $y is strictly less than $y (right-
hand argument).

TRUE if $x (left hand argument)


> Greater than $x > $y is strictly greater than $y (right
hand argument).

TRUE if $x (left hand argument)


<= Less than or equal to $x <= $y is less than or equal to $y (right
hand argument).

TRUE if $x is greater than or


>= Greater than or equal to $x >= $y
equal to $y.

7
Example for identical

<?php

$x = 300;

$y = "300";

var_dump($x === $y);

?>

Output:

bool(false)

Example for not identical

<?php

$x = 150;

$y = "150";

var_dump($x !== $y);

?>

Output:

bool(true)

5. Conditional operators

? and : are PHP conditional operators

Operator Name Example Result

Returns the value of $x.


The value of $x is expr2 if expr1 =
$x = expr1 ?
?: Ternary TRUE.
expr2 : expr3
The value of $x is expr3 if expr1 =
FALSE

Example:

<?php
$a = 10;
$b = 20;

/* If condition is true then assign a to result otheriwse b */


$result = ($a > $b ) ? $a :$b;

echo "TEST1 : Value of result is $result<br/>";


8
/* If condition is true then assign a to result otheriwse b */
$result = ($a < $b ) ? $a :$b;

echo "TEST2 : Value of result is $result<br/>";


?>
Output:
TEST1 : Value of result is 20
TEST2 : Value of result is 10

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.

Here is the list of logical operators:

Operator Name Example Result

&& and $x && $y is true if both $x and $y are true.

|| or $x || $y is true if either $x or $y is true.

xor xor $x xor $y is true if either $x or $y are true, but not both.

! not !$x is true if $x is not true.

and and $x and $y is true if both $x and $y are true.

or or $x or $y is true if either $x or $y is true.

Example:

<?php

$a = true && false;

var_dump($a);

$b = false && true;

var_dump($b);

$c = true && true;

var_dump($c);

$d = false && false;

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.

Operator Name Example Result

& And $x & $y Bits that are set in both $x and $y are set.

| Or $x | $y Bits that are set in either $x or $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.*

# Each step means 'multiply by two'

* Each step means 'divide by two'

10
8. String Operators.

There are two string operators : concatenation operator ('.') and concatenating
assignment operator ('.=').

Example : PHP string concatenation operator

<?php

$x = "Good";

$y = $x ." Morning";

// now $y contains "Good Morning "

echo $y;

?>

Output:

Good Morning

Example: PHP string concatenating assignment operator

<?php

$x = "Good";

$x.= " Morning";

echo $x;

?>

Output

Good Morning favorite

PHP Control statements

A control statement controls the flow of execution of a program.PHP control


statements are.
1.conditional control statements (if &switch)
2.Iterative or Loop statements(while, do-while, for & for-each)
if: It is a conditional executable statement.
It has four forms
1.simple if

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.

Iterative statements are while, do-while, for and foreach

15
While:
The while statement will be executed repeatedly as long as the expression remains
true.

Syntax:

while(test-condition)
{
//body of the loop
}

The while statement is an entry controlled statement. The test condition is


evaluated if the condition is true, then the body of the loop is executed. After
execution of the body, the test-condition is once again evaluated and if it is true,
the body is executed once again. This process of repeated execution of the body
continues until the test condition finally becomes false and the control is
transferred out of the loop. On exit, the program continues with the statements
immediately after the body of the loop.
Example:
<?php
$n=1;
while($n<=5)
{
echo $n;
$n=$n+1;
}
?>
Output: 1 2 3 4 5

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

The execution of for statement is as follows:

1. Initialization of control variable is done first using assignment statement.

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:

Advantage of PHP Array


Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an
array.
Sorting: We can sort the elements of array.

There are 3 types of array in PHP.


1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number,
string and object in the PHP array. All PHP array elements are assigned to an
index number by default.
There are two ways to define indexed array:
1st way:
1. $season=array("summer","winter","spring","autumn");

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

Count Length of PHP Indexed Array


PHP provides count() function which returns length of an array.

<?php
$size=array("Big","Medium","Short");
echo count($size);
?>

Output:
3

PHP Associative Array

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

Traversing PHP Associative Array


By the help of PHP for each loop, we can easily traverse the elements of PHP
associative array.
<?php
$salary=array("Sachin"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
foreach($salary as $k => $v)
{
echo "Key: ".$k." Value: ".$v."<br/>";
}
?>
Output:
Key: Sachin Value: 550000
Key: Vimal Value: 250000
Key: Ratan Value: 200000

21
PHP Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to


store tabular data in an array. PHP multidimensional array can be represented in
the form of matrix which is represented by row * column.
Definition
$emp = array(
array(1,"sachin",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display following
tabular data. In this example, we are displaying 3 rows and 3 columns.

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

for ($row = 0; $row < 3; $row++)


{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";

22
}
echo "<br/>";
}
?>

Output:
1 sachin 400000
2 john 500000
3 rahul 300000

PHP Array Functions


PHP provides various array functions to access and manipulate the elements of
array.
The important PHP array functions are given below.

1) PHP array() function


PHP array() function creates and returns an array. It allows you to create indexed,
associative and multidimensional arrays.

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

2) PHP array_change_key_case() function


PHP array_change_key_case() function changes the case of all key of an array.
Note: It changes case of key only.

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 )

3) PHP array_chunk() function


PHP array_chunk() function splits array into chunks. By using array_chunk()
method, you can divide array into many parts.

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

5) PHP sort() function

PHP sort() function sorts all the elements in an array.


Syntax
1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

24
Example
<?php
$season=array("summer","winter","spring","autumn");
sort($season);
foreach( $season as $s )
{
echo "$s<br />";
}
?>

Output:
autumn
spring
summer
winter

6) PHP array_reverse() function


PHP array_reverse() function returns an array containing elements in reversed
order.
Syntax
1. array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>

Output:
autumn spring winter summer

7) PHP array_search() function

PHP array_search() function searches the specified value in an array. It returns


key if search is successful.

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

8) PHP array_intersect() function


PHP array_intersect() function returns the intersection of two array. In other
words, it returns the matching elements of two array.
Syntax
1. array array_intersect ( array $array1 , array $array2 [, array $... ] )
Example

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

Double Quoted PHP String


In PHP, we can specify string through enclosing text within double quote also. But
escape sequences and variables will be interpreted using double quote PHP
strings.
<?php
$str="Hello text within double quote";
echo $str;
?>

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

In double quoted strings, variable will be interpreted.


<?php
$num1=10;
echo "Number is: $num1";
?>

Output: Number is: 10


PHP String Functions

PHP provides various string functions to access and manipulate strings. A list of
important PHP string functions are given below.

1) PHP strtolower() function

The strtolower() function returns string in lowercase letter.


Syntax
1. string strtolower ( string $string )

28
Example

<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>

Output:
my name is khan

2) PHP strtoupper() function


The strtoupper() function returns string in uppercase letter.

Syntax
1. string strtoupper ( string $string )

Example
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>

Output:
MY NAME IS KHAN

3) PHP ucfirst() function


The ucfirst() function returns string converting first character into uppercase. It
doesn't change the case of other characters.

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

5) PHP ucwords() function


The ucwords() function returns string converting first character of each word into
uppercase.

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

6) PHP strrev() function


The strrev() function returns reversed string.

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

7) PHP strlen() function


The strlen() function returns length of the string.
Syntax
1. int strlen ( string $string )

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.

In PHP, we can define Conditional function, Function within Function and


Recursive function also.

Advantage of PHP Functions

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.

Easy to understand: PHP functions separate the programming logic. So it is


easier to understand the flow of the application because every logic is divided in
the form of functions.

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.

PHP Functions Example

File: function1.php

<?php
function sayHello()
{
echo "Hello PHP Function";
}
sayHello();//calling function
?>

Output:
Hello PHP Function

PHP Function Arguments


We can pass the information in PHP function through arguments which is
separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument
values and Variable-length argument list.

Let's see the example to pass single argument in 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

PHP Call By Reference

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

PHP Function: Default Argument Value

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: Returning Value


Let's see an example of PHP function that returns value.
File: functiondefaultarg.php

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

Addition and Subtraction


In this example, we have passed two parameters $x and $y inside two functions
add() and sub().

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

Now clicking on ADDITION button, we get the following output.

Now clicking on SUBTRACTION button, we get the following output.

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.

Let's understand the concept of call by value by the help of examples.


Example 1
In this example, variable $str is passed to the adder function where it is
concatenated with 'Call By Value' string. But, printing $str variable results
'Hello' only. It is because changes are done in the local variable $str2 only. It
doesn't reflect to $str variable.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}

$str = 'Hello ';


adder($str);
echo $str;
?>
Output:
Hello

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

In this example, variable $str is passed to the adder function where it is


concatenated with 'Call By Reference' string. Here, printing $str variable
results 'This is Call By Reference'. It is because changes are done in the actual
variable $str.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Output:
This is Call By Reference

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

PHP Default Argument Values Function


PHP allows you to define C++ style default argument values. In such case, if
you don't pass any value to the function, it will use default argument value.
Let' see the simple example of using PHP default arguments in function.

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 Variable Length Argument Function

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 Recursive Function

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

Example 2 : Factorial Number


<?php
function factorial($n)
{
if ($n < 0)
return -1; /*Wrong value*/
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorial ($n -1));
}
echo factorial(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.

PHP Get Form

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

<form action="welcome.php" method="get">


Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>

File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>

PHP Post Form


Post request is widely used to submit form that have large amount of data such
as file upload, image upload, login form, registration form etc.

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 Include File

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:

Home | PHP | Java | HTML This is Main Page

PHP require example


PHP require is similar to include. Let's see a simple PHP require example.

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:

Home | PHP | Java | HTML This is Main Page

PHP include vs PHP require


If file is missing or inclusion fails, include allows the script to continue but
require halts the script producing a fatal E_COMPILE_ERROR level error.

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)

PHP can be used to interact with the database. To establish a connection


with a database the following information is needed.

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.

2)Username: A valid username must be provided to access the database.

3)Password: Along with the username a valid password must be given to


authenticate the DB.

4) Name of database: There can be multiple databases in an RDBMS


and hence the name of DB must be mentioned in order to access it.

Connection steps:

1. Establish a new connection

mysql_connect (“hostname”, “username”, “password”);

ex: mysql_connect (“localhost”, “root”, “root”);

2.select the Database.

mysql_select_db(“database name”);

ex: mysql_select_db(“cse”);

3.Execute a query

mysql_query(“Query name”);

ex: mysql_query(“create table stud(sno int(3),sanme varchar(20)”);

4.close the connection

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

// Get all the data from the "stud" table


$result = mysql_query("SELECT * FROM stud") or die(mysql_error());

echo "<table border='1'>";


echo "<tr> <th>Name</th> <th>smarks</th> </tr>";

while($row = mysql_fetch_array( $result ))


{
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['smarks'];
echo "</td></tr>";
}
echo "</table>";
?>

50
Handling File Uploads

PHP File Upload

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.

Here, we are assuming that file name is filename.


$_FILES['filename']['name']

returns file name.


$_FILES['filename']['type']

returns MIME type of the file.


$_FILES['filename']['size']

returns size of the file (in bytes).


$_FILES['filename']['tmp_name']

returns temporary file name of the file which was stored on the server.
$_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!";
}
?>

Handling sessions and cookies.


Cookies:
A cookie is a small file used to identify a particular user. A cookie is created
with the setcookie() function.

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.

Setting PHP cookies

<?php
setcookie("name", "abc", time()+3600, "/","", 0);
setcookie("age", "20", time()+3600, "/", "", 0);
?>

Reading PHP cookies

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

You might also like