KEMBAR78
Unit-2 Part2 PHP | PDF | Control Flow | Php
0% found this document useful (0 votes)
22 views73 pages

Unit-2 Part2 PHP

PHP, originally standing for 'Personal Home Page', is an open-source, server-side scripting language developed by Rasmus Lerdorf in 1995, primarily used for web application development. It operates in two modes: copy mode, which outputs XHTML, and interpret mode, which processes PHP scripts to generate dynamic content. Installation requires an AMP stack (Apache, MySQL, PHP), with XAMPP being a popular cross-platform option, and PHP supports various data types and operators for programming.

Uploaded by

rohitronaldo834
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)
22 views73 pages

Unit-2 Part2 PHP

PHP, originally standing for 'Personal Home Page', is an open-source, server-side scripting language developed by Rasmus Lerdorf in 1995, primarily used for web application development. It operates in two modes: copy mode, which outputs XHTML, and interpret mode, which processes PHP scripts to generate dynamic content. Installation requires an AMP stack (Apache, MySQL, PHP), with XAMPP being a popular cross-platform option, and PHP supports various data types and operators for programming.

Uploaded by

rohitronaldo834
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/ 73

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 distrbuted
version of PHP.

Official Logo

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

PHP Processing
The PHP processing has two modes of operations
• Copy mode
• Interpret mode
In copy mode, the PHP processor finds XHTML code in the input file, it simply copies the XHTML
code to output file.
In interpreting mode, the PHP processor encounters PHP script in the input file; it interprets the
PHP script and sends the output of the script to the output file.
In simple words, the PHP processor takes a PHP document file as input and produces an XHTML
document file as output.
Client-Server model (Request-Response cycle)

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

In this tutorial, we are going to use XAMPP software pack which is suitable for all operating
systems. 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.
To install XAMPP on windows
1. Go to official website of XAMPP i.e. https://www.apachefriends.org/index.html
2. Click on "XAMPP for windows" as per your windows configuration to download XAMPP
pack.
3. Double click the downloaded file and then click yes to do changes in your operating system.
4. Select the required components like MySQL, FileZilla ftp server, PHP, phpMyAdmin or
leave the default options and click the Next button.
5. Choose installation directory by default installatin directory is "C:/xampp".
6. Click the Allow access button to allow the XAMPP modules from the Windows firewall.
7. After the installation process, click the Finish button of the XAMPP Setup wizard.

To check either XAMPP pack was installed or not


• Open XAMPP control panel and then start Apache and MySQL servers.
• Open any web browser and type "localhost" at the address bar as url, then we will get a
home page of XAMPP (i.e. Installation was successful)

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

Format of PHP tag is

Note : In PHP, each statement ends with semicolon ( ; ).

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

Note: In PHP, . (dot) symbol is used to concatenate two strings.

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 " //
"

// This is single line comment

2. Multi Line Comment


In case of Multi lined comment, the comment must starts with /* and ends with */ i.e. /* .... */ .

/* 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/>";

/* Comments are used to


hide or describe the
code in php */
echo ' This is an example to demonstrate comments in PHP ';
?>
</body>
</html>
Output :

Variables Declaration in PHP


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.

$variablename = value;

Rules for naming variable:


• Variable names can be a group of both letters and digits, but they have to begin with a letter
or an underscore, i.e. the variable name can't be starts with numbers or special symbols.

Example:
$a = "Study"; ---> Valid declaration
$_b = "Glance"; ---> Valid declaration

$3c = "Hello"; ---> Invalid declaration


$*d = 25; ---> Invalid declaration
• 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";

where both variables ($a and $A) are different.

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.

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 :

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

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

$var2 = -675; // a negative number


echo "Negative Number is : ".$var2."<br>";
var_dump($var2);
echo "<br>";

$var3 = 0123; // octal number


echo "Octal Number is : ".$var3."<br>";
var_dump($var3);
echo "<br>";

$var4 = 0x1B; // hexadecimal number


