Unit Iv-We
Unit Iv-We
4.1 Introduction
PHP was an short form for "Hypertext PreProcessor", And PHP was developed
by "Rasmus Lerdorf".
In 1995, he developed package called Pesonal Home Page tools which became the first
distributed version of PHP.
What is PHP
» PHP is an open source, interpreted, object-oriented and server-side scripting language. It is
used to create or develop server side web applications.
» PHP is an interpreted language, i.e. there is no need of compilation. And PHP is naturally
used for form handling and database access.
» Database access has been a prime focus for PHP development as a result, PHP has driver
support for many different database systems.
» PHP is a server-side, XHTML embedded scripting language as such, it is an alternative to
CGI (Common Gateway Interface), ASP (Active Server Pages) and JSP (Java Server Pages).
1
In the Clint-Server Model, the client sends a request to the server, then the server receives the
request and processes it along with database interactions (if required) and generates the
response in the client understandable format, and then the server sends that response to the
client.
In the above Client-Server model, the web browser can be used as a client and it understands
simple stuff like HTML, JavaScript and CSS, Apache can be used as a server and it translates
PHP script into a browser understandable format and MySQL can be used as a database.
PHP Installation
To install PHP, We need to install AMP (Apache, MySQL, and PHP) software pack. It is
available for all operating systems and it is an open source.
To work with PHP, we must have a web server (Apache), database (MySQL) and PHP scripting
language.
AMP (Apache, MySQL, and PHP) software pack for different operating systems:
• WAMP for Windows
• LAMP for Linux
• MAMP for Mac
• SAMP for Solaris
• XAMPP for Cross Platform
XAMPP is a AMP software pack which stands for (X)Cross platform, Apache, MySQL, PHP,
Perl with some additional administrative tools such as PhpMyAdmin (for database access),
FileZilla FTP server, Mercury mail server and JSP Tomcat server.
PHP Program
This tutorial gives detailed information about how to create and execute a PHP program.
To create PHP program, we need basic knowledge of Hyper Text Markup Language (HTML)
to generate static content.
To create and execute a PHP Program,
2
Creation:
• Open any text editor (like notepad, edit plus ...).
• Write PHP script and Html tags in that text editor.
• Save this file with ".php" extension in the following location.
In Windows:
C: /xampp/htdocs
In Linux (Ubuntu):
/var/www/html
Execution:
• Open the XAMPP control panel and then start the Apache server.
• Open any web browser (Chrome, Firefox ,IE..) and type "localhost/filename.php" as
url in the address bar.
• Then we get an output of PHP programs.
The PHP file is the combination of HTML and PHP script, where HTML generates static
content and PHP generates dynamic content.
To insert or embed PHP script into html document, we use PHP tag.
echo statement :
The echo statement is used to print something on screen just like print function C language.
Example:
echo "Hello Welcome !";
echo "Hello ".10*3;
Output:
Hello Welcome !
Hello 30
3
Example: "First.php"
<html>
<head>
<title>First PHP Example</title>
</head>
<body>
<?php
echo "This is My First PHP Example";
?>
</body>
</html>
Output :
Comments in PHP
In general, Comments are used in a programming language to describe the program or to hide
the some part of code from the interpreter.
Comments in PHP can be used to explain any program code. It can also be used to hide the
code as well.
Comment is not a part of the program, but it enhances the interactivity of the program and
makes the program readable.
PHP supports two types of comments:
• Single Line Comment
• Multi Line Comment
1. Single Line Comment:
In case the developer wants to specify a single line comment, then the comment must start
with " // "
format:
4
2. Multi Line Comment
In case of Multi lined comment, the comment must starts with /* and ends with */ i.e. /* .... */ .
format:
/* This
Is
Multiline comment */
Example: "commentdemo.php"
<html>
<head>
<title>Comments in PHP</title>
</head>
<body>
<h1>Comments in PHP</h1>
<?php
// echo prints something on screen
echo "This is My First PHP Example <br/>";
Output :
5
4.3 PHP Variables
A variable is a named memory location in which we can store values for the particular
program.In other words, Variable is a name of memory location and used to hold the value.
Creating Variables
In PHP, a variable is created using $ symbol followed by variable name.
format:
$variablename = value;
Example:
• In PHP, The variable names are case - sensitive, so the variable name $a is different
from $A, i.e. $a != $A
Example:
• $a = "Study";
$A = "Glance";
In PHP, We don't need to declare explicitly variable, when we assign any value to the
variable that variable is declared automatically.
In PHP, We don't need to specify the type of variable because PHP is a loosely typed
language. I.e. In loosely typed language no need to specify the type of variable because the
variable automatically changes it's datatype based on the assigned value.
6
Example:
$str = "Study Glance"; //string type variable
$x = 250; //integer type variable
$y = 14.6; //float type variable
Example: "VarDemo.php"
<html>
<head>
<title>Variables Demo</title>
</head>
<body bgcolor="#fff">
<h1>Variable Demonstration</h1>
<?php
$str = "Study Glance";
$x = 112;
$y = 45.12;
echo "String is : $str<br/>";
echo "Integer is : $x <br/>";
echo "Float is : $y <br/>";
?>
</body>
</html>
Output :
7
Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
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
Create a constant with a case-sensitive name:
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Example
Create a constant with a case-insensitive name:
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
function myTest() {
echo GREETING;
}
myTest();
?>
8
4.5 Datatypes in PHP
Generally, the datatypes are used to hold different types of data (or) values. Datatypes specifies
the different types of data that are supported in PHP.
PHP supports total eight primitive datatypes :
• Integer
• Float
• String
• Boolean
• Array
• Object
• NULL
• Resource
PHP supports eight primitive data types which are categorized into 3 main types. They are:
• Scalar Types: boolean, integer, float and string.
• Compound Types: array and object.
• Special Types: resource and NULL.
Note :In PHP, var_dump() function returns the data type and value. Ex: int(123).
☞ Integer :
In PHP, Integers hold whole numbers including positive and negative numbers (... -3, -2, -1, 0,
1, 2, 3, ...). i.e., numbers without decimal point. They can be decimal (base 10), octal (0) or
hexadecimal (0x) optionally preceded by + or - sign.
Example: "intdemo.php"
<?php
$var1 = 521; // decimal number
echo "Decimal Number is : ".$var1."<br>";
var_dump($var1); // it prints datatype and value
echo "<br>";
9
Output :
☞ Float :
A float (floating point number) is a number with a decimal point. It hold numbers containing
fractional or decimal part including positive and negative numbers.
Example: "floatdemo.php"
<?php
$var1 = 23.45; // float
echo "Float Number is : ".$var1."<br>";
var_dump($var1); // it prints datatype and value
echo "<br>";
10
☞ String :
A string is a sequence of characters which are enclosed with single quotes or double quotes.
Example: "stringdemo.php"
<?php
$var1 = "Hello PHP"; // string
echo "String is : ".$var1."<br>";
var_dump($var1); // it prints datatype and value
echo "<br>";
$var2 = 'Study Glance'; // string
echo "String is : ".$var2."<br>";
var_dump($var2);
echo "<br>";
?>
Output :
☞ Boolean :
A boolean datatype hold two possible values either TRUE or FALSE.
Example: "blndemo.php"
<?php
$a= TRUE; // boolean
echo "Status is : ".$a."<br>";
var_dump($a); // it prints datatype and value
echo "<br>";
11
Output :
☞ Array :
An array datatype can hold more than one value at a time.In other words, An array is collection
of elements or items.
Example: "arydemo.php"
<?php
$numbers = array(1,2,3,4,5); //array
var_dump($numbers); // prints datatype and value
echo "<br>";
?>
Output :
☞ Object :
In PHP, Object is an instance of user defined class that can store both values and
functions.Objects are created based on user defined class via the new keyword
Example: "objdemo.php"
<?php
class msg {
function display() {
$str = "Hello ! Welcome ";
echo $str;
}
}
12
$obj = new msg();
$obj -> display();
echo "<br>";
var_dump($obj);
?>
Output :
☞ Null :
In PHP, Null is a special data type that has only one value: NULL, And it is case sensitive you
must write in capital letters.The special type of data type NULL defined a variable with no
value.
Example: "nulldemo.php"
<?php
$var = NULL;
echo $var; //it will not give any output
?>
Output :
☞ Resource :
In PHP, A resource is a special variable, that hold a reference to an external resource such as
database connection and opened files.The Resources are not exact data type in PHP
Example: "resdemo.php"
<?php
// Open a file for reading
$fp = fopen("file.txt", "r");
var_dump($fp);
13
echo "<br>";
echo $fp;
?>
Output :
An operator can be defined as a symbol which is used to perform a particular operation between
operands.
/ (divide) Divide left operand by the right one (always results into float)
14
Operator Description
= (Assigns to) Assigns values from right side operands to left side
operand.
+= (Assignment after It adds right operand to the left operand and assign the
Addition) result to left operand.
-= (Assignment after It subtracts right operand from the left operand and
Subtraction) assign the result to left operand.
*= (Assignment after It multiplies right operand with the left operand and
Multiplication) assign the result to left operand.
/= (Assignment after It divides left operand with the right operand and assign
Division) the result to left operand.
%= (Assignment after It takes modulus using two operands and assign the
Modulus) result to left operand.
!= (Not equal to) Not equal to - True if operands are not equal.
<= (Less than or Less than or equal to - True if left operand is less than or
equal) equal to the right
>= (Greater than or Greater than or equal to - True if left operand is greater than
equal) or equal to the right
< (Less than) Less than - True if left operand is less than the right
> (Greater than) Greater than - True if left operand is greater than the right
=== (Indentical) Indentical - True if both operands have same value and
datatype.
!== (Not Indentical) Not Indentical - True if both operands doesn't have same
value and datatype..
☞ Increment/Decrement operators
Increment/Decrement operators are used to increment or decrement the value of the operand.
15
Operator Description
and (or) && (logical and) Returns True if both statements are true
not (or) ! (logical not) Reverse the result, returns False if the result is true
☞ String operators
String operators are used to concatenate two strings.
Operator Description
!= (Not equal to) Not equal to - True if operands(arrays) are not equal.
=== (Indentical) Indentical - True if both operands(arrays) have same value and
datatype.
!== (Not Not Indentical - True if both operands(aarays) doesn't have same
Indentical) value and datatype..
Example: "OperatorDemo.php"
<html>
<head>
<title>Operators Demo</title>
</head>
<body>
<?php
$a=10;
16
$b=5;
//Arithmetic operators
$c=$a+$b;
echo "Addition is :$c <br/>";
$c=$a-$b;
echo "Subtraction is :$c <br/>";
//Increment/Decrement Operators
$c=$a++;
echo "Increment is :$c <br/>";
$c=$a--;
echo "Decrement is :$c <br/>";
//Assignment Operators
$c+=$a;
echo " Add Assignment is :$c <br/>";
$c-=$a;
echo "Sub Assignment is :$c <br/>";
//Comparison operators
echo "$a > $b is : ".($a>$b)."<br/>";
echo "$a < $b is : ".($a<$b)."<br/>";
//String operators
$str1="Study";
$str2="Glance";
$str3=$str1.$str2;
echo "Combined String : $str3 <br>";
//Logical Operators
echo "$a > $b and $a < $c is : ".($a>$b && $a<$c)."<br/>";
echo "$a > $b or $a < $b is : ".($a>$b || $a<$b)."<br/>";
?>
</body>
</html>
Output :
17
4.7 Flow Control and Looping
• Conditional Statements
• Loop Statements
• Jump Statements
Conditional Statements :
Conditional Statements performs different computations or actions depending on conditions.
In PHP, the following are conditional statements
• if statement
• if - else statement
• if - elseif - else statement
• switch statement
☞ if statement
The if statement is used to test a specific condition. If the condition is true, a block of code
(if-block) will be executed.
Syntax :
if (condition)
{
statements
}
☞ if - else statement
The if-else statement provides an else block combined with the if statement which is executed
in the false case of the condition.
Syntax :
if (condition)
{
statements
}
else
{
statements
}
18
Syntax :
if (condtion1)
{
statements
}
else if (condtion2)
{
statements
}
else if (condtion3)
{
statements
}
.
.
else
{
statements
}
Example: "ConditionalDemo.php"
<html>
<head>
<title>Conditional Demo</title>
</head>
<body>
<?php
$x=15;
$y=5;
if ($x > $y)
{
echo "$x is greater than $y";
}
else if ($x < $y)
{
echo "$x is lessthan $y";
}
else
{
echo "Both are Equal";
}
?>
</body>
</html>
19
Output :
☞ switch statement
The switch statement enables us to execute a block of code from multiple conditions
depending upon the expression.
Syntax :
switch (expression)
{
case 1: statements
break;
case 2: statements
break;
case 3: statements
break;
.
.
default: statements
}
Example: "SwitchDemo.php"
<html>
<head>
<title>Switch Demo</title>
</head>
<body>
<?php
$x=15;
$y=10;
$op='*';
switch($op)
{
case '+': $z = $x + $y;
echo "Addition is : $z";
break;
case '-': $z = $x - $y;
20
echo "Subtraction is : $z";
break;
case '*': $z = $x * $y;
echo "Multiplication is : $z";
break;
case '/': $z = $x / $y;
echo "Division is : $z";
break;
case '%': $z = $x % $y;
echo "Modulus is : $z";
break;
default: echo "Invalid Operator";
}
?>
</body>
</html>
Output :
Syntax :
while (condition)
{
statements
}
21
Example: "WhileDemo.php"
<html>
<head>
<title>While Demo</title>
</head>
<body>
<h1>While Demo</h1>
<?php
$n=1;
while($n<=5)
{
echo "$n <br/>";
$n++;
}
?>
</body>
</html>
Output :
Syntax :
do
{
statements
} while (condition);
Example: "DoWhileDemo.php"
<html>
<head>
<title>Do-While Demo</title>
22
</head>
<body>
<h1>Do-While Demo</h1>
<?php
$n=1;
do
{
echo "$n <br/>";
$n++;
} while($n<=5);
?>
</body>
</html>
Output :
Syntax :
for (initialization; condition; increment/decrement)
{
statements
}
Example: "ForDemo.php"
<html>
<head>
<title>For Demo</title>
</head>
<body>
<h1>For Demo</h1>
23
<?php
for($i=1;$i<=5;$i++)
{
echo "$i <br/>";
}
?>
</body>
</html>
Output :
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops. The break is commonly used in the cases
where we need to break the loop for a given condition.
Syntax :
break;
Example: "BreakDemo.php"
<html>
<head>
<title>Break Demo</title>
</head>
24
<body>
<h1>Break Demo</h1>
<?php
for($i=1;$i<=10;$i++)
{
if($i==5)
{
break; //terminates the current loop
}
echo "$i <br/>";
}
echo "Loop is Over !";
?>
</body>
</html>
Output :
☞ continue statement
The continue statement in php is used to bring the program control to the beginning of the
loop. i.e. when a continue statement is encountered inside the loop, remaining statements are
skipped and loop proceeds with the next iteration.
The continue statement skips the remaining lines of code inside the loop and start with the
next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.
Syntax :
continue;
Example: "ContinueDemo.php"
<html>
<head>
<title>Continue Demo</title>
</head>
<body>
25
<h1>Continue Demo</h1>
<?php
for($i=1;$i<=10;$i++)
{
if($i%2==0)
{
continue; //terminates the current Iteration and moves to Next
}
echo "$i <br/>";
}
echo "Loop is Over !";
?>
</body>
</html>
Output :
An array is a special variable, which can hold more than one value at a time. In other words,
an array can hold many values under single name, and we can access the values by referring to
an index .
In PHP, the array() function is used to create an array.
PHP supports three types of arrays, those are
• Indexed array
• Associative array
• Multi-dimensional array
☞ Indexed array :
In arrays, the elements are assigned to specific index to access those elements easily.In the
Indexed array, index is represented by number which is starts from '0'.
An Indexed array is array with collection of elements where index is represented by number.
26
There are two ways to define indexed array, those are
1st-way:
$marks = array(60, 72, 66);
2nd-way:
Example: "IndArray.php"
<html>
<head>
<title>Indexed Array</title>
</head>
<body>
<h1>Indexed Array Demo</h1>
<?php
$marks=array(60,78,87,67);
echo "Marks are : $marks[0],$marks[1],$marks[2] and $marks[3]";
?>
</body>
</html>
Output :
☞ Associative array :
The associative arrays are very similar to indexed arrays in terms of functionality but they are
different in terms of their index.
Associative array will have their index as string so that we can establish a strong association
between key and value. In PHP, we can associate name with each array element using "=>"
symbol.
There are two ways to define associative array, those are
27
1st-way:
$marks = array("C"=>60, "Java"=>72, "Php"=>66);
2nd-way:
$marks ["C"] = 60;
$marks ["Java"] = 72;
$marks ["Php"] = 66;
Example: "AssocArray.php"
<html>
<head>
<title>Associate Array</title>
</head>
<body>
<h1>Associate Array Demo</h1>
<?php
$marks=array("WT"=>56,"FLAT"=>67,"SE"=>65,"PPL"=>78);
echo "Marks of WT :".$marks["WT"]."<br/>";
echo "Marks of FLAT :".$marks["FLAT"]."<br/>";
echo "Marks of SE :".$marks["SE"]."<br/>";
echo "Marks of PPL :".$marks["PPL"]."<br/>";
?>
</body>
</html>
Output :
☞ Multidimensional array :
• The multidimensional array is also known as array of arrays. It allows you to store
tabular data in an array.
• Multidimensional array represents in the form of matrix(i.e. rows and columns).
28
The following way is to define multidimensional array
$employees = array (
array (1,"A",28),
array (2,"B",27),
array (3,"C",29)
);
Example: "MultiArray.php"
<html>
<head>
<title>Multi-Dimensional Array</title>
</head>
<body>
<h1>Multi-Dimensional Array Demo</h1>
<?php
$students=array(
array(501,"Kiran",20),
array(502,"Hari",21),
array(503,"Naveen",20)
);
for($i=0;$i<3;$i++)
{
for($j=0;$j<3;$j++)
{
echo $students[$i][$j]." ";
}
echo "<br/>";
}
?>
</body>
</html>
Output :
29
4.9 Strings in PHP
In PHP, A String is a sequence of characters which are enclosed with single quotes or double
quotes.
There are 2 ways to specify string
• Single Quotes Ex: $str=' Hello PHP ';
• Double Quotes Ex: $str=" Hello PHP ";
Where in Single quoted string, we can store multiline text, special characters and escape
sequences.Where in Double quoted string, we can't use special characters directly.
Output:
Your age is : 20
Your age is : '20'
Output:
Your age is : $age
Your age is : '$age'
☞ String Function in PHP
PHP provides various string functions to perform different operations on strings i.e. to access
and manipulate strings. Those are,
☞ strtolower() :
It returns string in lowercase letters i.e. it converts given string into lowercase.
Example:
$str="StudyGLANCE";
$str1=strtolower($str);
echo $str1;
30
Output:
studyglance
☞ strtoupper() :
It returns string in uppercase letters i.e. it converts given string into uppercase.
Example:
$str="StudyGLANCE";
$str1=strtoupper($str);
echo $str1;
Output:
STUDYGLANCE
☞ ucwords() :
It converts first character of each word in given string into uppercase.
Example:
$str="study glance";
$str1=ucwords($str);
echo $str1;
Output:
Study Glance
☞ strlen() :
It returns the length of given string.
Example:
$str="study glance";
$len=strlen($str);
echo "Length of given string : $len";
Output:
Length of given string : 12
☞ strrev() :
It returns the given string in reverse.
Example:
$str="study glance";
$str1=strrev($str);
echo $str1;
Output:
31
ecnalg yduts
☞ str_word_count() :
It returns the number of words in the given string.
Example:
$str="study glance";
$wc=str_word_count($str);
echo $wc;
Output:
2
☞ strpos() :
It searchs for a specific text within a string. If a match is found, this function returns the
character position of the first match. If no match is found, it will return false.
Example:
$str="study glance";
$pos=strpos($str,"glance");
echo $pos;
Output:
6
☞ str_replace() :
It replaces some characters with another characters in the given string.
Example:
$str="study glance";
$str1=str_replace("glance","world",$str);
echo $str1;
Output:
study world
☞ substr() :
It returns the sub-string from the given string.
Example:
$str="study glance";
$str1=substr($str,6);
$str2=substr($str,0,4);
echo $str1;
echo $str2;
32
Output:
glance
study
Example: "Strfundemo.php"
<html>
<head>
<title>String Functions</title>
</head>
<body>
<h1>String Functions Demo</h1>
<?php
$str="I am study GLANCE";
echo "<strong>String in Lower case : </strong>".strtolower($str)."<br/>";
echo "<strong>String in Upper case :</strong> ".strtoupper($str)."<br/>";
echo "<strong>String in Word case :</strong> ".ucwords($str)."<br/>";
echo "<strong>Length of the String :</strong> ".strlen($str)."<br/>";
echo "<strong>String reverse :</strong> ".strrev($str)."<br/>";
echo "<strong>No of Words in String :</strong> ".str_word_count($str)."<br/>";
echo "<strong>Position of Sub-string :</strong> ".strpos($str,"am")."<br/>";
echo "<strong>String replace :</strong> ".str_replace("GLANCE","World",$str)."<br/>";
echo "<strong>Sub-string from given String :</strong> ".substr($str,5,5)."<br/>";
?>
</body>
</html>
Output :
33
4.10 Functions in PHP
• A function is a piece of code or self contained block of code that is used to perform a
particular task.
• The main advantage of functions is that code reusability (Write once Invoke multiple).
• PHP supports both built-in and user-defined functions. And PHP supports thousands of
built-in functions and allows us to define own functions, by using "function" keyword.
Syntax:
function fun_name ()
{
//code
}
Simple Function
A simple function is a function without any arguments or parameters.
Example: "FunSimple.php"
<html>
<head>
<title>Function Example</title>
</head>
<body>
<h1>Simple Function Example</h1>
<?php
function simple() //Function Definition
{
echo "Welcome to php";
}
simple();//Function calling
?>
</body>
</html>
Output :
34
Parameterized Functions
• A Parameterized functions are functions with parameters.i.e. These functions allow us
to pass one or more parameters inside the function.
• We can pass the information in function through arguments (or) parameters which are
separated by comma (,).
• These passed arguments (or) parameters acts as variables inside the function.
Example: "FunParam.php"
<html>
<head>
<title>Function Example</title>
</head>
<body>
<h1>Parameterized Function Example</h1>
<?php
function add($a,$b) //function defn
{
$sum = $a + $b;
echo "Sum is :$sum <br/>";
}
add(23,34);//calling function
35
Example: "FunCallByValue.php"
<html>
<head>
<title>Call by Value</title>
</head>
<body>
<h1>Call by Value Demo</h1>
<?php
//Example1
echo "Example1 : ";
function adder($str)
{
$str .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
echo "<br/>";
//Example2
echo "Example2 : ";
function increment($i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
</body>
</html>
Output :
☞ Call by Reference:
In case of call by reference, the actual value is modified if it is modified inside the function.
In this case, we need to use & (ampersand) symbol with formal arguments or parameters.
And & (ampersand) symbol represents reference of a variable.
36
Example: "FunCallByReference.php"
<html>
<head>
<title>Call by Reference</title>
</head>
<body>
<h1>Call by Reference Demo</h1>
<?php
//Example1
echo "Example1 : ";
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
echo "<br/>";
//Example2
echo "Example2 : ";
function increment(&$i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
</body>
</html>
Output :
37
Example1: "FunDefaultParam.php"
<html>
<head>
<title>Default Argument Function</title>
</head>
<body>
<h1>Default Argument Function Demo</h1>
<?php
function msg($name="Study") //Function Definition
{
echo "Welcome to $name <br/>";
}
msg(); //Function calling without parameter
msg("Glance"); //Function calling with parameter
?>
</body>
</html>
Output :
Example2: "FunDefaultParamd.php"
<html>
<head>
<title>Default Argument Function</title>
</head>
<body>
<h1>Default Argument Function Demo</h1>
<?php
function add($a=10, $b=10) //Function Definition
{
$sum = $a + $b;
echo "Addition is : $sum <br/>";
}
add(); //Function calling with no parameter
add(20); //Function calling with 1 parameter
add(20,40); //Function calling with 2 parameter
?>
</body>
38
</html>
Output :
Recursive function
PHP allow us to use recursive function. In this case, we call the current function within the
same function. It is also known as recursion.
Example: "FunRecursive.php"
<html>
<head>
<title>Recursive Function Example</title>
</head>
<body>
<h1>Recursive Function Demo</h1>
<?php
function factorial($n)
{
if($n < 0)
return -1;
if($n == 0)
return 1;
return($n * factorial($n - 1));
}
echo factorial(5);
?>
</body>
</html>
Output :
39
4.11 Form Handing in PHP
In PHP, We can create and use forms to get data from a Form. To read or get data from a form,
we need to use SuperGlobal Variables. A Superglobal variable is a built in PHP variable that
is available in any scope.
In simple words, the form request generated through may be get or post method. To retrieve
data from get request, we need to use $_GET, To retrieve data from post request, we need to
use $_POST.
Now, we going to learn about Get and Post forms with suitable examples.
Get Form :
Get form is a form which is generated through get request. The get request is the default form
request. The data passed through get request is visible on the URL so it is not secured. And we
can able send limited amount of data through get request.
Here, I am attaching an example to work with get request form, which consists two programs
one is HTML file(GetForm.html) to create an user interface and second one is PHP
file(getform.php) to read data from HTML input elements.
Example:
GetForm.html
<!doctype html>
<html lang="en">
<title>Get Form</title>
</head>
<body><br>
<form action="getform.php" method="get">
Name:<input type="text" name="uname"></input><br/><br/>
Age:<input type="number" name="age"></input><br/><br/>
<input type="submit" value="Click Me"></input>
</form>
</body>
</html>
40
Output:
When the user clicks on the "Click Me" button the following PHP script file gets executed. The
PHP script reads the data from HTML form elements using $_GET superglobal variable and
then displays on the screen.
getform.php
<!doctype html>
<html lang="en">
<title>Get Form</title>
</head>
<body><br>
<?php
// To read data from input elements using $_GET
$name = $_GET["uname"];
$age = $_GET["age"];
// To display data
echo "Welcome ".$name."<br/>";
echo "Your age is ".$age;
?>
</body>
</html>
Output:
Post Form :
Post form is a form which is generated through post request. The post request is not a default
form request. The data passed through post request is not visible on the URL so it is secured.
And it allows you send unlimited amount of data.
41
The Post request is widely used to submit form that have large amount of data such as file
upload and sensitive data such as login form, registration form etc.
Here, I am attaching an example to work with post request form, which consists two programs
one is HTML file(PostForm.html) to create an user interface and second one is PHP
file(postform.php) to read data from HTML input elements.
Example:
PostForm.html
<!doctype html>
<html lang="en">
<title>Post Form</title>
</head>
<body><br>
<form action="postform.php" method="post">
UserName :<input type="text" name="uname"></input><br/><br/>
Password :<input type="password" name="pwd"></input><br/><br/>
<input type="submit" value="Login"></input>
</form>
</body>
</html>
Output:
When the user clicks on the "Login" button the following PHP script file gets executed. The
PHP script reads the data from HTML form elements using $_POST superglobal variable and
then displays on the screen.
42
postform.php
<!doctype html>
<html lang="en">
<title>Post Form</title>
</head>
<body><br>
<?php
// To read data from input elements using $_POST
$uname = $_POST["uname"];
$password = $_POST["pwd"];
// To display data
echo "Welcome ".$uname."<br/>";
echo "Your password is ".$password;
?>
</body>
</html>
Output:
RadioDemo.html
<html>
<head>
<title>Radiobutton Example</title>
</head>
<body>
<form action="radio.php" method="post">
<b>1.PHP is a _____________ language?</b>
<br/><br/>
<input type="radio" name="q1" value="Programming"> Programming</input><br/>
<input type="radio" name="q1" value="Server-side Scripting"> Server-side
Scripting</input><br/>
43
<input type="radio" name="q1" value="Client-side Scripting"> Client-side
Scripting</input><br/>
<input type="radio" name="q1" value="None of the above"> None of the
above</input><br/>
<br/>
<input type="submit" value="Show"/>
</form>
</body>
</html>
Output:
radio.php
<html>
<head>
<title>Result</title>
</head>
<body>
<?php
$ans=$_POST['q1'];
echo "Selected answer is :$ans <br/><br/>";
echo "Correct answer is : Server-side Scripting";
?>
</body>
</html>
44
Output:
ListDemo.html
<html>
<head>
<title>List Example</title>
</head>
<body>
<form action="list.php" method="post">
<b>Branch : </b>
<select name="branch">
<option value="CSE">CSE</option>
<option value="ECE">ECE</option>
<option value="EEE">EEE</option>
<option value="MECH">MECH</option>
<option value="CIVIL">CIVIL</option>
</select>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Output:
45
list.php
<html>
<head>
<title>List</title>
</head>
<body>
<?php
$branch=$_POST['branch'];
echo "Your Branch is : <b>$branch </b><br/><br/>";
?>
</body>
</html>
Output:
In PHP File System allows us to create file, read file line by line, read file character by
character, write file, append file, delete file and close file.
PHP supports following functions to handle files.
• fopen()
• fread()
• fwrite()
• fclose()
• unlink()
☞ fopen()
In PHP, The fopen() function is used to open a file in read mode or write mode or in both read
and write modes. And this function accepts two arguments: $filename and $mode.
The $filename represents the file to be opended and $mode represents the file mode for
example read-only, read-write, write-only etc.
46
w+ - Read & Write.
Example: "fopen.php"
<?php
$filename = "E:\\studyglance\\simple.txt";
$fp = fopen($filename, "r");//open file in read mode
?>
Note : The above code will open the file in in read mode.
☞ fread()
In PHP, The fread() function is used to read data of the file. It requires two arguments: file
resource and file size.
Syntax: fread(resource $fp,int $length)
Where $fp represents file pointer that is created by fopen() function. And $length represents
length of file (bytes)to be read.
Example: "fread.php"
<?php
$filename = "D:\\studyglance\\file.txt";
$fp = fopen($filename, "r");//open file in read mode
$content = fread($fp, filesize($filename));//read file
echo "$content";//printing data of file
fclose($fp);//close file
?>
Note : To read content of file, we need to open file with r , r+, w+ mode.
Output :
☞ fwrite()
In PHP, The fwrite() function is used to write the content (string) into file.And It requires two
arguments: file resource and data(string)
If the file opened in write(w) mode, the fwrite() function will erase the previous data of the file
and writes the new data or If the file opened in append(a) mode, the fwrite() function appends
the new data at the end of the previous data.
47
Where $fp represents file pointer that is created by fopen() function.And $data represents the
data to be written.
Example: "fwrite.php"
<?php
$filename = "D:\\studyglance\\file.txt";
$fp = fopen($filename, "w");//open file in write mode
fwrite($fp,'PHP is a Scripting Language');
echo "Data written successfully..";
fclose($fp);//close file
?>
Output :
Text File :
Example: "fappend.php"
<?php
$filename = "D:\\studyglance\\file.txt";
$fp = fopen($filename, "a");//open file in write mode
fwrite($fp,' at server side');
echo "Data appended successfully..";
48
fclose($fp);//close file
?>
Output :
Text File :
Note : To write data into file, you need to use w,r+,w+ mode.
☞ fclose()
In PHP, The fclose() function is used to close an open file.And It requires one argument i.e.
"File Pointer"
Example: "fclose.php"
<?php
$filename = "D:\\studyglance\\file.txt";
$fp = fopen($filename, "r");//open file in write mode
// To close the file
fclose($fp);
?>
☞ unlink()
In PHP, The unlink() function is used to delete any file.And It requires one argument i.e. "File
Name"
49
Example: "unlink.php"
<?php
$status=unlink('file.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>
Output :
PHP allow you to upload any type of a file i.e. image, binary or text files.etc..,PHP has one in
built global variable i.e. $_FILES, it contains all information about file.By the help
of $_FILES global variable, we can get file name, file type, file size and temparary file name
associated with file.
In PHP, To upload the file we have to use the function called move_uploaded_file().
☞ move_uploaded_file() function
The move_uploaded_file() function is used to move the uploaded file to a new location. It
moves the file only if it is uploaded through the POST request.
Syntax:
move_uploaded_file ( string $filename , string $destination )
First Configure the php.ini File by ensure that PHP is configured to allow file uploads. In
your php.ini file, search for the file_uploads directive, and set it to On i.e. file_uploads = On
Example: "fileupload.php"
<html>
<head>
50
<title>File Upload</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Select File: <input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Any File" name="submit"/>
</form>
<?php
if(isset($_POST["submit"]))
{
$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!";
}
}
?>
</body>
</html>
Output :
• Sending emails with attachments is a common task while developing PHP applications,
achieved using PHP's built-in mail() function.
• The mail() function allows developers to send emails with text or HTML content and
attach one or more files.
• Here's a sample PHP code that demonstrates how to send an email with an attachment
in PHP:
51
Example:
$message = "This is a sample email with attachment.";
// from
$from = "[email protected]";
// boundary
$boundary = uniqid();
// header information
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\".$boundary.\"\r\n";
// attachment
$attachment = chunk_split(base64_encode(file_get_contents('file.pdf')));
// send email
if (mail($to, $subject, $message, $headers)) {
echo "Email with attachment sent successfully.";
} else {
echo "Failed to send email with attachment.";
}
?>
• The recipient's email address, subject, message body, and header information are
defined in the code above.
• The boundary variable separates the message and attachment in the email.
• The attachment is read from a file using file_get_contents() and encoded
using base64_encode().
• The chunk_split() function splits the attachment into smaller chunks for sending.
• Finally, the mail() function sends the email with an attachment. If the email has been
sent successfully, the function will return true; Otherwise, it will return false.
The development of PHP has focused heavily on database access, and as a result, it provides
driver support for 15 distinct databases systems.
52
You may connect to and work with different databases using PHP. Among
them, MySQL is the most widely used database platform for PHP.
Establishing a connection to the database :
We require four parameters to connect to the database.
mysqli_connect("hostname","username","password","databasename")
The above function creates a successful connection with Database if you provide valid
information. When the connection is not well, we can kill that connection by using die()
format:
☞ mysqli_close()
mysqli_close() function is used to close or terminate the connection with MySQL database.
format:
mysqli_close(Connection);
Example: "DbConnection.php"
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'sampledb';
// to create the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connection established successfully';
// to close the connection
53
mysqli_close($conn);
?>
Output :
format:
mysqli_query(Connection,Query);
54
if(mysqli_query($conn, $query)){
echo "Table students created successfully";
}else{
echo "Could not create table: ". mysqli_error($conn);
}
// to close the connection
mysqli_close($conn);
?>
Output :
55
if(mysqli_query($conn, $query))
{
echo 'Record Inserted Successfully';
}
else
{
echo 'Error';
}
mysqli_close($conn);
?>
Output :
56
$dbname='sampledb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully'."<br/>";
Example: "SelectRecord.php"
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='sampledb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
57
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully'."<br/>";
58