Você está na página 1de 57

PHP o Platform Independent: PHP are available for

(HYPERTEXT PREPROCESSOR) WINDOWS, MAC, LINUX & UNIX operating system. A


PHP application developed in one OS can be easily
PHP is a open source, interpreted and object-oriented executed in other OS also.
scripting language i.e. executed at server side. It is used to
o Compatibility: PHP is compatible with almost all local
develop web applications (an application i.e. executed at
server side and generates dynamic page). servers used today like Apache, IIS etc.
o Embedded: PHP code can be easily embedded within
 What is PHP HTML tags and script.

o PHP is a server side scripting language.  Install PHP


o PHP is an interpreted language, i.e. there is no need
To install PHP, we will suggest you to install AMP (Apache,
for compilation.
MySQL, PHP) software stack. It is available for all operating
o PHP is an object-oriented language. systems. There are many AMP options available in the
o PHP is an open-source scripting language. market that is given below:
o PHP is simple and easy to learn language.
o WAMP for Windows
 PHP Features o LAMP for Linux
o MAMP for Mac
There are given many features of PHP.
o SAMP for Solaris
o Performance: Script written in PHP executes much o FAMP for FreeBSD
faster than those scripts written in other languages o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross
such as JSP & ASP. Platform: It includes some other components too
o Open Source Software: PHP source code is freely such as FileZilla, OpenSSL, Webalizer, Mercury Mail
available on the web; you can develop all the version etc.
of PHP according to your requirement without
paying any cost.

1
If you are on Windows and don't want Perl and other Output:
features of XAMPP, you should go for WAMP. In a similar
way, you may use LAMP for Linux and MAMP for Macintosh. Hello First PHP
 PHP Example PHP Echo
It is very easy to create a simple PHP example. To do so, PHP echo is a language construct not a function, so you
create a file and write HTML tags + PHP code and save this don't need to use parenthesis with it. But if you want to use
file with .php extension. more than one parameters, it is required to use parenthesis.

All PHP code goes between php tag. Syntax of PHP tag is The syntax of PHP echo is given below:
given below:
void echo ( string $arg1 [, string $... ] )
<?php
PHP echo statement can be used to print string, multi line
//your code here strings, escaping characters, variable, array etc.
?>
PHP echo: printing string
Let's see a simple PHP example where we are writing some
text using PHP echo command. File: echo1.php
<?php
File: first.php echo "Hello by PHP echo";
1. <!DOCTYPE> ?>
2. <html>
3. <body> Output:
4. <?php
Hello by PHP echo
5. echo "<h2>Hello First PHP</h2>";
6. ?> PHP echo: printing multi line string
7. </body>
File: echo2.php
8. </html>

2
<?php ?>
echo "Hello by PHP echo
Output:
this is multi line
text printed by Message is: Hello JavaTpoint PHP
PHP echo statement
";
PHP Print
?>
Like PHP echo, PHP print is a language construct, so you
Output: don't need to use parenthesis with the argument list. Unlike
echo, it always returns 1.
Hello by PHP echo this is multi line text printed by PHP echo
statement The syntax of PHP print is given below:

PHP echo: printing escaping characters int print(string $arg)

File: echo3.php PHP print statement can be used to print string, multi line
<?php strings, escaping characters, variable, array etc.
echo "Hello escape \"sequence\" characters";
PHP print: printing string
?>

File: print1.php
Output:
<?php
Hello escape "sequence" characters print "Hello by PHP print ";
print ("Hello by PHP print()");
PHP echo: printing variable value ?>

File: echo4.php Output:


<?php
Hello by PHP print Hello by PHP print()
$msg="Hello JavaTpoint PHP";
echo "Message is: $msg";

3
PHP print: printing multi line string <?php
$msg="Hello print() in PHP";
File: print2.php
print "Message is: $msg";
<?php
?>
print "Hello by PHP print
this is multi line Output:
text printed by
Message is: Hello print() in PHP
PHP print statement
"; PHP Variables
?>
A variable in PHP is a name of memory location that holds
data. A variable is a temporary storage that is used to store
Output: data temporarily.

Hello by PHP print this is multi line text printed by PHP print In PHP, a variable is declared using $ sign followed by
statement variable name.

PHP print: printing escaping characters Syntax of declaring a variable in PHP is given below:

File: print3.php
$variablename=value;
<?php
print "Hello escape \"sequence\" characters by PHP p A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
rint";
?> Rules for PHP variables:

Output:  A variable starts with the $ sign, followed by the


name of the variable
Hello escape "sequence" characters by PHP print  A variable name must start with a letter or the
underscore character
 A variable name cannot start with a number
PHP print: printing variable value  A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
File: print4.php

4
 Variable names are case-sensitive ($age and $AGE The scope of a variable is the part of the script where the
are two different variables) variable can be referenced/used.

PHP Variable: Declaring string, integer and float PHP has three different variable scopes:

Let's see the example to store string, integer and float  local
values in PHP variables.  global
 static
File: variable1.php
Global and Local Scope
<?php
$str="hello string"; A variable declared outside a function has a GLOBAL
$x=200; SCOPE and can only be accessed outside a function:
$y=44.6;
Example
echo "string is: $str <br/>";
<?php
echo "integer is: $x <br/>";
$x = 5; // global scope
echo "float is: $y <br/>";
?> function myTest() {
// using x inside this function will generate an
Output: error
echo "<p>Variable x inside function is: $x</p>";
string is: hello string }
integer is: 200
myTest();
float is: 44.6

echo "<p>Variable x outside function is: $x</p>";


PHP: Loosely typed language
?>
PHP is a loosely typed language; it means PHP automatically
converts the variable to its correct data type. Output:

Variable x inside function is:


PHP Variables Scope Variable x outside function is: 5

In PHP, variables can be declared anywhere in the script.

5
A variable declared within a function has a LOCAL SCOPE Example
and can only be accessed within that function:
<?php
Example $x = 5;
$y = 10;
<?php
function myTest() { function myTest() {
$x = 5; // local scope global $x, $y;
echo "<p>Variable x inside function is: $x</p>"; $y = $x + $y;
} }
myTest();
myTest();
// using x outside the function will generate an error echo $y; // outputs 15
echo "<p>Variable x outside function is: $x</p>"; ?>
?>
Output:
15

Output:
PHP also stores all global variables in an array called
Variable x inside function is: 5 $GLOBALS[index]. The index holds the name of the
Variable x outside function is: variable. This array is also accessible from within functions
and can be used to update global variables directly.
Note: You can have local variables with the same name in
The example above can be rewritten like this:
different functions, because local variables are only
recognized by the function in which they are declared. Example

<?php
PHP The global Keyword $x = 5;
$y = 10;
The global keyword is used to access a global variable from
within a function. function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
To do this, use the global keyword before the variables }
(inside the function):

6
myTest(); Then, each time the function is called, that variable will still
echo $y; // outputs 15 have the information it contained from the last time the
?> function was called.

Output: Note: The variable is still local to the function.


15
PHP Constants
PHP The static Keyword
PHP constants are name or identifier that can't be changed
Normally, when a function is completed/executed, all of its during the execution of the script. PHP constants can be
variables are deleted. However, sometimes we want a local defined by 2 ways:
variable NOT to be deleted. We need it for a further job.
1. Using define() function
To do this, use the static keyword when you first declare
the variable: 2. Using const keyword