echo "Hexadecimal Number is : ".$var4."<br>";
var_dump($var4);
?>

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>";
$var2 = -67.12; // a negative float
echo "Negative Float Number is : ".$var2."<br>";
var_dump($var2);
echo "<br>";

$var3 = 10.2e3; // double


echo "Double Number is : ".$var3."<br>";
var_dump($var3);
?>

Output :

☞ 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>";

$b= FALSE; // boolean


echo "Status is : ".$b."<br>";
var_dump($b); // it prints datatype and value
?>

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;
}
}
$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);
echo "<br>";
echo $fp;
?>

Output :

Note : 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.

Operators in PHP
An operator can be defined as a symbol which is used to perform a particular operation between
operands.

PHP provides a variety of operators described as follows.


• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• Increment/Decrement Operators
• Logical Operators
• String Operators
• Array Operators

☞ Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands.

Operator Description
+ (addition) Add two operands
- (subtraction) Subtract right operand from the left
Operator Description
*(multiplication) Multiply two operands
/ (divide) Divide left operand by the right one (always results into float)
%( reminder) Modulus - remainder of the division of left operand by the right
** (exponent) Exponent - left operand raised to the power of right

☞ Assignment Operators
The assignment operators are used to assign the value of the right expression to the left operand.

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 result
Modulus) to left operand.
**= (Assignment after Performs exponential (power) calculation on operators
Exponent) and assign value to the left operand.

☞ Comparison operators
Comparison operators are used to comparing the value of the two operands and returns boolean true
or false accordingly.

Operator Description
== (Equal to) Equal to - True if both operands are equal.
!= (Not equal to) Not equal to - True if operands are not equal.
<= (Less than or equal) Less than or equal to - True if left operand is less than or equal
to the right
>= (Greater than or Greater than or equal to - True if left operand is greater than or
equal) 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.
Operator Description
++ (Increment) Increment - It increments the value of operand by one.
-- (Decrement) Decrement - It decrements the value of operand by one.

☞ Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision.

Operator Description
and (or) && (logical and) Returns True if both statements are true
or (or) || (logical or) Returns True if one of the statements is 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
. (Concatenation) It concatenates left operand and right operand.
.= (Assignment after It concatenates left operand and right operand and assign
Concatenation) the result to left operand.

☞ Array operators
Array operators are used to perform various operations on arrays.

Operator Description
+ (Union) It combine two arrys.
== (Equal to) Equal to - True if both operands(arrays) are equal.
!= (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;
$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 :
Control Structures in PHP
The Control Structures (or) Statements used to alter the execution process of a program.

These statements are mainly categorized into following:


• 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 (condtion)
{
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 (condtion)
{
statements
}
else
{
statements
}
☞ if - elseif - else statement
The elseif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them.

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

Loop Statements :
Sometimes we may need to alter the flow of the program. If the execution of a specific code may
need to be repeated several numbers of times then we can go for loop statements.

In PHP, the following are loop statements


• while loop
• do - while loop
• for loop

☞ while loop statement


With the while loop we can execute a set of statements as long as a condition is true. The while loop
is mostly used in the case where the number of iterations is not known in advance.

Syntax :
while (condition)
{
statements
}

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 :

☞ do - while loop statement


The do-while loop will always execute a set of statements atleast once and then execute a set of
statements as long as a condition is true.

Syntax :
do
{
statements
} while (condition);

Example: "DoWhileDemo.php"

<html>
<head>
<title>Do-While Demo</title>
</head>
<body>
<h1>Do-While Demo</h1>
<?php
$n=1;
do
{
echo "$n <br/>";
$n++;
} while($n<=5);
?>
</body>
</html>

Output :

☞ for loop statement


With the for loop we can execute a set of statements specified number of times. The for loop is
mostly used in the case where the number of iterations is known in advance..

Syntax :
for (initialization; condition; increment/decrement)
{
statements
}

Example: "ForDemo.php"

<html>
<head>
<title>For Demo</title>
</head>
<body>
<h1>For Demo</h1>
<?php
for($i=1;$i<=5;$i++)
{
echo "$i <br/>";
}
?>
</body>
</html>
Output :

Jump Statements :
Jump statements in PHP are used to alter the flow of a loop like you want to skip a part of a loop or
terminate a loop.

In PHP, the following are jump statements


• break statement
• continue statement

☞ break statement
The break is a keyword in php which is used to bring the program control out of the loop. i.e. when
a break statement is encountered inside a loop, the loop is terminated and program control resumes
at the next statement following the loop.

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

Arrays in PHP
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.
There are two ways to define indexed array, those are

1st-way:
$marks = array(60, 72, 66);

2nd-way:
$marks [0] = 60;
$marks [1] = 72;
$marks [2] = 66;

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

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).
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 :
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.
☞ Double quoted string :
Example:
$age = 20;
$str1="Your age is : $age"; // string1
echo $str1;
$str2="Your age is : '$age'"; // string2
echo $str2;

Output:
Your age is : 20
Your age is : '20'

☞ Single quoted string :


Example:
$age = 20;
$str1='Your age is : $age'; //string1
echo $str1;
$str2='Your age is : "$age"'; //string2
echo $str2;

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;

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

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 :

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
}

Note : Function name must be starts with a letter or underscore only.

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

function sub($a,$b) //function defn


{
$sub = $a - $b;
echo "Sub is :$sub";
}
sub(63,34);//calling function
?>
</body>
</html>

Output :

Function Call by Value & Reference


PHP allow us to call the function by value and reference.
☞ Call by Value:
In case of call by value, the actual value is not modified even if it is modified inside the function.

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

Default argument function


PHP allow us to define default argument values in the function. In this case if we don�t pass any
value to the function, it will use default argument value.

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>
</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 :

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.

PHP supports two superglobal variables, Those are


• $_GET
- contains list of all input element names and values sent by a form using the get method.
• $_POST
- contains list of all input element names and values sent by a form using the post method.

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

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.

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:

Example Programs

☞ Reading data from Radio Button

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">&nbsp;Programming</input><br/>
<input type="radio" name="q1" value="Server-side Scripting">&nbsp;Server-side
Scripting</input><br/>
<input type="radio" name="q1" value="Client-side Scripting">&nbsp;Client-side
Scripting</input><br/>
<input type="radio" name="q1" value="None of the above">&nbsp;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>
Output:

☞ Reading data from Selection List(Dropdown List)

ListDemo.html

<html>
<head>
<title>List Example</title>
</head>
<body>
<form action="list.php" method="post">
<b>Branch : </b>&nbsp;&nbsp;

<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>
&nbsp;<input type="submit" value="Submit"/>
</form>
</body>
</html>
Output:

list.php

<html>
<head>
<title>List</title>
</head>
<body>
<?php
$branch=$_POST['branch'];
echo "Your Branch is :&nbsp;<b>$branch </b><br/><br/>";

?>
</body>
</html>
Output:

Database Programming in PHP


The development of PHP has focused heavily on database access, and as a result, it provides driver
support for 15 distinct databases systems.

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.

• Hostname (By default "localhost")


• Username (By default "root")
• Password (By default "No Password")
• Database Name
☞ mysqli_connect()
One built-in function in PHP allows us to establish a connection to a database (MySQL) .i.e.
mysqli_connect()

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

die("Can't create connection");

☞ mysqli_close()
mysqli_close() function is used to close or terminate the connection with MySQL database.

mysqli_close(Connection);

☞ An example program to create a connection with the database.

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
mysqli_close($conn);
?>
Output :

Executing simple queries :


Once you've established a connection to the database, you can run/perform a variety of actions on it.

☞ mysqli_query()
PHP includes a built-in function to carry out many database operations, including create, insert,
update, and delete. i.e. mysqli_query()

mysqli_query(Connection,Query);

The above function has two parameters, those are