Example PHP constants follow the same PHP variable rules. For
example, it can be started with letter or underscore only.
<?php
function myTest() { Conventionally, PHP constants should be defined in
static $x = 0; uppercase letters.
echo $x;
$x++; PHP constant by using define()
}
Let's see the syntax of define() function in PHP.
myTest();
myTest();
define(name, value, case-insensitive)
myTest();
?> 1. name: specifies the constant name

Output: 2. value: specifies the constant value


0 3. case-insensitive: Default value is false. It means it is
1
case sensitive by default.
2
Let's see the example to define PHP constant using define().

7
File: constant1.php Output:
<?php
Hello JavaTpoint PHP
define("MESSAGE","Hello JavaTpoint PHP"); Notice: Use of undefined constant message - assumed
echo MESSAGE; 'message'
in C:\wamp\www\vconstant3.php on line 4
?>
message

Output:
PHP constant by using const keyword
Hello JavaTpoint PHP
The const keyword defines constants at compile time. It is a
File: constant2.php language construct not a function.
<?php
It is bit faster than define().
define("MESSAGE","Hello JavaTpoint PHP",true);//no
t case sensitive It is always case sensitive.
echo MESSAGE;
File: constant4.php
echo message;
<?php
?>
const MESSAGE="Hello const by JavaTpoint PHP";
Output: echo MESSAGE;
?>
Hello JavaTpoint PHPHello JavaTpoint PHP
Output:
File: constant3.php
<?php Hello const by JavaTpoint PHP
define("MESSAGE","Hello JavaTpoint PHP",false);//ca
se sensitive PHP Data Types
echo MESSAGE;
echo message; Variables can store data of different types, and different
data types can do different things.
?>
PHP supports the following data types:

8
 String  An integer must have at least one digit
 Integer  An integer must not have a decimal point
 Float (floating point numbers - also called double)  An integer can be either positive or negative
 Boolean  Integers can be specified in three formats: decimal
 Array (10-based), hexadecimal (16-based - prefixed with
 Object 0x) or octal (8-based - prefixed with 0)
 NULL
 Resource In the following example $x is an integer. The PHP
var_dump() function returns the data type and value:
1. PHP String
Example
A string is a sequence of characters, like "Hello world!". A
string can be any text inside quotes. You can use single or <?php
double quotes: $x = 5985;
var_dump($x);
Example ?>

<?php Output
$x = "Hello world!"; int(5985)
$y = 'Hello world!';

echo $x; 3. PHP Float


echo "<br>";
echo $y; A float (floating point number) is a number with a decimal
point or a number in exponential form.
?>

Output: In the following example $x is a float. The PHP var_dump()


function returns the data type and value:
Hello world!
Hello world!
Example
2. PHP Integer
<?php
$x = 10.365;
An integer data type is a non-decimal number between -
2,147,483,648 and 2,147,483,647. var_dump($x);
?>
Rules for integers:

9
Output: In PHP, an object must be explicitly declared.
float(10.365)
First we must declare a class of object. For this, we use the
class keyword. A class is a structure that can contain
4. PHP Boolean properties and methods:

A Boolean represents two possible states: TRUE or FALSE. Example

$x = true; <?php
$y = false; class Car {
function Car() {
Booleans are often used in conditional testing. $this->model = "VW";
}
5. PHP Array }

An array stores multiple values in one single variable. // create an object


$herbie = new Car();
In the following example $cars is an array. The PHP
var_dump() function returns the data type and value:
// show object properties
echo $herbie->model;
Example
?>
<?php
$cars = array("Volvo","BMW","Toyota"); Output:
var_dump($cars); VW
?>
7. PHP NULL Value
Output:
Null is a special data type which can have only one value:
array(3) {[0]=> string(5) "Volvo" [1]=> string(3)
NULL.
"BMW" [2]=> string(6) "Toyota"}

6. PHP Object A variable of data type NULL is a variable that has no value
assigned to it.
An object is a data type which stores data and information
on how to process that data. Tip: If a variable is created without a value, it is
automatically assigned a value of NULL.

10
Variables can also be emptied by setting the value to NULL: 1. PHP Arithmetic Operators

Example The PHP arithmetic operators are used with numeric values
to perform common arithmetical operations, such as
<?php addition, subtraction, multiplication etc.
$x = "Hello world!";
$x = null;
Operator Name Example Result
var_dump($x);
?> Sum of $x and
+ Addition $x + $y
$y
Output:
NULL Difference of
- Subtraction $x - $y
$x and $y
8. PHP Resource
Product of $x
The special resource type is not an actual data type. It is * Multiplication $x * $y
and $y
the storing of a reference to functions and resources
external to PHP. Quotient of $x
/ Division $x / $y
and $y
A common example of using the resource data type is a
database call. Remainder of
% Modulus $x % $y $x divided by
PHP Operators $y

Result of
Operators are used to perform operations on variables and
raising $x to
values.
the $y'th
** Exponentiation $x ** $y
power
PHP divides the operators in the following groups: (Introduced in
PHP 5.6)
 Arithmetic operators
 Assignment operators
 Comparison operators 2. PHP Assignment Operators
 Increment/Decrement operators
 Logical operators
The PHP assignment operators are used with numeric values
 String operators
to write a value to a variable.
 Array operators

11
The basic assignment operator in PHP is "=". It means that
=== Identical $x === $y Returns true if
the left operand gets set to the value of the assignment
$x is equal to
expression on the right.
$y, and they
are of the same
Assignment Same Description type
as...
!= Not equal $x != $y Returns true if
x=y x=y The left operand gets set
$x is not equal
to the value of the
to $y
expression on the right
<> Not equal $x <> $y Returns true if
x += y x = x + y Addition
$x is not equal
to $y
x -= y x=x-y Subtraction
!== Not $x !== $y Returns true if
x *= y x=x*y Multiplication
identical $x is not equal
to $y, or they
x /= y x=x/y Division
are not of the
same type
x %= y x = x % y Modulus
> Greater $x > $y Returns true if
3. PHP Comparison Operators than $x is greater
than $y
The PHP comparison operators are used to compare two
values (number or string): < Less than $x < $y Returns true if
$x is less than
$y
Operator Name Example Result
>= Greater $x >= $y Returns true if
== Equal $x == $y Returns true if
than or $x is greater
$x is equal to
equal to than or equal to
$y
$y

<= Less than $x <= $y Returns true if


or equal to $x is less than
or equal to $y

12
4. PHP Increment / Decrement Operators
xor Xor $x xor $y True if either $x or
$y is true, but not
The PHP increment operators are used to increment a both
variable's value.
&& And $x && $y True if both $x and
The PHP decrement operators are used to decrement a $y are true
variable's value.
|| Or $x || $y True if either $x or
Operator Name Description $y is true

++$x Pre-increment Increments $x by one, then ! Not !$x True if $x is not true
returns $x

$x++ Post-increment Returns $x, then increments 6. PHP String Operators


$x by one
PHP has two operators that are specially designed for
--$x Pre-decrement Decrements $x by one, then strings.
returns $x
Operator Name Example Result
$x-- Post- Returns $x, then
decrement decrements $x by one
. Concatenation $txt1 . $txt2 Concatenation
of $txt1 and
$txt2
5. PHP Logical Operators
.= Concatenation $txt1 .= Appends $txt2
The PHP logical operators are used to combine conditional assignment $txt2 to $txt1
statements.

Operator Name Example Result 7. PHP Array Operators

and And $x and $y True if both $x and The PHP array operators are used to compare arrays.
$y are true

or Or $x or $y True if either $x or
$y is true

13
Operator Name Example Result PHP Single Line Comments

+ Union $x + $y Union of $x and $y There are two ways to use single line comments in PHP.

== Equality $x == $y Returns true if $x


o // (C++ style single line comment)
and $y have the
same key/value o # (Unix Shell style single line comment)
pairs

=== Identity $x === $y Returns true if $x <?php


and $y have the // this is C++ style single line comment
same key/value
# this is Unix Shell style single line comment
pairs in the same
order and of the echo "Welcome to PHP single line comments";
same types ?>

!= Inequality $x != $y Returns true if $x


Output:
is not equal to $y
Welcome to PHP single line comments
<> Inequality $x <> $y Returns true if $x
is not equal to $y
PHP Multi Line Comments
!== Non- $x !== $y Returns true if $x
identity is not identical to In PHP, we can comments multiple lines also. To do so, we
$y need to enclose all lines within /* */. Let's see a simple
example of PHP multiple line comment.
PHP Comments
<?php
PHP comments can be used to describe any line of code so
that other developer can understand the code easily. It can /*
also be used to hide any code. Anything placed
within comment
PHP supports single line and multi line comments. These
comments are similar to C/C++ and Perl style (Unix shell will not be displayed
style) comments. on the browser;
*/

14
echo "Welcome to PHP multi line comment"; Flowchart

?>

Output:

Welcome to PHP multi line comment

CONTROL STATEMENTS
PHP If Else

PHP if else statement is used to test condition. There are


various ways to use if statement in PHP.

o if

o if-else

o if-else-if

o nested if Example

PHP If Statement <?php

PHP if statement is executed if condition is true. $num=12;


if($num<100){
Syntax echo "$num is less than 100";
if(condition){ }
//code to be executed ?>
}
Output:

12 is less than 100

15
PHP If-else Statement Example

PHP if-else statement is executed whether condition is true <?php