- Connection : Specifies the name of the connection
- Query: Specifies the query

☞ An example program to create to table in the database.

Example: "TblCreation.php"

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='sampledb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connection established successfully'.'<br>';
// sql query to create students table
$query = "CREATE TABLE students(id INT AUTO_INCREMENT,name VARCHAR(20) NOT
NULL,Age INT NOT NULL,primary key (id))";
// to execute the query
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 :

The "students" table structure in database :

☞ An example program to insert data into table.

Example: "InsertRecord.php"

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='sampledb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully'."<br/>";

$query = 'INSERT INTO students VALUES (1,"Amith",30)';


if(mysqli_query($conn, $query))
{
echo 'Record Inserted Successfully';
}
else
{
echo 'Error';
}
mysqli_close($conn);
?>

Output :

The data in the "students" table :

☞ An example program to delete data from the table.


Example: "DeleteRecord.php"

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='sampledb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully'."<br/>";

$query = 'DELETE FROM students WHERE id=2';


if(mysqli_query($conn, $query))
{
echo 'Records Deleted Successfully';
}
else
{
echo 'Error';
}
mysqli_close($conn);
?>

Output :

Retrieve data from Table


In PHP, mysqli_query() function is used to retrieve data from table. There are two other MySQLi
functions used in select query. those are,

- mysqli_num_rows(mysqli_result $result): returns number of rows.


- mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key of the
array represents the name of column. It return NULL if there are no more rows.

☞ An example program to Select/retrive data from the table.


Example: "SelectRecord.php"

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='sampledb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully'."<br/>";

$query = 'SELECT * FROM students';


$result=mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "Student ID :{$row['id']} <br> ".
"Student NAME : {$row['name']} <br> ".
"Student Age : {$row['age']} <br> ".
"--------------------------------<br>";
} //end of while
}
else
{
echo "0 results";
}
mysqli_close($conn);
?>

Output :
Handling Sessions in PHP
A session is a small piece of information which is stored at server side.And session is used to store
and pass information from one page to another temporarily(until user close the website).
A session technique is widely used in shopping websites where we need to store and pass cart
information e.g.user name, product code, product name, product price etc from one page to another.
In simple words, A session is a way to store information (in variables) to be used across multiple
pages.

Start a PHP session :


☞ session_start() function is used to start the session.It starts a new or resumes existing session.
Example:
session_start();

Note : The session-start() function must be the very first thing in your document.

To get and set session variables :


☞ $_SESSION is an associative array that contains all session variables.And it is used to set and
get session variable values.

Example: To set session variable or store information in session variable


$_SESSION["name"] = "StudyGlance";

Example: To get session variable or get information from session variable


echo $_SESSION["name"];

Example1:
A simple example to understand working with sessions in PHP. In this, there are two PHP programs,
first program (FirstPage.php) is to create session variables and store information. And the second
program (SecondPage.php) is to get the information from the session variable.

Example: "FirstPage.php"

<?php
// to start the session
session_start();
?>
<html>
<body>
<?php
// To create session variable called "name"
$_SESSION["name"] = "Study Glance";
?>
<a href="SecondPage.php">Click Here to Visit Next Page</a>
</body>
</html>

Example: "SecondPage.php"

<?php
// to start the session
session_start();
?>
<html>
<body>
<?php
// to get the infromation from session variable
echo "Website Name is: ".$_SESSION["name"];
?>
</body>
</html>

Output :

After clicking on the above Hyperlink


Example2:
In this example, reading input from a text field and storing it in a session variable after which
another page reads the value of the session variable.

Example: "sessionPage1.php"

<?php
// To start the session
session_start();
?>
<html>
<head>
<title>Session example</title>
</head>
<body>
<form name="form1" method="post">
Name : <input name="uname" type="text">
<br/><br/>
<input type="submit" name="Submit" value="SUBMIT">
</form>
<?php
if(isset($_POST['Submit']))
{
$_SESSION["name"] = $_POST["uname"];
header('Location: sessionPage2.php');
}
?>
</body>
</html>