or false.
$num=12;
Syntax if($num%2==0){
if(condition){ echo "$num is even number";
//code to be executed if true }else{
}else{ echo "$num is odd number";
//code to be executed if false }
} ?>

Flowchart Output:

12 is even number

PHP Switch

PHP switch statement is used to execute one statement


from multiple conditions. It works like PHP if-else-if
statement.

Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;

16
...... PHP Switch Example

default:
<?php
code to be executed if all cases are not matched;
$num=20;
}
switch($num){
PHP Switch Flowchart case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>

Output:

number is equal to 20

PHP For Loop

PHP for loop can be used to traverse set of code for the
specified number of times.

17
It should be used if number of iteration is known otherwise Example
use while loop.
<?php
Syntax for($n=1;$n<=10;$n++){
echo "$n<br/>";
for(initialization; condition; increment/decrement){ }
//code to be executed ?>
} Output:
1
2
Flowchart
3
4
5
6
7
8
9
10

PHP Nested For Loop

We can use for loop inside for loop in PHP, it is known as


nested for loop.

In case of inner or nested for loop, nested for loop is


executed fully for one outer for loop. If outer for loop is to
be executed for 3 times and inner for loop for 3 times, inner
for loop will be executed 9 times (3 times for 1st outer loop,
3 times for 2nd outer loop and 3 times for 3rd outer loop).

Example

<?php
for($i=1;$i<=3;$i++){

18
for($j=1;$j<=3;$j++){ $season=array("summer","winter","spring","a
echo "$i $j<br/>"; utumn");
} foreach( $season as $arr ){
} echo "Season is: $arr<br />";
?> }
?>
Output:
Output:
1 1
1 2
Season is: summer
1 3
Season is: winter
2 1
Season is: spring
2 2
Season is: autumn
2 3
3 1 PHP While Loop
3 2
3 3
PHP while loop can be used to traverse set of code like for
loop.
PHP For Each Loop
It should be used if number of iteration is not known.
PHP for each loop is used to traverse array elements.
Syntax
Syntax
while(condition){
foreach( $array as $var ){
//code to be executed
//code to be executed
}
}
?> Alternative Syntax

Example while(condition):
//code to be executed
<?php
endwhile

19
PHP While Loop Flowchart 1
2
3
4
5
6
7
8
9
10

Alternative Example

<?php
$n=1;
while($n<=10):
echo "$n<br/>";
$n++;
endwhile;
?>

PHP While Loop Example


Output:

<?php 1
2
$n=1; 3
while($n<=10){ 4
5
echo "$n<br/>"; 6
$n++; 7
8
} 9
?> 10

Output:

20
PHP Nested While Loop 2 3
3 1
3 2
We can use while loop inside another while loop in PHP, it is 3 3
known as nested while loop.
PHP do while loop
In case of inner or nested while loop, nested while loop is
executed fully for one outer while loop. If outer while loop is PHP do while loop can be used to traverse set of code like
to be executed for 3 times and nested while loop for 3 php while loop. The PHP do-while loop is guaranteed to run
times, nested while loop will be executed 9 times (3 times at least once.
for 1st outer loop, 3 times for 2nd outer loop and 3 times
for 3rd outer loop). It executes the code at least one time always because
condition is checked after executing the code.
Example
Syntax
<?php
$i=1; do{

while($i<=3){ //code to be executed

$j=1; }while(condition);

while($j<=3){ Flowchart
echo "$i $j<br/>";
$j++;
}
$i++;
}
?>

Output:

1 1
1 2
1 3
2 1
2 2

21
Example Flowchart

<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>

Output:

1
2
3
4
5
6
7
8
9
10
PHP Break: inside loop
PHP Break
Let's see a simple example to break the execution of for
PHP break statement breaks the execution of current for, loop if value of i is equal to 5.
while, do-while, switch and for-each loop. If you use break
inside inner loop, it breaks the execution of inner loop only.
<?php
Syntax for($i=1;$i<=10;$i++){
echo "$i <br/>";
jump statement;
if($i==5){
break;
break;
}

22
2 1
} 2 2
?> 3 1
3 2
Output: 3 3

1 PHP Break: inside switch statement


2
3 The PHP break statement breaks the flow of switch case
4
also.
5

PHP Break: inside inner loop <?php


$num=200;
The PHP break statement breaks the execution of inner loop switch($num){
only.
case 100:
echo("number is equals to 100");
<?php
break;
for($i=1;$i<=3;$i++){
case 200:
for($j=1;$j<=3;$j++){
echo("number is equal to 200");
echo "$i $j<br/>";
break;
if($i==2 && $j==2){
case 50:
break;
echo("number is equal to 300");
}
break;
}
default:
}
echo("number is not equal to 100, 200 or 500");
?>
}
Output: ?>

1 1 Output:
1 2
1 3
number is equal to 200

23
PHP Functions Note: Function name must be start with letter and
underscore only like other labels in PHP. It can't be
PHP function is a piece of code that can be reused many
times. It can take input as argument list and return value. start with numbers or special symbols.
There are thousands of built-in functions in PHP.

In PHP, we can define Conditional function, Function PHP Functions Example


within Function and Recursive function also.
File: function1.php
Advantage of PHP Functions
<?php
Code Reusability: PHP functions are defined only once and
can be invoked many times, like in other programming function sayHello(){
languages. echo "Hello PHP Function";
}
Less Code: It saves a lot of code because you don't need
to write the logic many times. By the use of function, you sayHello();//calling function
can write the logic only once and reuse it. ?>

Easy to understand: PHP functions separate the Output:


programming logic. So it is easier to understand the flow of
the application because every logic is divided in the form of Hello PHP Function
functions.
PHP Parameterized Function
PHP User-defined Functions
PHP Parameterized functions are the functions with
We can declare and call user-defined functions easily. Let's parameters. You can pass any number of parameters inside
see the syntax to declare user-defined functions. a function. These passed parameters act as variables inside
your function.
Syntax
They are specified inside the parentheses, after the function
name.
function functionname(){
//code to be executed The output depends upon the dynamic values passed as the
} parameters into the function.

24
PHP Parameterized Example

Addition and Subtraction

In this example, we have passed two


parameters $x and $y inside two functions add() and sub().

<!DOCTYPE html>
<html>
<head>
<title>Parameter Addition and Subtraction Example</titl
e>
</head>
<body>
<?php
//Adding two numbers PHP Call By Value
function add($x, $y) {
$sum = $x + $y; PHP allows you to call function by value and reference both.
echo "Sum of two numbers is = $sum <br><br>"; In case of PHP call by value, actual value is not modified if it
} is modified inside the function.
add(467, 943);
Let's understand the concept of call by value by the help of
//Subtracting two numbers examples.
function sub($x, $y) {
$diff = $x - $y;
Example
echo "Difference between two numbers is = $diff";
}
sub(943, 467); In this example, variable $str is passed to the adder
?> function where it is concatenated with 'Call By Value' string.
</body> But, printing $str variable results 'Hello' only. It is because
</html> changes are done in the local variable $str2 only. It doesn't
reflect to $str variable.

Output:

25
<?php <?php
function adder($str2) function adder(&$str2)
{ {
$str2 .= 'Call By Value'; $str2 .= 'Call By Reference';
} }
$str = 'Hello '; $str = 'This is ';
adder($str); adder($str);
echo $str; echo $str;
?> ?>

Output: Output:

Hello This is Call By Reference

PHP Call By Reference PHP Default Argument Values Function


In case of PHP call by reference, actual value is modified if it
PHP allows you to define C++ style default argument
is modified inside the function. In such case, you need to values. In such case, if you don't pass any value to the
use & (ampersand) symbol with formal arguments. The & function, it will use default argument value.
represents reference of the variable.
Let' see the simple example of using PHP default arguments
Let's understand the concept of call by reference by the in function.
help of examples.
Example 1
Example <?php
function sayHello($name="Ram"){
In this example, variable $str is passed to the adder echo "Hello $name<br/>";
function where it is concatenated with 'Call By Reference' }
string. Here, printing $str variable results 'This is Call By
sayHello("Sonoo");
Reference'. It is because changes are done in the actual
sayHello();//passing no value
variable $str.
sayHello("Vimal");
?>

26
Output: add(40,40);
?>
Hello Sonoo
Hello Ram Output:
Hello Vimal
Addition is: 20
Since PHP 5, you can use the concept of default argument Addition is: 30
value with call by reference also. Addition is: 80

Example 2 PHP Variable Length Argument Function


<?php
PHP supports variable length argument function. It means
function greeting($first="Sonoo",$last="Jaiswal"){
you can pass 0, 1 or n number of arguments in function. To
echo "Greeting: $first $last<br/>"; do so, you need to use 3 ellipses (dots) before the
} argument name.

greeting(); The 3 dot concept is implemented for variable length


greeting("Rahul"); argument since PHP 5.6.
greeting("Michael","Clark");
Let's see a simple example of PHP variable length argument
?> function.

Output: <?php
function add(...$numbers) {
Greeting: Sonoo Jaiswal
Greeting: Rahul Jaiswal $sum = 0;
Greeting: Michael Clark foreach ($numbers as $n) {
$sum += $n;
Example 3 }
<?php return $sum;
function add($n1=10,$n2=10){ }
$n3=$n1+$n2;
echo "Addition is: $n3<br/>"; echo add(1, 2, 3, 4);
}
?>
add();
add(20);

27
Output: Example 2 : Factorial Number
<?php
10 function factorial($n)
{
PHP Recursive Function if ($n < 0)
return -1; /*Wrong value*/
PHP also supports recursive function call like C/C++. In if ($n == 0)
such case, we call current function within function. It is also return 1; /*Terminating condition*/
known as recursion. return ($n * factorial ($n -1));
}
It is recommended to avoid recursive function call over 200
recursion level because it may smash the stack and may
cause the termination of script. echo factorial(5);
?>
Example 1: Printing number
<?php Output:
function display($number) {
120
if($number<=5){
echo "$number <br/>";
display($number+1); PHP Arrays
}
} PHP array is an ordered map (contains value on the basis of
key). It is used to hold multiple values of similar type in a
display(1); single variable.
?>
Advantage of PHP Array
Output:
Less Code: We don't need to define multiple variables.
1
2 Easy to traverse: By the help of single loop, we can
3 traverse all the elements of an array.
4
5 Sorting: We can sort the elements of array.

28
PHP Array Types PHP Indexed Array Example

There are 3 types of array in PHP. File: array1.php


<?php
1. Indexed Array
$size=array("Big","Medium","Short");
2. Associative Array echo "Size: $size[0], $size[1] and $size[2]";
3. Multidimensional Array ?>

PHP Indexed Array Output:

PHP indexed array is an array which is represented by an Size: Big, Medium and Short
index number by default. All elements of array are
represented by an index number which starts from 0. File: array2.php
<?php
PHP indexed array can store numbers, strings or any object.
PHP indexed array is also known as numeric array. $size[0]="Big";
$size[1]="Medium";
Definition $size[2]="Short";
echo "Size: $size[0], $size[1] and $size[2]";
There are two ways to define indexed array:
?>
1st way:
Output:
$size=array("Big","Medium","Short");
Size: Big, Medium and Short
2nd way:
Traversing PHP Indexed Array

$size[0]="Big"; We can easily traverse array in PHP using foreach loop.


$size[1]="Medium"; Let's see a simple example to traverse all the elements of
PHP array.
$size[2]="Short";
File: array3.php

29
<?php PHP Associative Array
$size=array("Big","Medium","Short");
PHP allows you to associate name/label with each array
foreach( $size as $s ) elements in PHP using => symbol. Such way, you can easily
{ remember the element because each element is
represented by label than an incremented number.
echo "Size is: $s<br />";
} Definition
?>
There are two ways to define associative array:
Output:
1st way:
Size is: Big
Size is: Medium
Size is: Short $salary=array("Sonoo"=>"550000","Vimal"=>"250000","R
atan"=>"200000");
Count Length of PHP Indexed Array
2nd way:
PHP provides count() function which returns length of an
array. $salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
<?php
$salary["Ratan"]="200000";
$size=array("Big","Medium","Short");
echo count($size); Example
?>
File: arrayassociative1.php
Output: <?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000",
3 "Ratan"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>

30
Output:
<?php
Sonoo salary: 550000 $salary=array("Sonoo"=>"550000","Vimal"=>"250000",
Vimal salary: 250000 "Ratan"=>"200000");
Ratan salary: 200000 foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
File: arrayassociative2.php }
<?php ?>

$salary["Sonoo"]="550000";
Output:
$salary["Vimal"]="250000";
$salary["Ratan"]="200000"; Key: Sonoo Value: 550000
Key: Vimal Value: 250000
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>"; Key: Ratan Value: 200000
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>"; PHP Multidimensional Array
?>
PHP multidimensional array is also known as array of
arrays. It allows you to store tabular data in an array. PHP
Output:
multidimensional array can be represented in the form of
matrix which is represented by row * column.
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000 Definition

Traversing PHP Associative Array $emp = array


(
By the help of PHP for each loop, we can easily traverse the
elements of PHP associative array. array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

31
PHP Multidimensional Array Example Output:

1 sonoo 400000
Let's see a simple example of PHP multidimensional array to
display following tabular data. In this example, we are 2 john 500000
displaying 3 rows and 3 columns. 3 rahul 300000

Id Name Salary PHP Array Functions


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

2 john 500000
1) PHP array() function
3 rahul 300000
PHP array() function creates and returns an array. It allows
you to create indexed, associative and multidimensional
arrays.
File: multiarray.php
Syntax
<?php
$emp = array
( array array ([ mixed $... ] )
array(1,"sonoo",400000),
array(2,"john",500000), Example
array(3,"rahul",300000)
);
<?php
for ($row = 0; $row < 3; $row++) { $season=array("summer","winter","spring","autumn");
for ($col = 0; $col < 3; $col++) { echo "Season are: $season[0], $season[1], $season[2] and
echo $emp[$row][$col]." ";
} $season[3]";
echo "<br/>"; ?>
}
?> Output:

Season are: summer, winter, spring and autumn

32
2) PHP array_change_key_case() function Output:

PHP array_change_key_case() function changes the case of Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] =>
all key of an array. 200000 )

Note: It changes case of key only. 3) PHP array_chunk() function

Syntax PHP array_chunk() function splits array into chunks. By


using array_chunk() method, you can divide array into
many parts.
array array_change_key_case ( array $array [, int $case =
CASE_LOWER ] ) Syntax

Example
array array_chunk ( array $array , int $size [, bool $preser
ve_keys = false ] )
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000", Example
"Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER)); <?php
?> $salary=array("Sonoo"=>"550000","Vimal"=>"250000",
"Ratan"=>"200000");
Output:
print_r(array_chunk($salary,2));
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] ?>
=> 200000 )
Output:
Example
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
<?php
[1] => Array ( [0] => 200000 )
$salary=array("Sonoo"=>"550000","Vimal"=>"250000", )
"Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_LOWER));
?>

33
4) PHP count() function <?php
$season=array("summer","winter","spring","autumn");
PHP count() function counts all elements in an array.
sort($season);
Syntax foreach( $season as $s )
{
int count ( mixed $array_or_countable [, int $mode = COUN echo "$s<br />";
T_NORMAL ] ) }
?>
Example
Output:
<?php
autumn
$season=array("summer","winter","spring","autumn"); spring
echo count($season); summer
?> winter

Output: 6) PHP array_reverse() function

4 PHP array_reverse() function returns an array containing


elements in reversed order.
5) PHP sort() function
Syntax
PHP sort() function sorts all the elements in an array.
array array_reverse ( array $array [, bool $preserve_keys
Syntax = false ] )

bool sort ( array &$array [, int $sort_flags = SORT_REGUL Example


AR ] )
<?php
Example $season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )

34
{ Output:

echo "$s<br />";


2
}
?> 8) PHP array_intersect() function

Output: PHP array_intersect() function returns the intersection of


two array. In other words, it returns the matching elements
autumn of two array.
spring
winter Syntax
summer

array array_intersect ( array $array1 , array $array2 [, ar


7) PHP array_search() function
ray $... ] )
PHP array_search() function searches the specified value in
an array. It returns key if search is successful. Example

Syntax <?php
$name1=array("sonoo","john","vivek","smith");
mixed array_search ( mixed $needle , array $haystack [, b $name2=array("umesh","sonoo","kartik","smith");
ool $strict = false ] ) $name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
Example
{
echo "$n<br />";
<?php
}
$season=array("summer","winter","spring","autumn");
?>
$key=array_search("spring",$season);
echo $key; Output:
?>
sonoo
smith

35
PHP String $str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
A PHP string is a sequence of characters i.e. used to store ?>
and manipulate text. There are 2 ways to specify string in
PHP.
Output:

o single quoted Hello text multiple line text within single quoted string
o double quoted Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string

Single Quoted PHP String


Note: In single quoted PHP strings, most escape
We can create a string in PHP by enclosing text in a single sequences and variables will not be interpreted. But,
quote. It is the easiest way to specify string in PHP. we can use single quote through \' and backslash
through \\ inside single quoted PHP strings.
<?php
$str='Hello text within single quote'; <?php
echo $str; $num1=10;
?> $str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quot
Output: ed string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
Hello text within single quote
echo "$str1 <br/> $str2 <br/> $str3";

We can store multiple line text, special characters and ?>


escape sequences in a single quoted PHP string.
Output:

<?php
trying variable $num1
$str1='Hello text trying backslash n and backslash t inside single quoted
multiple line string \n \t
text within single quoted string'; Using single quote 'my quote' and \backslash

$str2='Using double "quote" directly inside single quoted str


ing';

36
Double Quoted PHP String <?php
$str1="Hello text
In PHP, we can specify string through enclosing text within
multiple line
double quote also. But escape sequences and variables will
be interpreted using double quote PHP strings. text within double quoted string";
$str2="Using double \"quote\" with backslash inside double
<?php quoted string";
$str="Hello text within double quote"; $str3="Using escape sequences \n in double quoted string";
echo $str;
?> echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Output:
Hello text within double quote
Hello text multiple line text within double quoted string
Now, you can't use double quote directly inside double Using double "quote" with backslash inside double quoted
quoted string. string
Using escape sequences in double quoted string
<?php
In double quoted strings, variable will be interpreted.
$str1="Using double "quote" directly inside double quoted s
tring";
<?php
echo $str1;
$num1=10;
?>
echo "Number is: $num1";
?>
Output:

Parse error: syntax error, unexpected 'quote' (T_STRING) in Output:


C:\wamp\www\string1.php on line 2
Number is: 10
We can store multiple line text, special characters and
escape sequences in a double quoted PHP string.

37
PHP String Functions string strtoupper ( string $string )

PHP provides various string functions to access and Example


manipulate strings. A list of important PHP string functions
are given below.
<?php
1) PHP strtolower() function $str="My name is KHAN";
$str=strtoupper($str);
The strtolower() function returns string in lowercase letter. echo $str;
?>
Syntax
Output:
string strtolower ( string $string )
MY NAME IS KHAN
Example
3) PHP ucfirst() function
<?php
The ucfirst() function returns string converting first
$str="My name is KHAN";
character into uppercase. It doesn't change the case of
$str=strtolower($str); other characters.
echo $str;
?> Syntax