Example: "sessionPage2.php"

<?php
// To start the session
session_start();
?>
<html>
<head>
<title>Welcome </title>
</head>
<body>
<br/>
<?php
echo "Welcome : ".$_SESSION['name'];
?>
</body>
</html>
Output :

Once the SUBMIT button has been pressed

Destroying Session :
☞ session_destroy() function is used to destroy all session variables completely.

Example:
session_destroy();

Note : Unlike a cookie, the information is not stored on the users computer.

Handling Cookies in PHP


A cookie is a piece of information that is stored in the client browser. Additionally, a cookie is
generated on the server and saved to the client browser.
• A cookie is often used to identify a user.
• The Cookies are stored on the client side.
• A cookie takes less space to store data.

The first time when a client sends a request to the server, the server embedded the cookie along with
the response. Next time onwards client sends the request along with a cookie to the server. In such a
way, cookies can be received on the server side.

A cookie is a small file that the server embeds on the user's computer. With PHP, we can both create
and retrieve cookie values.
Note : Cookie must be used before html tag.

Create cookies with PHP :


☞ setcookie() function is used to set/create cookie.
Syntax:
setcookie(name, value, expire);

In the above only the name parameter is required. All other parameters are optional.
Example1:
setcookie("username","StudyGlance");

In the above example, defining a name and value for cookie

Example2:
setcookie("username","StudyGlance",time()+1*60*60);
In the above example, defining a name and value for cookie along with expiry time (1 hour =
1*60*60 seconds or 3600 seconds)

Retrieve a cookie :
☞ $_COOKIE superglobal variable is used to get/retrieve cookie. i.e Once cookie is set, we can
access cookie by $_COOKIE superglobal variable.
Example:
$value = $_COOKIE["username"];

Example1:

A simple example to understand working with cookies in PHP.

Example: "cookiedemo.php"

<?php
// To create cookie
setcookie("username", "StudyGlance");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["username"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["username"];
}
?>
</body>
</html>

Output :

Once the page has been reloaded


In the above example program, Firstly cookie is not set. But, if you refresh the page, you will see
cookie is set now. And it creates the cookie "username" along with the value "StudyGlance" and the
default expiry time 0. i,e the cookie will expire as soon as after closing the browser window.

Example2:

A simple example to understand working with cookies along with expiry time in PHP.

Example: "cookiedemoex.php"

<?php
// To create cookie
setcookie("username", "StudyGlance",time()+1*60*60);
?>
<html>
<body>
<?php
if(!isset($_COOKIE["username"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["username"];
}
?>
</body>
</html>
Output :

Once the page has been reloaded

In the above example program, Firstly cookie is not set. But, if you refresh the page, you will see
cookie is set now. And it creates the cookie "username" along with the value "StudyGlance" and
with the expiry time 1 hour (1*60*60 seconds or 3600 seconds.) i,e the cookie will expire after 1
hour.

File Handling in PHP


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.

Syntax: fopen(string $filename , string $mode)

The $filename represents the file to be opended and $mode represents the file mode for example
read-only, read-write, write-only etc.

The fopen() supports the following modes:

r - Read Only
w - Write Only
a - Append
r+ - Read & Write.
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.

Syntax: fwrite(resource $fp,string $data)

Where $fp represents file pointer that is created by fopen() function.And $data represents the data
to be written.

☞ If the file opened in write(w) mode :

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 :

☞ If the file opened in append(a) mode :

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..";
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"

Syntax: fclose(resource $fp)

Where $fp represents file pointer that is created by fopen() function.

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"

Syntax: unlink(string $filename)

Where $filename represents name of the file to be remove.

Example: "unlink.php"

<?php
$status=unlink('file.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>

Output :
File Uploading in PHP
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.

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

In HTML, File Upload control can be created by using following:


<input type="file" name="fileupload"/>

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

You might also like