Output: string ucfirst ( string $str )

my name is khan Example

2) PHP strtoupper() function <?php


$str="my name is KHAN";
The strtoupper() function returns string in uppercase letter.
$str=ucfirst($str);
Syntax echo $str;
?>

38
Output: string ucwords ( string $str )

My name is KHAN
Example

4) PHP lcfirst() function


<?php
The lcfirst() function returns string converting first character $str="my name is Sonoo jaiswal";
into lowercase. It doesn't change the case of other $str=ucwords($str);
characters. echo $str;
?>
Syntax

Output:
string lcfirst ( string $str )
My Name Is Sonoo Jaiswal
Example
6) PHP strrev() function
<?php
$str="MY name IS KHAN"; The strrev() function returns reversed string.
$str=lcfirst($str);
Syntax
echo $str;
?>
string strrev ( string $string )
Output:
Example
mY name IS KHAN
<?php
5) PHP ucwords() function $str="my name is Sonoo jaiswal";
$str=strrev($str);
The ucwords() function returns string converting first echo $str;
character of each word into uppercase.
?>
Syntax

39
Output: The abs() function returns absolute value of given number.
It returns an integer value but if you pass floating point
lawsiaj oonoS si eman ym value, it returns a float value.

Syntax
7) PHP strlen() function
number abs ( mixed $number )
The strlen() function returns length of the string. Example

Syntax <?php
echo (abs(-7)."<br/>"); // 7 (integer)
int strlen ( string $string ) echo (abs(7)."<br/>"); //7 (integer)
echo (abs(-7.2)."<br/>"); //7.2 (float/double)
Example ?>

<?php Output:
$str="my name is Sonoo jaiswal";
7
$str=strlen($str); 7
echo $str; 7.2
?>
PHP Math: ceil() function
Output:
The ceil() function rounds fractions up.
24
Syntax
PHP Math
float ceil ( float $value )
PHP provides many predefined math constants and Example
functions that can be used to perform mathematical
<?php
operations.
echo (ceil(3.3)."<br/>");// 4
PHP Math: abs() function echo (ceil(7.333)."<br/>");// 8
echo (ceil(-4.8)."<br/>");// -4
?>

40
Output: <?php
echo (sqrt(16)."<br/>");// 4
4
8 echo (sqrt(25)."<br/>");// 5
-4 echo (sqrt(7)."<br/>");// 2.6457513110646
?>
PHP Math: floor() function
Output:
The floor() function rounds fractions down.
4
Syntax 5
float floor ( float $value ) 2.6457513110646

Example
PHP Math: decbin() function
<?php
echo (floor(3.3)."<br/>");// 3 The decbin() function converts decimal number into binary.
echo (floor(7.333)."<br/>");// 7 It returns binary number as a string.
echo (floor(-4.8)."<br/>");// -5
Syntax
?>
string decbin ( int $number )
Output: Example
<?php
3
echo (decbin(2)."<br/>");// 10
7
-5 echo (decbin(10)."<br/>");// 1010
echo (decbin(22)."<br/>");// 10110
PHP Math: sqrt() function ?>

The sqrt() function returns square root of given argument. Output:

Syntax 10
float sqrt ( float $arg ) 1010
10110
Example

41
PHP Math: dechex() function echo (decoct(22)."<br/>");// 26
?>
The dechex() function converts decimal number into
hexadecimal. It returns hexadecimal representation of given
Output:
number as a string.
2
Syntax 12
string dechex ( int $number ) 26
Example
PHP Math: base_convert() function
<?php
echo (dechex(2)."<br/>");// 2 The base_convert() function allows you to convert any base
echo (dechex(10)."<br/>");// a number to any base number. For example, you can convert
echo (dechex(22)."<br/>");// 16 hexadecimal number to binary, hexadecimal to octal, binary
to octal, octal to hexadecimal, binary to decimal etc.
?>
Syntax
Output:
string base_convert ( string $number , int $frombase , int $
2 tobase )
a
Example
16
<?php
PHP Math: decoct() function $n1=10;
echo (base_convert($n1,10,2)."<br/>");// 1010
The decoct() function converts decimal number into octal. It ?>
returns octal representation of given number as a string.
Output:
Syntax
string decoct ( int $number ) 1010
Example
PHP Math: bindec() function
<?php
echo (decoct(2)."<br/>");// 2 The bindec() function converts binary number into decimal.
echo (decoct(10)."<br/>");// 12

42
Syntax File: form1.html
number bindec ( string $binary_string ) <form action="welcome.php" method="get">
Example Name: <input type="text" name="name"/>

<?php <input type="submit" value="visit"/>

echo (bindec(10)."<br/>");// 2 </form>

echo (bindec(1010)."<br/>");// 10 File: welcome.php


echo (bindec(1011)."<br/>");// 11 <?php
?> $name=$_GET["name"];//receiving name field value in $na
me variable
Output: echo "Welcome, $name";
?>
2
10
11 PHP Post Form

Post request is widely used to submit form that have large


PHP Form Handling amount of data such as file upload, image upload, login
form, registration form etc.
We can create and use forms in PHP. To get form data, we
need to use PHP superglobals $_GET and $_POST.
The data passed through post request is not visible on the
URL browser so it is secured. You can send large amount of
The form request may be get or post. To retrieve data from data through post request.
get request, we need to use $_GET, for post request
$_POST. Let's see a simple example to receive data from post
request in PHP.
PHP Get Form
File: form1.html
Get request is the default form request. The data passed <form action="login.php" method="post">
through get request is visible on the URL browser so it is
not secured. You can send limited amount of data through <table>
get request. <tr><td>Name:</td><td> <input type="text" name="na
me"/></td></tr>
Let's see a simple example to receive data from get request <tr><td>Password:</td><td> <input type="password" na
in PHP.
me="password"/></td></tr>

43
<tr><td colspan="2"><input type="submit" value="login"/
> </td></tr>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $n
ame variable
$password=$_POST["password"];//receiving password field
value in $password variable

echo "Welcome: $name, your password is: $password";


?> PHP Include & Require

Output: PHP allows you to include file so that a page content can be
reused many times. There are two ways to include file in
PHP.

1. include
2. require

Advantage

Code Reusability: By the help of include and require


construct, we can reuse HTML code or PHP script in many
PHP scripts.

PHP include example

PHP include is used to include file on the basis of given


path. You may use relative or absolute path of the file. Let's
see a simple PHP include example.

44
File: menu.html
<a href="http://www.javatpoint.com/java-
tutorial">Java</a> |
<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/html-
<a href="http://www.javatpoint.com/php-
tutorial">HTML</a>
tutorial">PHP</a> | File: require1.php
<a href="http://www.javatpoint.com/java-
tutorial">Java</a> | <?php require("menu.html"); ?>
<a href="http://www.javatpoint.com/html- <h1>This is Main Page</h1>
tutorial">HTML</a>
File: include1.php Output:

<?php include("menu.html"); ?> Home | PHP | Java | HTML

<h1>This is Main Page</h1>


This is Main Page
Output:

Home | PHP | Java | HTML PHP include vs PHP require

If file is missing or inclusion fails, include allows the script


This is Main Page to continue but require halts the script producing a fatal
E_COMPILE_ERROR level error.

PHP require example


PHP Cookie
PHP require is similar to include. Let's see a simple PHP
require example. PHP cookie is a small piece of information which is stored at
client browser. It is used to recognize the user.
File: menu.html
Cookie is created at server side and saved to client browser.
Each time when client sends request to the server, cookie is
<a href="http://www.javatpoint.com">Home</a> |
embedded with request. Such way, cookie can be received
<a href="http://www.javatpoint.com/php- at the server side.
tutorial">PHP</a> |

45
2. setcookie("CookieName", "CookieValue", time()+1*60*60);
//using expiry in 1 hour(1*60*60 seconds or 3600 seconds)

3. setcookie("CookieName", "CookieValue", time()+1*60*60,


"/mypath/", "mydomain.com", 1);

PHP $_COOKIE

PHP $_COOKIE superglobal variable is used to get cookie.


In short, cookie can be created, sent and received at server
end.
Example

Note: PHP Cookie must be used before <html> tag. $value=$_COOKIE["CookieName"];//returns cookie value

PHP Cookie Example


PHP setcookie() function
File: cookie1.php
PHP setcookie() function is used to set cookie with HTTP
response. Once cookie is set, you can access it by
<?php
$_COOKIE superglobal variable.
setcookie("user", "Sonoo");
?>
Syntax <html>
<body>
bool setcookie ( string $name [, string $value [, int $expire <?php
if(!isset($_COOKIE["user"])) {
= 0 [, string $path
echo "Sorry, cookie is not found!";
[, string $domain [, bool $secure = false [, bool $httponly = } else {
false ]]]]]] ) echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
Example
</body>
</html>
1. setcookie("CookieName", "CookieValue");
/* defining name and value only*/

46
Output: PHP session creates unique user id for each browser to
recognize the user and avoid conflict between multiple
Sorry, cookie is not found! browsers.

Firstly cookie is not set. But, if you refresh the page, you
will see cookie is set now.

Output:

Cookie Value: Sonoo

PHP Delete Cookie

If you set the expiration date in past, cookie will be deleted.

File: cookie1.php PHP session_start() function

<?php PHP session_start() function is used to start the session. It


setcookie ("CookieName", "", time() - 3600); starts a new or resumes existing session. It returns existing
session if session is created already. If session is not
// set the expiration date to one hour ago
available, it creates and returns new session.
?>
Syntax
PHP Session
bool session_start ( void )
PHP session is used to store and pass information from one
page to another temporarily (until user close the website). Example

PHP session technique is widely used in shopping websites


where we need to store and pass cart information e.g. session_start();
username, product code, product name, product price etc
from one page to another.

47
PHP $_SESSION File: session2.php

PHP $_SESSION is an associative array that contains all <?php


session variables. It is used to set and get session variable session_start();
values.
?>

Example: Store information <html>


<body>

$_SESSION["user"] = "Sachin"; <?php


echo "User is: ".$_SESSION["user"];
Example: Get information ?>
</body>
echo $_SESSION["user"]; </html>

PHP Session Example PHP Session Counter Example

File: session1.php File: sessioncounter.php


<?php <?php
session_start(); session_start();
?>
<html> if (!isset($_SESSION['counter'])) {
<body> $_SESSION['counter'] = 1;
<?php } else {
$_SESSION["user"] = "Sachin"; $_SESSION['counter']++;
echo "Session information are set successfully.<br/>"; }
?> echo ("Page Views: ".$_SESSION['counter']);
<a href="session2.php">Visit next page</a> ?>
</body>
</html>

48
PHP Destroying Session Mode Description
r Opens file in read-only mode. It places the file pointer at
PHP session_destroy() function is used to destroy all session the beginning of the file.
variables completely. r+ Opens file in read-write mode. It places the file pointer at
the beginning of the file.
File: session3.php w Opens file in write-only mode. It places the file pointer to
<?php the beginning of the file and truncates the file to zero
session_start(); length. If file is not found, it creates a new file.
session_destroy(); w+ Opens file in read-write mode. It places the file pointer to
?> the beginning of the file and truncates the file to zero
length. If file is not found, it creates a new file.
a Opens file in write-only mode. It places the file pointer to
PHP File Handling the end of the file. If file is not found, it creates a new file.
a+ Opens file in read-write mode. It places the file pointer to
PHP File System allows us to create file, read file line by the end of the file. If file is not found, it creates a new file.
line, read file character by character, write file, append file, x Creates and opens file in write-only mode. It places the
delete file and close file. file pointer at the beginning of the file. If file is found,
fopen() function returns FALSE.
PHP Open File x+ It is same as x but it creates and opens file in read-
write mode.
PHP fopen() function is used to open file or URL and returns
c Opens file in write-only mode. If the file does not exist, it
resource. The fopen() function accepts two arguments:
$filename and $mode. The $filename represents the file to is created. If it exists, it is neither truncated (as opposed
be opended and $mode represents the file mode for to 'w'), nor the call to this function fails (as is the case
example read-only, read-write, write-only etc. with 'x'). The file pointer is positioned on the beginning of
the file
Syntax c+ It is same as c but it opens file in read-write mode.

resource fopen ( string $filename , string $mode [, bool PHP Open File Example
$use_include_path = false [, resource $context ]] )
<?php
PHP Open File Mode: $handle = fopen("c:\\folder\\file.txt", "r");
?>

49
PHP Read File
$contents = fread($fp, filesize($filename));//read file
PHP provides various functions to read data from file. There
are different functions that allow you to read all file data,
read data line by line and read data character by character. echo "<pre>$contents</pre>";//printing data of file
fclose($fp);//close file
The available PHP file read functions are given below.
?>
o fread()
Output
o fgets()
this is first line
o fgetc()
this is another line
this is third line
PHP Read File - fread()
PHP Read File - fgets()
The PHP fread() function is used to read data of the file. It
requires two arguments: file resource and file size.
The PHP fgets() function is used to read single line from the
file.
Syntax
Syntax
string fread (resource $handle , int $length )
string fgets ( resource $handle [, int $length ] )
$handle represents file pointer that is created by fopen()
function.
Example
$length represents length of byte to be read.
<?php
Example: $fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
<?php fclose($fp);
$filename = "c:\\file1.txt";
?>
$fp = fopen($filename, "r");//open file in read mode

50
Output PHP Write File
this is first line PHP fwrite() and fputs() functions are used to write data
into file. To write data into file, you need to use w, r+, w+,
PHP Read File - fgetc() x, x+, c or c+ mode.

The PHP fgetc() function is used to read single character PHP Write File - fwrite()
from the file. To get all data using fgetc() function, use
!feof() function inside the while loop. The PHP fwrite() function is used to write content of the
string into file.
Syntax
Syntax

string fgetc ( resource $handle )


int fwrite ( resource $handle , string $string [, int $length ])
Example:
Example

<?php
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
$fp = fopen('data.txt', 'w');//opens file in write-only mode
while(!feof($fp)) {
fwrite($fp, 'welcome ');
echo fgetc($fp);
fwrite($fp, 'to php file write');
}
fclose($fp);
fclose($fp);
?>
echo "File written successfully";
Output ?>

this is first line this is another line this is third line Output: data.txt

welcome to php file write

51
PHP Overwriting File PHP Append to File - fwrite()

If you run the above code again, it will erase the previous The PHP fwrite() function is used to write and append data
data of the file and writes the new data. Let's see the code into file.
that writes only new data into data.txt file.
Example
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode <?php

fwrite($fp, 'hello'); $fp = fopen('data.txt', 'a');//opens file in append mode

fclose($fp); fwrite($fp, ' this is additional text ');


fwrite($fp, 'appending data');

echo "File written successfully"; fclose($fp);

?>
echo "File appended successfully";
Output: data.txt ?>

hello Output:

PHP Append to File data.txt


welcome to php file write this is additional text appending
You can append data into file by using a or a+ mode in data
fopen() function. Let's see a simple example that appends
data into data.txt file.
PHP Delete File
Let's see the data of file first.
In PHP, we can delete any file using unlink() function. The
unlink() function accepts one argument only: file name. It is
data.txt
similar to UNIX C unlink() function.

welcome to php file write PHP unlink() generates E_WARNING level error if file is not
deleted. It returns TRUE if file is deleted successfully
otherwise FALSE.

52
Syntax PHP $_FILES

bool unlink ( string $filename [, resource $context ] ) The PHP global $_FILES contains all the information of file.
By the help of $_FILES global, we can get file name, file
type, file size, temp file name and errors associated with
$filename represents the name of the file to be deleted.
file.

PHP Delete File Example Here, we are assuming that file name is filename.

<?php $_FILES['filename']['name']
$status=unlink('data.txt');
returns file name.
if($status){
echo "File deleted successfully"; $_FILES['filename']['type']
}else{
returns MIME type of the file.
echo "Sorry!";
}
$_FILES['filename']['size']
?>
returns size of the file (in bytes).
Output
$_FILES['filename']['tmp_name']
File deleted successfully
returns temporary file name of the file which was stored on
PHP File Upload the server.

PHP allows you to upload single and multiple files through $_FILES['filename']['error']
few lines of code only.
returns error code associated with this file.
PHP file upload features allows you to upload binary and
text files both. Moreover, you can have the full control over
the file to be uploaded through PHP authentication and file
operation functions.

53
move_uploaded_file() function if(move_uploaded_file($_FILES['fileToUpload']['tmp_name']
, $target_path)) {
The move_uploaded_file() function moves the uploaded file
to a new location. The move_uploaded_file() function echo "File uploaded successfully!";
checks internally if the file is uploaded thorough the POST } else{
request. It moves the file if it is uploaded through the POST
request. echo "Sorry, file not uploaded, please try again!";
}
Syntax ?>

bool move_uploaded_file ( string $filename , string $destina


tion )
PHP Mail
The PHP mail() Function
PHP File Upload Example
Sending email messages are very common for a web
File: uploadform.html application, for example, sending welcome email when a
user create an account on your website, sending
<form action="uploader.php" method="post" enctype= newsletters to your registered users, or getting user
"multipart/form-data"> feedback or comment through website's contact form, and
Select File: so on.
You can use the PHP built-in mail () function for creating
<input type="file" name="fileToUpload"/> and sending email messages to one or more recipients
<input type="submit" value="Upload Image" name= dynamically from your PHP application either in a plain-text
form or formatted HTML. The basic syntax of this function
"submit"/> can be given with:
</form> mail (to, subject, message, headers, parameters)
File: uploader.php The following table summarizes the parameters of this
<?php function.
Parameter Description
$target_path = "e:/"; Required — The following parameters are required
$target_path = $target_path.basename( $_FILES to The recipient's email address.
subject Subject of the email to be sent. This
['fileToUpload']['name']);
parameter i.e. the subject line cannot
contain any newline character (\n).

54
message Defines the message to be sent. Each line
should be separated with a line feed-LF
(\n). Lines should not exceed 70 characters. Sending HTML Formatted Emails
Optional — The following parameters are optional
headers This is typically used to add extra headers When you send a text message using PHP, all the content
such as "From", "Cc", "Bcc". The additional will be treated as simple text. We're going to improve that
headers should be separated with a carriage output, and make the email into a HTML-formatted email.
return plus a line feed-CRLF (\r\n). To send an HTML email, the process will be the same.
parameters Used to pass additional parameters. However, this time we need to provide additional headers as
well as an HTML formatted message.
Sending Plain Text Emails
The simplest way to send an email with PHP is to send a <?php
text email. In the example below we first declare the $to = 'maryjane@email.com';
variables — recipient's email address, subject line and $subject = 'Marriage Proposal';
message body — then we pass these variables to $from = 'peterparker@email.com';
the mail() function to send the email.
// To send HTML mail, the Content-type header must be set
<?php
$headers = 'MIME-Version: 1.0' . "\r\n";
$to = 'maryjane@email.com';
$headers .= 'Content-type: text/html; charset=iso-8859-1'
$subject = 'Marriage Proposal';
. "\r\n";
$message = 'Hi Jane, will you marry me?';
$from = 'peterparker@email.com';
// Create email headers
$headers .= 'From: '.$user_email."\r\n".
// Sending email
'Reply-To: '.$user_email."\r\n" .
if(mail($to, $subject, $message)){
'X-Mailer: PHP/' . phpversion();
echo 'Your mail has been sent successfully.';
} else{
// Compose a simple HTML email message
echo 'Unable to send email. Please try again.';
$message = '<html><body>';
}
$message .= '<h1 style="color:#f40;">Hi Jane!</h1>';
?>
$message .= '<p style="color:#080;font-size:18px;">Will
you marry me?</p>';
$message .= '</body></html>';

// Sending email

55
if(mail($to, $subject, $message, $headers)){ Function Description
echo 'Your mail has been sent successfully.';
} else{ date_diff() Returns the difference between
echo 'Unable to send email. Please try again.'; two dates
} date_format() Returns a date formatted
?> according to a specified format
date_get_last_errors() Returns the warnings and
errors found while parsing a
date/time string
PHP Date and Time Functions
date_interval_create_from Sets up a DateInterval from
The following date and time functions are the part of the _date_string() the relative parts of the string
PHP core so you can use these functions within your script
without any further installation. date_interval_format() Formats the interval
date_isodate_set() Set a date according to the ISO
Function Description 8601 standard
checkdate() Validates a Gregorian date date_modify() Modifies the timestamp
date_add() Adds an amount of days, date_offset_get() Returns the timezone offset
months, years, hours, minutes
and seconds to a date date_parse_from_format() Returns an associative array
with detailed info about given
date_create_from_format( Returns a new DateTime object date formatted according to the
) formatted according to the specified format
specified format
date_parse() Returns associative array with
date_create() Returns new DateTime object detailed info about a specified
date
date_date_set() Sets a new date
date_sub() Subtracts an amount of days,
date_default_timezone_ge Returns the default timezone months, years, hours, minutes
t() used by all date/time functions and seconds from a date
in a script
date_sun_info() Returns an array with
date_default_timezone_se Sets the default timezone used information about
t() by all date/time functions in a sunset/sunrise and twilight
script begin/end for a specified day
and location

56
57

Você também pode gostar