SlideShare a Scribd company logo
1 of 85
Download to read offline
1 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
HTTP
HTTP stands for HyperText Transfer Protocol. This is a basis for data communication in the
internet. The data communication starts with a request sent from a client and ends with the
response received from a web server.
• A website URL starting with “http://” is entered in a web browser from a computer (client). The
browser can be a Chrome, Firefox, Edge, Safari, Opera or anything else.
• Browser sends a request sent to the web server that hosts the website.
• The web server then returns a response as a HTML page or any other document format to the
browser.
• Browser displays the response from the server to the user.
HTTP Request
A simple request message from a client computer consists of the following components:
• A request line to get a required resource,
• Number of Headers lines
• An empty line.
• A message body which is optional.
HTTP Response
A simple response from the server contains the following components:
• HTTP Status Code
• Number of Headers lines
• An empty line.
• A message body which is optional.
Web server
A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that
form Web pages to users, in response to their requests, which are forwarded by their computers'
HTTP clients
2 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Name of web server
1 Apache HTTP Server
2. Internet Information Services
3. Sun Java System Web Server
4.NGINX
5. Node.js
Name of Web browser
Chrome, Firefox, Edge, Safari, Opera, internet explorer
What is PHP?
• PHP means " Hypertext Preprocessor"
• PHP is cross platform ,HTML embedded & server side web scripting language
cross platform=> PHP runs on many operating system such as windows,UNIX etc.
HTML embedded=>It can take a standard HTML page, drop in some PHP whenever
need & end up with a dynamic result.
Server Side=>PHP run on server such as apache,IIS etc
3 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
web scripting language=>It is used to write web script, not stand alone application.(PHP
programs are executed through web server)
Feature of PHP
• PHP can generate dynamic page content
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• It is open source.
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP is easy to learn and runs efficiently on the server side
• PHP code can written in a procedure or object oriented manner.
• PHP supports a wide range of databases
Lexical Structure
The lexical structure of a programming language is the set of basic rules that governs how you
write programs in that language. It is the lowest-level syntax of the language and specifies such
things as what variable names look like, what characters are used for comments, and how
program statements are separated from each other.
Basic PHP Syntax
<?php
// PHP code goes here
?>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
It can insert HTML tag in PHP
<html>
<body>
<?php
echo "<b>Hello World!</b>";
4 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
?>
</body>
</html>
Comments in PHP
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive. But variables are case sensitive
PHP variable
Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo "String is $txt";
echo "Integer is $x";
5 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
echo "float is $y";
?>
Data type in PHP
• Integers: are whole numbers, without a decimal point, like 4195.
• float: are floating-point numbers, like 3.14159 or 49.1.
• Booleans: have only two possible values either true or false.
• NULL: is a special type that only has one value: NULL.
• Strings: are sequences of characters, like 'PHP supports string operations.'
• Arrays: are named and indexed collections of other values.
• Objects: are instances of programmer-defined classes,
• Resources: are special variables that hold references to resources external to PHP (such
as database connections, image).
PHP Constant
A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Where
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-insensitive. Default
is false
<?php
define("PI", 3.14);
echo PI;
?>
Variables variable
6 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
It can reference the value of variable
whose name is stored in another variable
<?php
$a='hello';
$$a='world';
echo $a;
echo $$a;
?>
o/p
hello
world
Type Juggling
PHP does not require (or support) explicit type definition in variable declaration, a variable's
type is determined by the context in which the variable is used.
The conversion of value from one type to another is called casting.
This kind of implicit casting is called type juggling.
<?php
$x="9hello"-1;
echo $x;
$y="3.14 pile"*2;
echo $y;
?>
o/p
8
6.28
Operators
1.Arithmetic Operators
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
7 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
2.Comparison Operators
Operator Name Example Result
==
Equal $x == $y
Returns true if $x is equal
to $y
$x = 100;
$y = "100";
$x == $y
=>true(Because values
are equal)
===
Identical $x === $y
Returns true if $x is equal
to $y, and they are of the
same type
$x = 100;
$y = "100";
$x === $y
=>false(Because types
are not same)
!=
Not equal $x != $y
Returns true if $x is not
equal to $y
$x = 100;
$y = "100";
$x != $y
=>false(Because values
are equal)
<>
Not equal $x <> $y
Returns true if $x is not
equal to $y
$x = 100;
$y = "100";
$x <> $y
=>false(Because values
are equal)
8 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
!==
Not identical $x !== $y
Returns true if $x is not
equal to $y, or they are not
of the same type
$x = 100;
$y = "100";
$x !== $y
=>true(Because types are
not equal)
>
Greater than $x > $y
Returns true if $x is greater
than $y
<
Less than $x < $y
Returns true if $x is less
than $y
>= Greater than or
equal to
$x >= $y
Returns true if $x is greater
than or equal to $y
<= Less than or
equal to
$x <= $y
Returns true if $x is less
than or equal to $y
3.Logical operator
Operator Name Example Result
And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y
True if either $x or $y is true, but
not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
4.Assignment operator
Assignment Same as... Description
x = y x = y
The left operand gets set to the value of the
expression on the right
9 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
5.Increment / Decrement Operators
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
6.PHP String Operators
PHP has two operators that are specially designed for strings.
OperatorName Example Result
. Concatenation $txt1 . $txt2
Concatenation of $txt1 and
$txt2
S $txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;how it
»O/P Hello world!
.=
Concatenation
assignment
$txt1 .= $txt2 Appends $txt2 to $txt1
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 .= $txt2;
O/P Hello world!
10 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Conditional Statements
1. if Statement
if (condition)
{
code to be executed if condition is true;
}
2.if...else Statement
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
3. if...elseif....else Statement
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
4. switch Statement
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from
all labels;
}
Loop
1.while Loop
Syntax
while (condition is true)
{
code to be executed;
}
e.g
<?php
$x = 1;
2.do...while Loop
Syntax
do
{
code to be executed;
} while (condition is true);
e.g
11 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
while($x <= 3)
{
echo "The number is: $x <br>";
$x++;
}
?>
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 3);
?>
3.for Loop
Syntax
for (init counter; test counter; increment
counter)
{
code to be executed;
}
e.g
<?php
for ($x = 0; $x <= 3; $x++)
{
echo "The number is: $x <br>";
}
?>
There are two ways the browser client can send information to the web server.
• The GET Method
• The POST Method
GET POST
The GET method sends the encoded user information appended to
the page request. The page and the encoded information are
separated by the ? character.e.g
http://www.test.com/index.htm?name1=value1&name2=value2
he POST method transfers
information via HTTP
headers.e.g
http://www.test.com/index.htm
It is by default method It is not by default method
12 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
The GET method is restricted to send upto 1024 characters only. The POST method does not
have any restriction on data size
to be sent.
GET method is not used for password or other sensitive
information to be sent to the server.
POST method is used for
password or other sensitive
information to be sent to the
server.
GET can't be used to send binary data to the server. POST can be used to send
binary data to the server.
1.$_GET
1.It is global array that collect information from HTML form.
2.It is used to accept values from an html form sent with method is
“get”.
<html>
<body>
<form name=”frm” method=”get”
action="http://localhost/b.php">
Enter value
<input type=text name=t1>
<input type="submit" name=b1
value=OK>
</form>
</body>
</html>
<?php
$a=$_GET['t1'];
echo $a;
?>
2.$_POST
1.It is global array that collect information from HTML form.
2.It is used to accept values from an html form sent with method is
“post”.
<html>
<body>
<form name=”frm” method=”post”
action="http://localhost/b.php">
<?php
$a=$_POST['t1'];
echo $a;
?>
13 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Enter value
<input type=text name=t1>
<input type="submit" name=b1
value=OK>
</form>
</body>
</html>
Functions
User Defined Functions
A function is a block of statements that can be used repeatedly in a program.
A function will be executed by a call to the function
Create a User Defined Function
Syntax
function functionName()
{
code to be executed;
}
<?php
function display()
{
echo "Hello world!";
}
display(); // call the function
?>
14 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
PHP Function Arguments
1.
<?php
function add($a,$b)
{
$c=$a+$b;
echo "Addition is $c<br>";
}
add(2,3);
?>
2.
<?php
function display($fname, $year)
{
echo "fname is $fname<br>";
echo "year is $year<br>";
}
display("vision",2004);
?>
Returning values
<?php
function add($a,$b)
{
$c=$a+$b;
return $c;
}
$c=add(2,3);
echo "Addition is $c";
?>
Variables Scope
15 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
PHP has three different variable scopes:
• local
• global
• static
1.Global
A variable declared outside a function has a GLOBAL SCOPE
They can be access from any part of the program.
The global keyword is used to access a global variable from within a function
<?php
$x = 5;
$y = 10;
function add()
{
global $x, $y;
$y = $x + $y;
}
add();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable.
<?php
$x = 5;
$y = 10;
function add()
{
16 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
}
add();
echo $y; // outputs 15
?>
2.Local
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function
<?php
function display()
{
$y=5;
echo $y;
}
display();
?>
3.Static
A static variable retains the value between calls to a function but it is visible only within that
function
<?php
function display()
{
static $x=0;
echo $x;
$x++;
}
display ();
display ();
display ();
?>
17 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Default Argument Value
<?php
function add($a,$b=4)
{
$c=$a+$b;
echo "Addition is $c<br>";
}
add(2);
?>
Variable-length argument lists(Variable parameter)
PHP 4 and above has support for variable-length argument lists in user-defined functions.
PHP provide 3 function
intfunc_num_args ( )
Returns the number of arguments passed into the current user-defined function.
array func_get_args ( )
It return array of all parameter provided to the function.
mixedfunc_get_arg ( int arg_num)
It return a specific argument from the parameter.
<?php
function display()
{
for($i=0;$i<func_num_args();$i++)
{
echo func_get_arg($i);
}
}
18 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
display(1,2,3);
?>
Variable functions
PHP supports the concept of variable functions. This means that if a variable name has
parentheses appended to it, PHP will look for a function with the same name as whatever the
variable evaluates to, and will attempt to execute it.
<?php
function disp1()
{
echo "disp1 fuction <br>";
}
function disp2($arg)
{
echo "disp2 function $arg";
}
$func = 'disp1';
$func();
$func = 'disp2';
$func("hello");
?>
Anonymous functions
PHP allows programmer to write the function without name is called anonymous.
To create anonymous function create_function is used
Syntax
stringcreate_function ( string$args , string$code )
19 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
<?php
$newfunc = create_function('$a,$b', 'return ($a + $b);');
echo $newfunc(2, 3);
?>
Missing Parameter
when you call a function, you can pass any number of arguments to the function. Any parameters
the function that are not passed to it remain unset, and a warning is issued for each of them
<?php
function show( $a, $b )
{
if (isset($a))
echo " a is set";
if (isset($b))
echo " b is set";
}
show(2);
?>
o/p
warning :missing argument two
a is set
String
A string type can be specified in 3 different ways:
1 single quoted
2 double quoted
3 heredoc
1 Single quoted String
PHP support the strings to be enclosed in single quotes.Single quoted string do not interpolate
variables.The variables name in the string is not expanded except escape sequence character.
20 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
<?php
$a=5;
echo 'Value is $a';
?>
o/p
value is $a
2.Double quoted string
Double quoted strings interpolate variables and expand the many PHP escape sequences.
<?php
$a=5;
echo “Value is $a”;
?>
o/p
value is 5
3. using heredoc
Single quoted & double quoted string allow strings in single line. To write multiline strings into
the program a heredoc is used.
The <<< identifier is used in PHP,to tell the language that the string is written with heredoc.
The space before after the <<< is essential. The text starts on the second line & continue until it
reaches a line that consist of nothing but identifier
<?php
$a= <<<ed
It is php
It is server script
ed;
echo $a;
21 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
?>
Printing String
1. echo
The echo() allow to print many strings.
Syntax
echo(strings)
<?php
$str1="Hello world!";
$str2="What a nice day!";
echo $str1 . "" . $str2;
?>
2.print
The print() allow to print one or more strings.
Syntax
print(strings)
<?php
$str1="Hello world!";
$str2="What a nice day!";
print $str1 . "" . $str2;
?>
Note:The print() function is slightly slower than echo().
3.printf
The printf() function outputs a formatted string.
It is similar to printf() function in c Language.
22 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
%d - Signed decimal number (negative, zero or positive)
%f - Floating-point number (local settings aware)
%s - String
Syntax
printf(format,arg1,arg2,arg++)
<?php
$name="amol";
$age=18;
printf("name is %s",$name);
printf("age is %d",$age);
?>
4.print_r
The print_r() debugging function used to print human-readable information about a variable.
Syntax
Return value print_r(expression)
Where
Expression=>The expression to be printed
Return value=>To capture the output in a variable, parameter should set TRUE. Default value is
FALSE.
<?php
$name="amol";
print_r($name);
?>
o/p
amol
<?php
23 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
$a = array('name'=>'amol','class'=>'ty');
print_r($a);
?>
o/p
Array ( [name] => amol [class] => ty )
5.var_dump()
The var_dump()debugging function is used to display structured information (type and value)
about one or more variables
Syntax
var_dump(variable1);
<?php
$a=4;
$b=1.5;
echo var_dump($a);
echo var_dump($b);
?>
o/p
int 4
float 1.5
<?php
$a = array('name'=>'amol','class'=>'ty');
echo var_dump($a);
?>
o/p
array
'name' => string 'amol'(length=4)
'class' => string 'ty'(length=2)
24 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Difference var_dump & print_r
1.The var_dump() function displays structured information (type and value) about one or more
variables.
2.The print_r() function displays human-readable information about a variable.
3.print_r function loops infinitely while var_dump cuts off after visiting the same element three
times
Array in php
Array: An array is a data structure that stores one or more similar type of values in a single
value.
1.Single dimension array
PHP array type
1.Indexed array - An array with a numeric index. Values are stored and accessed in linear
fashion.index always start with 0
Display array without
using array function
Displaying array using
loop(using array function)
Displaying array using print_r
<?php
$a[0] = 1;
$a[1] = 2;
$a[2] = 3;
print_r($a)
?>
o/p
Array ( [0] => 1 [1] => 2
[2] => 3 )
<?php
$a = array(1,2,3);
$len = count($a);
for($i = 0; $i < $len; $i++)
{
echo $a[$i];
echo "<br>";
}
?>
o/p
1
2
3
<?php
$a = array(1,2,3);
print_r($a);
?>
o/p
Array ( [0] => 1 [1] => 2 [2] => 3 )
2.Associative Array:An array with a string index(key)
25 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Display array without
using array function
Display array using array
function & foreach loop
Displaying array using print_r
<?php
$a['rollno'] = "1";
$a['name’] = "amol";
$a['class'] = “ty”;
print_r($a);
?>
o/p
Array ( [rollno] => 1
[name] => amol [class]
=> ty)
<?php
$a = array("rollno"=>"1",
"name"=>"amol",
"class"=>"ty");
foreach($a as $x => $val)
{
echo "Key=" . $x ;
echo " Value=".$val;
echo "<br>";
}
?>
o/p
Key=rollno Value=1
Key=name Value=amol
Key=class Value=ty
<?php
$a = array("rollno"=>"1",
"name"=>"amol", "class"=>"ty");
print_r($a);
?>
o/p
Array ( [rollno] => 1 [name] =>
amol [class] => ty)
Traversing Array in php
1 Using foreach loop
Syntax
foreach ($array as$value)
{
// code
}
Numeric index array Associative array
<?php
$colors = array("red", "green", "blue",
"yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
o/p
red
green
<?php
$a = array("rollno"=>"1", "name"=>"amol",
"class"=>"ty");
foreach($a as $x => $val)
{
echo "Key=" . $x ;
echo " Value=".$val;
echo "<br>";
}
?>
26 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
yellow o/p
Key=rollno Value=1
Key=name Value=amol
Key=class Value=ty
2.Using loop(while or for loop)
<?php
$a = array(1,2,3);
$len = count($a);
for($i = 0; $i < $len; $i++)
{
echo $a[$i];
echo "<br>";
}
?>
o/p
1
2
3
3.Using iterator function
1.current():Returns the element currently pointed by the iterstor
2.next():Moves the iterator to the next element in the array & return it.
3.prev():Moves the iterator to the previous element in the array & return it.
4.reset():Moves the iterator to the first element in the array & return it.
5.end():Moves the iterator to the end element in the array & return it.
<?php
$colors = array("red", "green", "blue", "yellow");
echo "<br> current element".current($colors);
echo "<br> next element".next($colors);
echo "<br> prevous element".prev($colors);
echo "<br> reset element".reset($colors);
echo "<br> end element".end($colors);
?>
27 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
2.Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
2D array
1.Indexed array
Display array without using
array function
Display array using array
function
Display array using
print_r function
<?php
$a[0][0]=1;
$a[0][1]=2;
$a[1][0]=33;
$a[1][1]=22;
for($i=0;$i<count($a);$i++)
{
for($j=0;$j<count($a[$i]);$j++)
{
echo $a[$i][$j]."<br>";
}
}
?>
<?php
$a=array(array(1,2),
array(33,22));
for($i=0;$i<count($a);$i++)
{
for($j=0;$j<count($a[$i]);$j++)
{
echo $a[$i][$j]."<br>";
}
}
?>
<?php
$a=array(array(1,2),
array(33,22));
print_r($a);
?>
o/p
Array ( [0] => Array ( [0]
=> 1 [1] => 2 ) [1] =>
Array ( [0] => 33 [1] =>
22 ) )
Display array using foreach
<?php
$a=array(array(1,2),
array(33,22));
$a=array(array(1,2),
array(33,22));
foreach($a as $v1)
{
foreach($v1 as $v2)
{
echo $v2."<br>";
}
}
?>
28 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
2.Associative Array
Display array using
array function
Display array using print_r function
<?php
$a=array(
array("rollno"=>"1",
"name"=>"amol",
"class"=>"ty"),
array("rollno"=>"2",
"name"=>"amit",
"class"=>"ty"),
);
for($i=0;$i<2;$i++)
{
foreach($a[$i] as
$key=>$val)
{
echo $val;
}
echo "<br>";
}
?>
<?php
$a=array(
array("rollno"=>"1", "name"=>"amol",
"class"=>"ty"),
array("rollno"=>"2", "name"=>"amit",
"class"=>"ty"),
);
print_r($a);
?>
o/p
Array ( [0] => Array ( [rollno] => 1
[name] => amol [class] => ty ) [1] =>
Array ( [rollno] => 2 [name] => amit
[class] => ty ) )
Sorting Array
1.Sort 2.rsort 3.asort
The sort() function sorts an indexed
array in ascending order.
<?php
$a=array(4,6,2,);
sort($a);
print_r($a);
?>
o/p
Array ( [0] => 2 [1] => 4 [2] => 6 )
The rsort() function sorts an indexed
array in descending order.
<?php
$a=array(4,6,2);
rsort($a);
print_r($a);
?>
o/p
Array ( [0] => 6 [1] => 4 [2] => 2 )
Sort an associative array in
order, according to the valu
<?php
$a=array("amol"=>"16","a
asort($a);
print_r($a);
?>
o/p
Array ( [amit] => 13 [amol
4.ksort 5.arsort 6.krsort
29 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Sort an associative array in ascending
order, according to the key
<?php
$a=array("amol"=>"13","amit"=>"16");
ksort($a);
print_r($a);
?>
o/p
Array ( [amit] => 16 [amol] => 13 )
Sort an associative array in descending
order, according to the value
<?php
$a=array("amol"=>"11","amit"=>"14");
arsort($a);
print_r($a);
?>
o/p
Array ( [amit] => 14 [amol] => 11 )
Sort an associative array in
order, according to the key
<?php
$a=array("amol"=>"13","a
krsort($a);
print_r($a);
?>
o/p
Array ( [amol] => 13 [amit
array_multisort()
array_multisort() function is used to sort multiple arrays
Syntax
array_multisort(array1,array2,array3...)
<?php
$a1=array("Dog","Cat");
$a2=array("Fido","Missy");
array_multisort($a1,$a2);
print_r($a1);
print_r($a2);
?>
o/p
Array ( [0] => Cat [1] => Dog )
Array ( [0] => Missy [1] => Fido )
30 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Converting between array &variables
Creating variable from a array Creating array from variable
1.extract 2.Compact
This function atomically creates local variable
from a array
Syntax
extract(arrayname)
<?php
$a = array("rollno"=>"1", "name"=>"amol",
"class"=>"ty");
extract($a);
echo $rollno;
echo $name;
echo $class;
?>
o/p 1 amol ty
It Create an array from variables
Syntax
compact(var1,var2...)
<?php
$rollno = 1;
$name = "amol";
$a = compact("rollno","name");
print_r($a)
?>
o/p
Array ( [rollno] => 1 [name] => amol )
Adding & Removing array function
1.Array_push() 2.Array_pop()
The array_push() function inserts one or
more elements to the end of an array.
Syntax
array_push(array,value1,value2...)
The array_pop() function deletes the last element of an array.
Syntax
array_pop(array)
<?php
31 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
<?php
$a=array("red");
array_push($a,"yellow");
print_r($a);
?>
o/p
Array ( [0] => red [1] => yellow )
$a=array("red","yellow");
array_pop($a);
print_r($a);
?>
o/p
Array ( [0] => red )
3.array_filter() 4.array_splice()
The array_filter() function filters the
values of an array using a callback
function
Syntax
array_filter(array,callbackfunction);
<?php
function test_odd($var)
{
if($var%2!=0)
return(1);
}
$a1=array(2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
o/p
3
It removes selected elements from an array and replaces it with
new elements. The function also returns an array with the
removed elements.
Syntax
array_splice(array,start,length,array)
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
o/p
Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
5.Array_flip() 6.shuffle
The array_flip() function
flips/exchanges all keys with their
associated values in an array
Syntax
array_flip(array);
<?php
The shuffle() function randomizes the order of the elements in the
array.
Syntax
shuffle(array)
<?php
32 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
$a1=array("a"=>"red","b"=>"green");
$result=array_flip($a1);
print_r($result);
?>
o/p
"c"=>"blue","d"=>"yellow"
$my_array = array("a"=>"red","b"=>"green");
shuffle($my_array);
print_r($my_array);
?>
o/p
Array ( [0] => green [1] => red )
7.count 8.array_merge
The count() function returns the number
of elements in an array
<?php
$cars=array("green","red");
echo count($cars);
?>
o/p
2
The array_merge() function merges one or more arrays into one
array.
Syntax
array_merge(array1,array2,array3...)
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
o/p
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
9.array_intersect 10 array_diff
The array_intersect() function compares
the values of two (or more) arrays, and
returns the matches.
Syntax
array_intersect(array1,array2,array3...);
<?php
$a1=array("red","yellow");
$a2=array("blue","yellow");
print_r(array_intersect($a1,$a2));
?>
Array ( [1] => yellow )
The array_diff() function compares the values of two (or more)
arrays, and returns the differences.
Syntax
array_diff(array1,array2,array3...);
<?php
$a1=array("red","yellow");
$a2=array("blue","yellow");
print_r(array_diff($a1,$a2));
?>
o/p
Array ( [0] => red )
11 array_shift 12 array_unshift
The array_shift() function removes the
first element from an array, and returns
the value of the removed element.
The array_unshift() function inserts new elements to an array. The
new array values will be inserted in the beginning of the array.
33 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Syntax
array_shift(array)
<?php
$a=array("red","green","blue");
echo array_shift($a);
print_r ($a);
?>
o/p
red
Array ( [0] => green [1] => blue )
Syntax
array_unshift(array,value1,value2,value3...)
<?php
$a=array("red","green");
array_unshift($a,"blue");
print_r($a);
?>
o/p
Array ( [0] => blue [1] => red [2] => green )
Union
<?php
$a1=array("red","green");
$a2=array("red","yellow");
$m=array_merge($a1,$a2));
$u=array_unique($m);
print_r($u);
?>
34 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
COMPARING FUNCTION
1.EXACT COMPRISION
1.strcmp()
Compare two strings (case-sensitive) &This
function returns following result:
• 0 - if the two strings are equal
• <0 - if string1 is less than string2
• >0 - if string1 is greater than string2
Syntax
strcmp(string1,string2);
<?php
echo strcmp("Hello","Hello");
?>
o/p 0
2. strcasecmp()
The strcasecmp() function compares two
strings but case-insensitive & return below
result
• 0 - if the two strings are equal
• <0 - if string1 is less than string2
• >0 - if string1 is greater than string2
Syntax
strcasecmp(string1,string2);
<?php
echo strcasecmp("Hello","hello");
?>
o/p
0
3. strncmp()(case sensitive)
Strings comparison of first n characters(case
sensitive) &This function returns following
result:
4.strncasecmp()
String comparison of the first n characters
(case-insensitive) insensitive & return below
result
35 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
2. APPROXIMATE EQUALITY
1.soundex()
2.metaphone()
3.similar_text()
This function see whether two
strings are approximate equal in
their pronunciation.
metaphone() is more accurate
than soundex(), because
metaphone() knows the basic
rules of English pronunciation
syntax
soundex(string)
metaphone(string)
<?php
$v1=”no”;
$v2=”know”;
If(soundex($v1)==soundex($v2))
The similar_text() function calculates the similarity between
two strings.
It can also calculate the similarity of the two strings in
percent
Syntax.
similar_text(string1,string2,percent)
Parameter Description
string1
Required. Specifies the first string to be
compared
string2
Required. Specifies the second string to be
compared
• 0 - if the two strings are equal
• <0 - if string1 is less than string2
• >0 - if string1 is greater than string2
Syntax
strncmp(string1,string2,length)
<?php
echo strncmp("Hello","Hello",2);
?>
o/p
0
• 0 - if the two strings are equal
• <0 - if string1 is less than string2
• >0 - if string1 is greater than string2
Syntax
strncmp(string1,string2,length)
<?php
echo strncasecmp("Hello world!","hello
earth!",6);
?>
o/p
0
36 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
echo “$v1 sound $v2 using
soundex”;
else
echo “$v1 not sound $v2 using
soundex”;
echo "<br>";
If(metaphone ($v1)==
metaphone ($v2))
echo “$v1 sound $v2 using
metapone”;
else
echo “$v1 not sound $v2 using
metaphone”;
?>
o/p
percent
Optional. Specifies a variable name for
storing the similarity in percent
Return
Value:
Returns the number of matching characters of
two strings
<?php
$c=similar_text("Hello World","HelloPeter",$percent);
echo $percent;
echo $c;
?>
o/p
4.levenshtein()
This function calculates the similarity of two string
based on how many characters must be added,
substituted or remove to make them the same.
Syntax
levenshtein(string1,string2,insert,replace,delete)
Parameter Description
string1 Required. First string to compare
string2 Required. Second string to compare
Insert Optional. The cost of inserting a character.
Replace Optional. The cost of replacing a character.
Delete Optional. The cost of deleting a character.
Return Value: Returns the Levenshtein distance between the two argument strings or -1
37 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
<?php
$c=levenshtein("sun","son");
echo $c;
?>
o/p
1
3.Manipulating & Searching String
1.substr() 2.substr_count()
The substr() function returns a part of a
string
Syntax
substr(string,start,length)
ParameterDescription
String
Required. Specifies the string
to return a part of
Start
Required. Specifies where to
start in the string
Length
Optional. Specifies the length
of the returned string. Default
is to the end of the string.
<?php
$c=substr("hello world",3);
echo $c;
?>
o/p
The substr_count() function counts the number of
times a substring occurs in a string.
Syntax
substr_count(string,substring,start,length)
ParameterDescription
String Required. Specifies the string to check
substring
Required. Specifies the string to search
for
Start
Optional. Specifies where in string to
start searching
Length
Optional. Specifies the length of the
search
Return
Value:
Returns the the number of times the
substring occurs in the string
<?php
$str="That is php is";
echo substr_count($str,"is");
38 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
lo world ?>
o/p
2
3.substr_replace()
The substr_replace() function replaces a part of a string
with another string.
Syntax
substr_replace(string,replacement,start,length)
Parameter Description
String Required. Specifies the string to check
Replacement Required. Specifies the string to insert
Start Required. Specifies where to start replacing in the string
Length
Optional. Specifies how many characters should be replaced. Default is the
same length as the string.
Return Value: Returns the replaced string.
<?php
echo substr_replace("Hello world","earth",6);
?>
o/p
39 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
strpos()
The strpos() function finds
the position of the first
occurrence of a string inside
another string.
Syntax
strpos(string,find,start)
<?php
echo strpos(“bcs is”,”is");
?>
o/p
4
strstr() Function
The strstr() function searches for the first occurrence of a string
inside another string.
strstr(string,search,before_search)
Parameter Description
String Required. Specifies the string to search
Search Required. Specifies the string to search for.
before_search Optional. A boolean value whose default is
"false". If set to "true", it returns the part of
the string before the first occurrence of
the search parameter.
<?php
echo strstr("Hello world!","world",true);
?>
o/p
world!
40 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
strrchr()
The strrchr() function finds the
position of the last occurrence
of a string within another
string, and returns all
characters from this position to
the end of the string.
Syntax
strrchr(string,char)
<?php
echo strrchr("Hello world!
What a beautiful day!",What);
?>
o/p
What a beautiful day!
Decomposition a string function
1 explode
Split a string by string & return array.
Syntax
explode(separator,string,limit)
separator
Required. Specifies where to break the string
string
Required. The string to split
limit
2 Implode
Join array elements with a string
Syntax
implode(separator,array)
separator Optional. Specifies what to put
between the array elements.
Default is "" (an empty string)
Array Required. The array to join to a
string
41 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Optional. Specifies the number of array
elements to return.
<?php
// Example 1
$a = "hello world";
$p = explode(" ", $a);
print_r($p);
?>
o/p
Array ( [0] => hello [1] => world )
<?php
$a = array('lastname', 'email', 'phone');
$c = implode(" ", $a);
echo $c;
?>
o/p
lastname,email,phone
42 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
3.strtok()
The strtok() function splits a string into
smaller strings (tokens).
Syntax
strtok(string,split)
string Required. Specifies the string to
split
split Required. Specifies one or more
split characters
<?php
$string = "Hello bcs";
$token = strtok($string, "");
while ($token !== false)
{
echo "$token<br>";
$token = strtok("");
}
?>
o/p
Hello
bcs
ENCODING ESCAPING FUNCTION
43 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
1.Htmlentities 2. htmlspecialchars
This function changes all characters with
HTML entity into equivalent(except space
character).This include less then(<),greater
than(>),ampersand(&).
Syntax
htmlentities(string,flags,character-
set,double_encode)
Parameter Description
String
Required. Specifies the
string to convert
Flags
Optional. Specifies how to
handle quotes, invalid
encoding and the used
document type.
The available quote styles
are:
• ENT_COMPAT -
Default. Encodes
only double quotes
• ENT_QUOTES -
Encodes double
and single quotes
• ENT_NOQUOTES
- Does not encode
any quotes
The htmlspecialchars() function
converts some predefined characters to
HTML entities.
The predefined characters are:
• & (ampersand) becomes &amp;
• " (double quote) becomes &quot;
• ' (single quote) becomes &#039;
• < (less than) becomes &lt;
• > (greater than) becomes &gt;
Syntax
htmlspecialchars(string,flags,character-
set,double_encode)
<?php
$str = "hello &'ok'";
echo htmlspecialchars($str,
ENT_COMPAT); // Will only convert
double quotes
echo "<br>";
echo htmlspecialchars($str,
ENT_QUOTES); // Converts double
and single quotes
echo "<br>";
echo htmlspecialchars($str,
ENT_NOQUOTES); // Does not
convert any quotes
?>
o/p
hello &amp; 'ok'<br>
hello &amp; &#039;ok&#039;<br>
44 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
character-set
Optional. A string that
specifies which character-
set to use.
Allowed values are:
double_encode
Optional. A boolean value
that specifies whether to
encode existing html
entities or not. TRUE -
Default. Will convert
everything & FALSE -
Will not encode existing
html entities
<?php
$str = "<&hello>";
echo htmlentities($str);
?>
o/p
&lt;&amp;hello&gt;
hello &amp; 'ok'
----------------------------------------------
3.strip_tags
----------------------------------------------
The strip_tags() function strips a string
from HTML, XML, and PHP tags.
Syntax
strip_tags(string,allow)
string
Required. Specifies the string to
check
allow
Optional. Specifies allowable
tags. These tags will not be
removed
<?php
echo strip_tags("Hello <b>");
?>
o/p
Remove <b> tag
Regular Expression
A regular expression is a string that represent a pattern.
The regular expression function compare that pattern to another string &check if any of the
string matches the pattern.
There are 2 types of regular expression
1. POSIX Regular Expressions
2. PERL Style Regular Expressions
45 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
POSIX regular expression are less powerful & slower then PERL
ExpressionDescription
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lowercase a through lowercase z.
[A-Z] It matches any character from uppercase A through uppercase Z.
[a-Z] It matches any character from lowercase a through uppercase Z.
Quantifiers
ExpressionDescription
p+
[a-z]+ It matches any string containing at least one p.
p*
[a-z]*
It matches any string containing zero or more p's.
p?
It matches any string containing zero or more p's. This is just an alternative way to
use p*.
p{N}
It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
46 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
1.ereg 2.ereg_replace
The ereg() function searches a string specified
by string for a string specified by pattern,
returning true if the pattern is found, and false
otherwise.(case sensitive)
<?php
if(ereg("^[a-z]+$","amol")==null)
echo "true";
else
echo "false";
?>
o/p
true
This function scans string for matches to
pattern, then replaces the matched text with
replacement.
<?php
$string = "This is a test";
echo ereg_replace(" is", " was", $string);
?>
O/P
This was a test
3.eregi 4.split
The eregi() function searches throughout a
string specified by pattern for a string specified
by string. The search is not case sensitive
<?php
if(eregi("^[a-z]+$","amol")==null)
echo "true";
else
echo "false";
?>
o/p
The split() function will divide a string into
various elements.
<?php
$ip = "123.456";
$p = split (".", $ip);
echo "$p[0]"; print_r($p);
echo "$p[1]";
?>
o/p
123
456
47 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
true
48 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
FILE
1.fopen()
The fopen() function opens a file
Syntax
fopen(filename,mode)
File mode as follows
• "r" (Read only. Starts at the
beginning of the file)
• "r+" (Read/Write. Starts at the
beginning of the file)
• "w" (Write only. Opens and clears
the contents of file; or creates a
new file if it doesn't exist)
• "w+" (Read/Write. Opens and
clears the contents of file; or
creates a new file if it doesn't exist)
• "a" (Write only. Opens and writes
to the end of the file or creates a
new file if it doesn't exist)
• "a+" (Read/Write. Preserves file
content by writing to the end of the
file)
• "x" (Write only. Creates a new file.
Returns FALSE and an error if file
already exists)
• "x+" (Read/Write. Creates a new
file. Returns FALSE and an error if
file already exists)
e.g $file = fopen("test.txt","r");
2.fclose()
The fclose() function closes an open file
Syntax
fclose(file)
e.g fclose($file)
49 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
3.fread() Function
The fread() reads from an open file.
The function will stop at the end of the file
or when it reaches the specified length
Syntax
fread(file,length)
Parameter Des
File Required.
Specifies
the open
file to
read from
Length Required.
Specifies
the
maximum
number of
bytes to
read
e.g fread($file,"10");
4.fwrite() or fputs()
The fwrite() writes to an open file.
Syntax
fwrite(file,string,length)
File Required. Specifies the open file to
write to
String Required. Specifies the string to write
to the open file
length Optional. Specifies the maximum
number of bytes to write
e.g
fwrite($file,"Hello World. Testing!");
50 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
fgetc()
The fgetc() function returns a single
character from an open file
Syntax
fgetc(file)
file Required. Specifies the
file to check
e.g
echo fgetc($file)
fgets()
The fgets() function returns a line from an open
file.
Syntax
fgets(file,length)
File Required. Specifies the file to
read from
length Optional. Specifies the number of
bytes to read. Default is 1024
bytes.
e.g
echo fgets($file);
unlink()
The unlink() function deletes a file.
Syntax
unlink(filename)
e.g unlink($file)
basename()
Syntax
basename(path)
$path = "/testweb/home.php";
echo basename($path);
o/p
home.php
• To Write a data into a file
<?php
$file = fopen("test.txt","w") or die(“can’t open file”);
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>
51 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
• To read a file from a file
<?php
$file = fopen("t.txt","r") or die(“can’t open file”);
echo fread($file,filesize("t.txt"));
fclose($file);
?>
Or
<?php
$file = fopen("t.txt","r") or die(“can’t open file”);
while($ch=fgetc($file))
{
echo $ch;
}
fclose($file);
52 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
file()
The file() reads a file into an array.
Syntax
file(path,include_path,context)
Path Required. Specifies the file to read
include_path Optional. Set this parameter to '1' if
you want to search for the file in the
include_path (in php.ini) as well
Context Optional. Specifies the context of the
file handle. Context is a set of options
that can modify the behavior of a
stream. Can be skipped by using
NULL.
<?php
$p=file("test.txt");
print_r($p);
?>
fpassthru()
The fpassthru() function reads all data
from the current position in an open
file, until EOF, and writes the result to
the output buffer
Syntax
fpassthru(file)
file Required. Specifies the open
file or resource to read from
<?php
$file = fopen("test.txt","r");
// Read first line
fgets($file);
// Send rest of the file to the output
buffer
echo fpassthru($file);
fclose($file);
?>
53 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
readfile()
The readfile() function reads a file and writes it to the
output buffer
Syntax
readfile(filename,include_path,context)
<?php
$preadfile("test.txt");
echo $p;
?>
Random Access to file
54 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
fseek()
The fseek() function seeks in an open file.
Syntax
fseek(file,offset,whence)
Offset Required. Specifies the new
position (measured in bytes from
the beginning of the file)
Whence Optional. (added in PHP 4).
Possible values:
• SEEK_SET - Set position
equal to offset. Default
• SEEK_CUR - Set position
to current location plus
offset
• SEEK_END - Set position
to EOF plus offset (to
move to a position before
EOF, the offset must be a
negative value)
e.g
<?php
$file = fopen("test.txt","r");
// read first line
fgets($file);
// move back to beginning of file
fseek($file,0);
?>
ftell()
The ftell() function returns the
current position in an open
file
Syntax
ftell(file)
$file = fopen("test.txt","r");
echo ftell($file);
55 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
rewind()
The rewind() function "rewinds" the position
of the file pointer to the beginning of the file
Syntax
rewind(file)
$file = fopen("test.txt","r");
fseek($file,"15");
//Set file pointer to 0
rewind($file);
ftell()
The ftell() function returns the
current position in an open
file
Syntax
ftell(file)
$file = fopen("test.txt","r");
echo ftell($file);
Getting information on File
file_exists()
The file_exists() function checks whether or
not a file or directory exists.
Syntax
Boolean file_exists(path)
<?php
echo file_exists("test.txt");
?>
Filesize
The filesize() function returns the size of the
specified file.This function returns the file size
in bytes on success or FALSE on failure.
Syntax
filesize(filename)
<?php
echo filesize("test.txt");
?>
56 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
filectime()
The filectime() function returns the last
time the specified file was changed.
Syntax
filectime(filename)
e.g
echo "Last change: ".date("F d Y
H:i:s.",filectime("test.txt"));
filemtime()
The filemtime() function returns the last time the
file content was modified.
Syntax
filemtime(filename)
e.g
echo "Last modified: ".date("F d Y
H:i:s.",filemtime("test.txt"));
pathinfo()
The pathinfo() function returns an array that contains information about a path.
Syntax
pathinfo(path,options)
<?php
print_r(pathinfo("/bcs/test.txt"));
?>
o/p
Array
(
[dirname] => /testweb
[basename] => test.txt
[extension] => txt
)
57 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
stat()
The stat() function returns information about a file.
This function returns an array with the following elements:
• [0] or [dev] - Device number
• [1] or [ino] - Inode number
• [2] or [mode] - Inode protection mode
• [3] or [nlink] - Number of links
• [4] or [uid] - User ID of owner
• [5] or [gid] - Group ID of owner
• [6] or [rdev] - Inode device type
• [7] or [size] - Size in bytes
• [8] or [atime] - Last access (as Unix timestamp)
• [9] or [mtime] - Last modified (as Unix timestamp)
• [10] or [ctime] - Last inode change (as Unix timestamp)
• [11] or [blksize] - Blocksize of filesystem IO (if supported)
• [12] or [blocks] - Number of blocks allocated
Syntax
stat(filename)
e.g
$stat = stat('test.txt');
echo 'file size: ' .$stat['size'];
Ownership & permission
58 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
posix_getpwuid()
Return info about a user by user id
Syntax
array posix_getpwuid ( int $uid )
• name: The username.
• passwd: Contents of the passwd field (may be x or similar on systems
with shadow passwords enabled).
• uid: The user ID.
• gid: The group ID.
• gecos: Contents of the GECOS field; intended to hold the user's real
name. GECOS stands for 'General Electric Comprehensive Operating
System', for historical reasons.
• dir: The user's home directory.
• shell: The user's login shell (e.g. /bin/bash).
e.g
$userinfo = posix_getpwuid(10000);
print_r($userinfo);
fileowner():Return USER ID of specfied file
filegroup():Return Group ID of specified file
file_type():Return type of the file
Is_dir():Return true if true as directory
Is_file(): Return true if true as file
Working with directories
59 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
opendir()
Open a directory, read its contents, then close.
Syntax
opendir(path);
path Required. Specifies the directory path
to be opened
readdir()
Open a directory, read its contents, then
close
//list of entries which is specified by
directory handle
Syntax
readdir(dir_handle);
dir_handle Optional.
Specifies the
directory handle
resource
<?php
$dir = "/bcs/";
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>
closedir()
Open a directory, read its contents, then close.
Syntax
closedir(dir_handle);
chdir()
Change the current directory
Syntax
chdir(directory);
e.g chdir("images");
60 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
dir()
Use the dir() function
Syntax
dir(directory)
<?php
$d = dir(getcwd());
echo "Handle: " . $d->handle . "<br>";
echo "Path: " . $d->path . "<br>";
while (($file = $d->read()) !== false){
echo "filename: " . $file . "<br>";
}
$d->close();
?>
scandir()
List files and directories inside the specified
directory
Syntax
scandir(directory)
<?php
$dir = "/bcs/";
$a = scandir($dir);
print_r($a);
?>
PHP include and require Statements
To insert the content of one PHP file into another PHP file with the include or require statement
is used.
Syntax
include 'filename';
or
require 'filename';
The include and require statements are identical, except upon failure:
• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue
61 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
e.g
a.php
<?php
Hello
?>
b.php
<?php
include ‘a.php';
?>
62 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Databases
There are two approaches to access databases from PHP.
1.Use a Database –specific extension.
2.Use the database –independent PEAR DB library.
1.Use a Database –specific extension.
This done by following steps.
1. Create a connection to MySQL/Postgres Database.
2. Create a database (can be done in MySql/Postgres)
3. Create a table(Can be done in MySql/Postgres)
4. Execute Query(Select or any other)
5. Display Result in an HTML Table.
6 Close the connection.
1.pg_connect
pg_connect() opens a connection to a PostgreSQL database specified by the
connection_string.
Syntax
resource pg_connect ( string $connection_string )
connection string contains host, hostaddr, port, dbname,password etc
2.pg_query
pg_query() executes the query on the specified database
Syntax
resource pg_query ([ resource $connection ], string $query )
63 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
3.pg_fetch_row
pg_fetch_row() fetches one row of data from the result associated with the specified result
resource
Syntax
array pg_fetch_row ( resource $result [, int $row ] )
4.pg_close()
Closes a PostgreSQL connection
Syntax
bool pg_close ([ resource $connection ] )
• To retrieve data from database
<?php
$con=pg_connect("host=localhost dbname=ty user=root")or die("Unable to connect");
$q="select * from stud";
$res=pg_query($con,$q) or die("Unable to execute query");
while($r1=pg_fetch_row($res))
{
echo $r1[0]."<br>";
echo $r1[1]."<br>";
}
pg_close($con);
?>
64 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
• To insert data into database
<?php
$con=pg_connect("host=localhost dbname=ty user=root")or die("Unable to connect");
$s1=111;
$s2='ram';
$q="insert into stud values($s1,$s2)";
pg_query($con,$q) or die("Unable to insert query");
echo "insert successfully";
pg_close($con);
?>
• Update data into database
<?php
$con=pg_connect("host=localhost dbname=ty user=root")or die("Unable to connect");
$s1=111;
$s2='ram';
$q="update stud set sname='$s2' where rollno=$s1";
pg_query($con,$q) or die("Unable to update query");
echo "update successfully";
pg_close($con);
?>
• Delete from database
<?php
$con=pg_connect("host=localhost dbname=ty user=root")or die("Unable to connect");
65 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
$s1=111;
$q="delete from stud where rollno=$s1";
pg_query($con,$q) or die("Unable to delete query");
echo "delete successfully";
pg_close($con);
?>
PEAR DB BASICS
PEAR stands for PHP Extension and Application Repository.
1.PEAR DB library is object oriented.
It provide mixture of class methods such as DB::connect(),DB::iserror() etc.
2.PEAR DB is portable.
It allowed to use single API to work with many different type of databases.
3. Code Simplification
Application involved multiple databases , It normally to learn the API for each of the databases.
but using pear db allow to work with all databases using single API.
PEAR DB codes the functions are generic
4. It provide a number of open source collection of free PHP modules and classes for many
different function.
<?php
include_once('DB.php');
$user = "root";
$pwd = "";
$host = "localhost";
Web Browser
Apache
PHP Engine
PEAR DB
pgSql,Mysql driver
Database Server
66 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
$database = "bca";
$dsn = “pgsql://$user:$pwd@$host/$database";
$db = DB::connect($dsn);
if (DB::isError($db))
{
die($db->getMessage());
}
else
{
$r = $db->query("SELECT * FROM student");
while ($r->fetchInto($row))
{
echo $row[0];
echo $row[1];
}
$r->free();
}
$db->disconnect();
?>
1.Data Source Names
A data source name(DSN) is a string that specifies where the database is located, what kind of
database it is, the username and password to use when connecting to the database, and more.
The components of a DSN are assembled into a URL-like string:
type(dbsyntax)://username:password@protocol+hostspec/database
Where
Type:(Compulsory)which specifies the PHP database backend to use. The following lists the
implemented database types at the time of writing.
Name Database
Mysql MySQL
Pgsql PostgreSQL
67 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Ibase InterBase
Msql Mini SQL
Mssql Microsoft SQL Server
oci8 Oracle 7/8/8i
Odbc ODBC
Sybase SyBase
Ifx Informix
Fbsql FrontBase
Eg. The following valid DSN
mysql://php_data:Only database name
mysql://localhost/php_data:server name +database name.
mysql://user@localhost/php_data:user+servername+database name
mysql://user@tcp+localhost/php_data:user+protocol+server name+ database name
mysql://user:user123@localhost/php_data:user+password+server name+ database name
2.Connecting to the database
DB::connect()
After a DSN is created ,establish a connection to the database using the connect() method
Syntax:
$db=DB::connect(DSN[,option]);
DSN:Data source name
Where option is
Option Controls
persistent Connection persists between accesses
68 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
optimize What to optimize for
debug Display debugging information
3.Checking Errors
DB::ISERROR
This method is used to return if error occurs.
if (DB::isError($db))
{
die($db->getMessage());
}
4. Issuing Query
Query()
Using this method SQL query can be sent to the database
If SQL statements as INSERT,UPDATE,DELETE are executed successfully then the function
returns DB_OK message.
Sr=$db->query(sql);
5.Fetching result from query
It provides have 2 method for fetching data from a query result object.
1.Returing the row
fetchRow():This method on a query result returns an array of the next row of result
Syntax:
$row=$r->fetchRow([mode]);
Mode:(optional) It controls the format of the result array return
1. DB_FETCHMODE_ORDERED: Default value.
2. DB_FETCHMODE_ASSOC: It creates an array whose value keys are the column name
and whose values are the values from column.
69 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
ON success it return an array of data It return NULL if there is no more data
while ($row = $result->fetchRow( ))
{
---
}
2.Storing Row
This method also returns the next row, but stores it into the array variable passed as parameter
Syntax:
$var=$result->fetchInto(array,[mode]));
Array:array variable into which result will be stored
while ($success = $result->fetchInto($row))
{
--
}
6. Free up memory
Free()
The function is used to free up the memory consumed by the query. The memory is returned to
the operating system. This is required since a query result object usually holds all rows returned
by the query.
$r->free()
7.Discconnected Database
Disconnected()
$db->disconnected()
Advantage and Disadvantage of two approach
1.If we use database-specific extension, then the code is very much tied to that database only. So
changing one database to other involves many changes in the code.
70 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
2PEAR DB approach is quit different than this and it is not bound to any specific database. It is
object oriented approach.
Advanced Database Techniques
1.Placeholders
While writing query like insert or update, it can put a placeholder “?” in place of specific
value
Syntax
$result = $db->query(SQL, values);
Where
Sql: either insert or update with a placeholder value
Values:The array of values to insert or update into the SQL
e.g
$stud = array(array(1,’amol’),array(2,’amit’),array(3,’sagar’));
foreach ($stud as $s)
{
$db->query('INSERT INTO stud (rollno,sname) VALUES (?,?)', $s);
}
There are three characters that you can use as placeholder values in an SQL query:
?
A string or number, which will be quoted if necessary (recommended)
|
A string or number, which will never be quoted
&
A filename, the contents of which will be included in the statement
2. Prepare/Execute
When issuing the same query repeatedly, it can be more efficient to compile the query once and
then execute it multiple times, using theprepare( ), execute( ), and executeMultiple( )methods.
71 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
1.prepare():The first step is to call prepare()method on the query. This method is used to create
a generic statement.
$compiled = $db->prepare(SQL);
2.execute():After preparing the statement it can execute query.
$response = $db->execute(compiled, values);
The values array contains the values for the placeholders in the query. The return value is either
a query response object, or DB_ERROR if an error occurred.
For example, we could insert multiple values into the stud table like this:
$stud = array(array(1,’amol’),array(2,’amit’),array(3,’sagar’));
$compiled = $q->prepare('INSERT INTO stud (rollno,sname) VALUES (?,?)');
foreach ($stud as $s)
{
$db->execute($compiled, $s);
}
3.executeMultiple():This method is used to avoid the foreach loop in above eg
$responses = $db->executeMultiple(compiled, values);
$stud = array(array(1,’amol’),array(2,’amit’),array(3,’sagar’));
$compiled = $q->prepare('INSERT INTO stud (rollno,sname) VALUES (?,?)');
$db->executeMultiple(compiled, $stud);
72 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
3.Shortcuts
PEAR DB provides a number of methods that perform a query and fetch the results in one step:
getOne( ), getRow( ), getCol( ), getAssoc( ), and getAll(). All of these methods permit
placeholders.
1.The getOne( ) method fetches the first column of the first row of data returned by an
SQL query:
$value = $db->getOne(SQL [, values ])
Eg
$m = $db->getOne("SELECT count(*) FROM stud");
echo "$m";
2. The getRow( ) method returns the first row of data returned by an SQL query:
$row = $db->getRow(SQL [, values ]]);
Eg
$m = $db->getRow("SELECT * FROM stud");
echo "$m";
3.The getCol( ) method returns a single column from the data returned by an SQL query:
$col = $db->getCol(SQL [, column [, values ]]);
The column parameter can be either a number (0, the default is the first column), or the column
name.
Eg
$t = $db->getCol("SELECT sname from stud");
foreach ($t as $p)
{
echo "$p";
}
73 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
4.The getAll( ) method returns an array of all the rows returned by the query:
$all = $db->getAll(SQL [, values]);
$r = $db->getAll("SELECT rollno,sname from stud);
foreach ($r as $r1)
{
echo "$r1[0].$r1[1]";
}
Details About a Query Response
Four PEAR DB methods provide you with information on a query result object: numRows( ),
numCols( ), affectedRows( ), and tableInfo( ).
The numRows( ) and numCols( ) methods tell you the number of rows and columns returned
from a SELECT query:
$howmany = $response->numRows( );
$howmany = $response->numCols( );
The affectedRows( ) method tells you the number of rows affected by an INSERT, DELETE, or
UPDATE operation:
$howmany = $response->affectedRows( );
The tableInfo( ) method returns detailed information on the type and flags of fields returned
from a SELECT operation:
$info = $response->tableInfo( );
Sequences
• Sequence is a database object that generates numbers in sequential order.
• Some of the RDBMS support to feature to assign unique row id.PEAR DB sequences are
an alternate to database specific ID assignment
• nextID() method returns the next ID for the given sequence
74 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
$id=$db->nextID(sequence)
• It can explicitly create and destroy sequences with the createSequence( )and
dropSequence( ) methods:
$res = $db->createSequence(sequence);
$res = $db->dropSequence(sequence);
Metadata
The getListOf( )method lets you query the database for information on available databases,
users, views, and functions:
$data = $db->getListOf(what);
The what parameter is a string identifying the database feature to list. Most databases support
"databases"; some support "users", "views", and "functions".
For example, this stores a list of available databases in $dbs:
$dbs = $db->getListOf("databases");
Transactions
Some RDBMSs support transactions, in which a series of database changes can be committed
(all applied at once) or rolled back (discarded, with the changes not applied to the database).
PEAR DB offers the commit( ) and rollback( ) methods to help with transactions:
$res = $db->commit( );
$res = $db->rollback( );
75 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
EMAIL HANDLING WITH PHP
Email Server Working
1. The sender composes a message using the email client on their computer.
2. When the user sends the message, the email text and attachments are uploaded to the
SMTP (Simple Mail Transfer Protocol) server as outgoing mail.
3. All outgoing messages wait in the outgoing mail queue while the SMTP server
communicates with the DNS (Domain Name Server–like a phone book for domain names
and server IP addresses) to find out where the recipient’s email server is located. If the
SMTP server finds the recipient’s email server, it will transfer the message and
attachments. If the recipient’s server can’t be found, the sender will get a “Mail Failure”
notification in their inbox.
4. Recipient download new message to their email client & received their message
76 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Internet Mail orE-mail Protocols
E-mail Protocols are set of rules that help the client to properly send the information to or
received from the mail server.
It consist of protocols such as SMTP(sending email), POP 3(receiving email)
, and IMAP(receiving email).
77 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
POP3
1. The POP (Post Office Protocol 3) protocol provides a simple, standardized way for
users to access mailboxes and download messages to their local computers.
2. Using the POP protocol all your eMail messages will be downloaded from the mail server
to your local computer.
3. The advantage is that once your messages are downloaded, the internet connection is not
required so that it reduces further communication costs.(Internet charges).But when
downloading the message, a a lot of message (including spam or viruses)are copied to the
local computer.
4. When the message is downloaded to the client machine, the copy from server gets
deleted. This makes to access the email only from that local computer & not from any
computer using internet(Mails once downloaded cannot be accessed from some other location)
The following table describes some of the POP commands:
S.N. Command Description
1 LOGIN
This command opens the connection.
78 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
2 STAT
It is used to display number of messages currently in the
mailbox.
3 LIST
It is used to get the summary of messages where each
message summary is shown.
4 RETR
This command helps to select a mailbox to access the
messages.
5 DELE
It is used to delete a message.
6 RSET
It is used to reset the session to its initial state.
7 QUIT
It is used to log off the session.
IMAP
1. IMAP (Internet Message Access Protocol) is a standard protocol for accessing e-mail
from your local server.
2. IMAP is a client/server protocol in which e-mail is received and held for you by your
Internet server.
3. This work even over a slow connection such as a modem since required only small data
transfer.
4. It can also create and manipulate folders or mailboxes on the server, delete messages etc.
5. IMAP support both online & offline modes of operation
79 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
6. It Allows mails to be accessed from multiple locations.
SMTP
SMTP stands for Simple Mail Transfer Protocol. It is a standard protocol used for sending e-
mail efficiently and reliably over the internet.
• SMTP is application level protocol.
• SMTP is connection oriented protocol.
• SMTP is text based protocol.
• It handles exchange of messages between e-mail servers over TCP/IP network.
• Apart from transferring e-mail, SMPT also provides notification regarding incoming mail.
• When you send e-mail, your e-mail client sends it to your e-mail server which further
contacts the recipient mail server using SMTP client.
• These SMTP commands specify the sender’s and receiver’s e-mail address, along with the
message to be send.
• The exchange of commands between servers is carried out without intervention of any
user.
• In case, message cannot be delivered, an error report is sent to the sender which makes
SMTP a reliable protocol.
HTTP Protocol
1. HTTP is the protocol that web browsers and web servers use to communicate with each
other over the Internet.
80 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
2. It is an application level protocol .
3. It is stateless protocol because each command is executed independently
4. It is request & response fro client server
Structure Of email
It consist of
1.Message Header
The message headers contain information concerning the sender and recipients. Headers contain
the following information:
• Subject:Subject is a description of the topic of the message
• Sender (From):This is the sender's Internet email address.
• Date and time received (On): The date and time the message was received.
• Reply-to: This is the Internet email address that will become the recipient of your reply if
you click the Reply button.
• Recipient (To:) Recipient email address.
• Cc: Address of the recipient, who will received copies.
• Attachments. Files that are attached to the message.
2.Message Body
The body of a message contains text that is the actual content
Sending Email Using PHP
Mail(): mail() function allows you to send emails directly from a script.
Syntax
mail(to,subject,message,headers,parameters);
81 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
To Required. Specifies the receiver / receivers of the email
Subject Required. Specifies the subject of the email.
Message Required. Defines the message to be sent. Each line should be separated with
a LF (n). Lines should not exceed 70 characters.
Headers Optional. Specifies additional headers, like From, Cc, and Bcc.
.
parameters Optional. Specifies an additional parameter to the sendmail program.
<?php
$to = "bcs@gmail.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: visionacademy@gmail.com" ;
mail($to,$subject,$txt,$headers) or die(“failed email”);
?>
Email Validation
Email validation using 2 ways
1.Using filter_var function
2. Using ereg function
1.Using filter_var
The FILTER_VALIDATE_EMAIL filter validates an e-mail address.
Syntax
filter_var(var, filtername, options)
82 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Parameter Description
Var Required. The variable to filter
filtername Optional. Specifies the ID or name of the filter to use.
Default is FILTER_DEFAULT, which results in no
filtering
options Optional. Specifies one or more flags/options to use.
<?php
$email = "visionacademy@gmail.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL))
echo("email is a valid");
else
echo("email is not a valid");
?>
2 Using ereg function
<?php
$email = "visionacademy@gmail.com";
if(!ereg("^[A-Za-z]+[0-9]*[.]{0,1}[A-Za-z0-9]*[@]{1}[A-Za-z0-9]*[.]{1,2}[A-Za-
z]{2,5}$",$mail))
echo "wrong Input for E-Mail";
else
echo "correct";
?>
83 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
POST OFFICE PROTOCOL
(POP3)
INTERNET MESSAGE
ACCESS PROTOCOL (IMAP)
POP3 is short for Post Office
Protocol. With POP3 mail, it will
connect and attempt to keep the
mail located on the local device
(computer or mobile).
IMAP is short for Internet
Message Access Protocol. With
IMAP, the message does not
remain on the local device, such
as a computer, it remains on the
server.
The POP server listens on port
110, and the POP with SSL
secure(POP3DS) server listens
on port 995
The IMAP server listens on port
143, and the IMAP with SSL
secure(IMAPDS) server listens
on port 993.
In POP3 the mail can only be
accessed from a single device
at a time.
Messages can be accessed across
multiple devices
The user can not organize
mails in the mailbox of the
mail server.
The user can organize the emails
directly on the mail server.
84 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
POST OFFICE PROTOCOL
(POP3)
INTERNET MESSAGE
ACCESS PROTOCOL (IMAP)
The user can not create, delete
or rename email on the mail
server.
The user can create, delete or
rename email on the mail server.
A user can not search the
content of mail before
downloading to the local
system.
A user can search the content of
mail for specific string before
downloading.
When the message is
downloaded to the client
machine, the copy from server
gets deleted.
Multiple redundant copies of the
message are kept at the mail
server, in case of loss of message
of a local server, the mail can
still be retrieved
POP3 works better if you are
only using one device,
IMAP is better if you are going
to be accessing your email from
multiple devices, such as a work
computer and a smart phone
What is CC &BCC?
85 Vision Academy
(9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
PHP
Cc means carbon copy and Bcc means blind carbon copy.
For emailing, you use Cc when you want to copy others publicly, and Bcc when you want to do
it privately. Any recipients on the Bcc line of an email are not visible to others on the email
Ahmed, Barry and Carol can all see that the email was sent to Ahmed, Barry and Carol for their
attention and they can also see that a copy of the email was sent to Darren, Elaine and Fred.
Darren, Elaine and Fred can all see that the email was sent to Ahmed, Barry and Carol for their
attention and they can also see that a copy of the email was sent to Darren, Elaine and Fred
Gunter, Harriet and Ian can all see that the email was sent to Ahmed, Barry and Carol for their
attention and they can also see that a copy of the email was sent to Darren, Elaine and Fred
Nobody can see that the email has been sent to Gunter, Harriet or Ian

More Related Content

Similar to PHP HTTP Protocol Guide

FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQLArti Parab Academics
 
From CakePHP to Laravel
From CakePHP to LaravelFrom CakePHP to Laravel
From CakePHP to LaravelJason McCreary
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics McSoftsis
 
LAB PHP Consolidated.ppt
LAB PHP Consolidated.pptLAB PHP Consolidated.ppt
LAB PHP Consolidated.pptYasirAhmad80
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfShaimaaMohamedGalal
 
PHP Introduction and Training Material
PHP Introduction and Training MaterialPHP Introduction and Training Material
PHP Introduction and Training MaterialManoj kumar
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckrICh morrow
 
Unit-1 PHP Basic1 of the understanding of php.pptx
Unit-1 PHP Basic1 of the understanding of php.pptxUnit-1 PHP Basic1 of the understanding of php.pptx
Unit-1 PHP Basic1 of the understanding of php.pptxAatifKhan84
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfonyFrancois Zaninotto
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...webhostingguy
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to DomainJeremy Cook
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 

Similar to PHP HTTP Protocol Guide (20)

FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
From CakePHP to Laravel
From CakePHP to LaravelFrom CakePHP to Laravel
From CakePHP to Laravel
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
php 1
php 1php 1
php 1
 
LAB PHP Consolidated.ppt
LAB PHP Consolidated.pptLAB PHP Consolidated.ppt
LAB PHP Consolidated.ppt
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
 
PHP Introduction and Training Material
PHP Introduction and Training MaterialPHP Introduction and Training Material
PHP Introduction and Training Material
 
PHP and MySQL.ppt
PHP and MySQL.pptPHP and MySQL.ppt
PHP and MySQL.ppt
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Unit-1 PHP Basic1 of the understanding of php.pptx
Unit-1 PHP Basic1 of the understanding of php.pptxUnit-1 PHP Basic1 of the understanding of php.pptx
Unit-1 PHP Basic1 of the understanding of php.pptx
 
PHP
PHPPHP
PHP
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to Domain
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 

Recently uploaded

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 

Recently uploaded (20)

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 

PHP HTTP Protocol Guide

  • 1. 1 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP HTTP HTTP stands for HyperText Transfer Protocol. This is a basis for data communication in the internet. The data communication starts with a request sent from a client and ends with the response received from a web server. • A website URL starting with “http://” is entered in a web browser from a computer (client). The browser can be a Chrome, Firefox, Edge, Safari, Opera or anything else. • Browser sends a request sent to the web server that hosts the website. • The web server then returns a response as a HTML page or any other document format to the browser. • Browser displays the response from the server to the user. HTTP Request A simple request message from a client computer consists of the following components: • A request line to get a required resource, • Number of Headers lines • An empty line. • A message body which is optional. HTTP Response A simple response from the server contains the following components: • HTTP Status Code • Number of Headers lines • An empty line. • A message body which is optional. Web server A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers' HTTP clients
  • 2. 2 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Name of web server 1 Apache HTTP Server 2. Internet Information Services 3. Sun Java System Web Server 4.NGINX 5. Node.js Name of Web browser Chrome, Firefox, Edge, Safari, Opera, internet explorer What is PHP? • PHP means " Hypertext Preprocessor" • PHP is cross platform ,HTML embedded & server side web scripting language cross platform=> PHP runs on many operating system such as windows,UNIX etc. HTML embedded=>It can take a standard HTML page, drop in some PHP whenever need & end up with a dynamic result. Server Side=>PHP run on server such as apache,IIS etc
  • 3. 3 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP web scripting language=>It is used to write web script, not stand alone application.(PHP programs are executed through web server) Feature of PHP • PHP can generate dynamic page content • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) • It is open source. • PHP is compatible with almost all servers used today (Apache, IIS, etc.) • PHP is easy to learn and runs efficiently on the server side • PHP code can written in a procedure or object oriented manner. • PHP supports a wide range of databases Lexical Structure The lexical structure of a programming language is the set of basic rules that governs how you write programs in that language. It is the lowest-level syntax of the language and specifies such things as what variable names look like, what characters are used for comments, and how program statements are separated from each other. Basic PHP Syntax <?php // PHP code goes here ?> <html> <body> <?php echo "Hello World!"; ?> </body> </html> It can insert HTML tag in PHP <html> <body> <?php echo "<b>Hello World!</b>";
  • 4. 4 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP ?> </body> </html> Comments in PHP <?php // This is a single-line comment # This is also a single-line comment /* This is a multiple-lines comment block that spans over multiple lines */ ?> In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. But variables are case sensitive PHP variable Rules for PHP variables: • A variable starts with the $ sign, followed by the name of the variable • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive <?php $txt = "Hello world!"; $x = 5; $y = 10.5; echo "String is $txt"; echo "Integer is $x";
  • 5. 5 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP echo "float is $y"; ?> Data type in PHP • Integers: are whole numbers, without a decimal point, like 4195. • float: are floating-point numbers, like 3.14159 or 49.1. • Booleans: have only two possible values either true or false. • NULL: is a special type that only has one value: NULL. • Strings: are sequences of characters, like 'PHP supports string operations.' • Arrays: are named and indexed collections of other values. • Objects: are instances of programmer-defined classes, • Resources: are special variables that hold references to resources external to PHP (such as database connections, image). PHP Constant A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). To create a constant, use the define() function. Syntax define(name, value, case-insensitive) Where • name: Specifies the name of the constant • value: Specifies the value of the constant • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false <?php define("PI", 3.14); echo PI; ?> Variables variable
  • 6. 6 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP It can reference the value of variable whose name is stored in another variable <?php $a='hello'; $$a='world'; echo $a; echo $$a; ?> o/p hello world Type Juggling PHP does not require (or support) explicit type definition in variable declaration, a variable's type is determined by the context in which the variable is used. The conversion of value from one type to another is called casting. This kind of implicit casting is called type juggling. <?php $x="9hello"-1; echo $x; $y="3.14 pile"*2; echo $y; ?> o/p 8 6.28 Operators 1.Arithmetic Operators Operator Name Example Result + Addition $x + $y Sum of $x and $y
  • 7. 7 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $y 2.Comparison Operators Operator Name Example Result == Equal $x == $y Returns true if $x is equal to $y $x = 100; $y = "100"; $x == $y =>true(Because values are equal) === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type $x = 100; $y = "100"; $x === $y =>false(Because types are not same) != Not equal $x != $y Returns true if $x is not equal to $y $x = 100; $y = "100"; $x != $y =>false(Because values are equal) <> Not equal $x <> $y Returns true if $x is not equal to $y $x = 100; $y = "100"; $x <> $y =>false(Because values are equal)
  • 8. 8 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type $x = 100; $y = "100"; $x !== $y =>true(Because types are not equal) > Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y 3.Logical operator Operator Name Example Result And And $x and $y True if both $x and $y are true Or Or $x or $y True if either $x or $y is true Xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true 4.Assignment operator Assignment Same as... Description x = y x = y The left operand gets set to the value of the expression on the right
  • 9. 9 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP x += y x = x + y Addition x -= y x = x - y Subtraction x *= y x = x * y Multiplication x /= y x = x / y Division x %= y x = x % y Modulus 5.Increment / Decrement Operators Operator Name Description ++$x Pre-increment Increments $x by one, then returns $x $x++ Post-increment Returns $x, then increments $x by one --$x Pre-decrement Decrements $x by one, then returns $x $x-- Post-decrement Returns $x, then decrements $x by one 6.PHP String Operators PHP has two operators that are specially designed for strings. OperatorName Example Result . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2 S $txt1 = "Hello"; $txt2 = " world!"; echo $txt1 . $txt2;how it »O/P Hello world! .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1 $txt1 = "Hello"; $txt2 = " world!"; echo $txt1 .= $txt2; O/P Hello world!
  • 10. 10 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Conditional Statements 1. if Statement if (condition) { code to be executed if condition is true; } 2.if...else Statement if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } 3. if...elseif....else Statement if (condition) { code to be executed if condition is true; } elseif (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } 4. switch Statement switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; } Loop 1.while Loop Syntax while (condition is true) { code to be executed; } e.g <?php $x = 1; 2.do...while Loop Syntax do { code to be executed; } while (condition is true); e.g
  • 11. 11 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP while($x <= 3) { echo "The number is: $x <br>"; $x++; } ?> <?php $x = 1; do { echo "The number is: $x <br>"; $x++; } while ($x <= 3); ?> 3.for Loop Syntax for (init counter; test counter; increment counter) { code to be executed; } e.g <?php for ($x = 0; $x <= 3; $x++) { echo "The number is: $x <br>"; } ?> There are two ways the browser client can send information to the web server. • The GET Method • The POST Method GET POST The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.e.g http://www.test.com/index.htm?name1=value1&name2=value2 he POST method transfers information via HTTP headers.e.g http://www.test.com/index.htm It is by default method It is not by default method
  • 12. 12 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP The GET method is restricted to send upto 1024 characters only. The POST method does not have any restriction on data size to be sent. GET method is not used for password or other sensitive information to be sent to the server. POST method is used for password or other sensitive information to be sent to the server. GET can't be used to send binary data to the server. POST can be used to send binary data to the server. 1.$_GET 1.It is global array that collect information from HTML form. 2.It is used to accept values from an html form sent with method is “get”. <html> <body> <form name=”frm” method=”get” action="http://localhost/b.php"> Enter value <input type=text name=t1> <input type="submit" name=b1 value=OK> </form> </body> </html> <?php $a=$_GET['t1']; echo $a; ?> 2.$_POST 1.It is global array that collect information from HTML form. 2.It is used to accept values from an html form sent with method is “post”. <html> <body> <form name=”frm” method=”post” action="http://localhost/b.php"> <?php $a=$_POST['t1']; echo $a; ?>
  • 13. 13 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Enter value <input type=text name=t1> <input type="submit" name=b1 value=OK> </form> </body> </html> Functions User Defined Functions A function is a block of statements that can be used repeatedly in a program. A function will be executed by a call to the function Create a User Defined Function Syntax function functionName() { code to be executed; } <?php function display() { echo "Hello world!"; } display(); // call the function ?>
  • 14. 14 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP PHP Function Arguments 1. <?php function add($a,$b) { $c=$a+$b; echo "Addition is $c<br>"; } add(2,3); ?> 2. <?php function display($fname, $year) { echo "fname is $fname<br>"; echo "year is $year<br>"; } display("vision",2004); ?> Returning values <?php function add($a,$b) { $c=$a+$b; return $c; } $c=add(2,3); echo "Addition is $c"; ?> Variables Scope
  • 15. 15 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP PHP has three different variable scopes: • local • global • static 1.Global A variable declared outside a function has a GLOBAL SCOPE They can be access from any part of the program. The global keyword is used to access a global variable from within a function <?php $x = 5; $y = 10; function add() { global $x, $y; $y = $x + $y; } add(); echo $y; // outputs 15 ?> PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. <?php $x = 5; $y = 10; function add() {
  • 16. 16 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } } add(); echo $y; // outputs 15 ?> 2.Local A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function <?php function display() { $y=5; echo $y; } display(); ?> 3.Static A static variable retains the value between calls to a function but it is visible only within that function <?php function display() { static $x=0; echo $x; $x++; } display (); display (); display (); ?>
  • 17. 17 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Default Argument Value <?php function add($a,$b=4) { $c=$a+$b; echo "Addition is $c<br>"; } add(2); ?> Variable-length argument lists(Variable parameter) PHP 4 and above has support for variable-length argument lists in user-defined functions. PHP provide 3 function intfunc_num_args ( ) Returns the number of arguments passed into the current user-defined function. array func_get_args ( ) It return array of all parameter provided to the function. mixedfunc_get_arg ( int arg_num) It return a specific argument from the parameter. <?php function display() { for($i=0;$i<func_num_args();$i++) { echo func_get_arg($i); } }
  • 18. 18 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP display(1,2,3); ?> Variable functions PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. <?php function disp1() { echo "disp1 fuction <br>"; } function disp2($arg) { echo "disp2 function $arg"; } $func = 'disp1'; $func(); $func = 'disp2'; $func("hello"); ?> Anonymous functions PHP allows programmer to write the function without name is called anonymous. To create anonymous function create_function is used Syntax stringcreate_function ( string$args , string$code )
  • 19. 19 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP <?php $newfunc = create_function('$a,$b', 'return ($a + $b);'); echo $newfunc(2, 3); ?> Missing Parameter when you call a function, you can pass any number of arguments to the function. Any parameters the function that are not passed to it remain unset, and a warning is issued for each of them <?php function show( $a, $b ) { if (isset($a)) echo " a is set"; if (isset($b)) echo " b is set"; } show(2); ?> o/p warning :missing argument two a is set String A string type can be specified in 3 different ways: 1 single quoted 2 double quoted 3 heredoc 1 Single quoted String PHP support the strings to be enclosed in single quotes.Single quoted string do not interpolate variables.The variables name in the string is not expanded except escape sequence character.
  • 20. 20 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP <?php $a=5; echo 'Value is $a'; ?> o/p value is $a 2.Double quoted string Double quoted strings interpolate variables and expand the many PHP escape sequences. <?php $a=5; echo “Value is $a”; ?> o/p value is 5 3. using heredoc Single quoted & double quoted string allow strings in single line. To write multiline strings into the program a heredoc is used. The <<< identifier is used in PHP,to tell the language that the string is written with heredoc. The space before after the <<< is essential. The text starts on the second line & continue until it reaches a line that consist of nothing but identifier <?php $a= <<<ed It is php It is server script ed; echo $a;
  • 21. 21 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP ?> Printing String 1. echo The echo() allow to print many strings. Syntax echo(strings) <?php $str1="Hello world!"; $str2="What a nice day!"; echo $str1 . "" . $str2; ?> 2.print The print() allow to print one or more strings. Syntax print(strings) <?php $str1="Hello world!"; $str2="What a nice day!"; print $str1 . "" . $str2; ?> Note:The print() function is slightly slower than echo(). 3.printf The printf() function outputs a formatted string. It is similar to printf() function in c Language.
  • 22. 22 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP %d - Signed decimal number (negative, zero or positive) %f - Floating-point number (local settings aware) %s - String Syntax printf(format,arg1,arg2,arg++) <?php $name="amol"; $age=18; printf("name is %s",$name); printf("age is %d",$age); ?> 4.print_r The print_r() debugging function used to print human-readable information about a variable. Syntax Return value print_r(expression) Where Expression=>The expression to be printed Return value=>To capture the output in a variable, parameter should set TRUE. Default value is FALSE. <?php $name="amol"; print_r($name); ?> o/p amol <?php
  • 23. 23 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP $a = array('name'=>'amol','class'=>'ty'); print_r($a); ?> o/p Array ( [name] => amol [class] => ty ) 5.var_dump() The var_dump()debugging function is used to display structured information (type and value) about one or more variables Syntax var_dump(variable1); <?php $a=4; $b=1.5; echo var_dump($a); echo var_dump($b); ?> o/p int 4 float 1.5 <?php $a = array('name'=>'amol','class'=>'ty'); echo var_dump($a); ?> o/p array 'name' => string 'amol'(length=4) 'class' => string 'ty'(length=2)
  • 24. 24 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Difference var_dump & print_r 1.The var_dump() function displays structured information (type and value) about one or more variables. 2.The print_r() function displays human-readable information about a variable. 3.print_r function loops infinitely while var_dump cuts off after visiting the same element three times Array in php Array: An array is a data structure that stores one or more similar type of values in a single value. 1.Single dimension array PHP array type 1.Indexed array - An array with a numeric index. Values are stored and accessed in linear fashion.index always start with 0 Display array without using array function Displaying array using loop(using array function) Displaying array using print_r <?php $a[0] = 1; $a[1] = 2; $a[2] = 3; print_r($a) ?> o/p Array ( [0] => 1 [1] => 2 [2] => 3 ) <?php $a = array(1,2,3); $len = count($a); for($i = 0; $i < $len; $i++) { echo $a[$i]; echo "<br>"; } ?> o/p 1 2 3 <?php $a = array(1,2,3); print_r($a); ?> o/p Array ( [0] => 1 [1] => 2 [2] => 3 ) 2.Associative Array:An array with a string index(key)
  • 25. 25 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Display array without using array function Display array using array function & foreach loop Displaying array using print_r <?php $a['rollno'] = "1"; $a['name’] = "amol"; $a['class'] = “ty”; print_r($a); ?> o/p Array ( [rollno] => 1 [name] => amol [class] => ty) <?php $a = array("rollno"=>"1", "name"=>"amol", "class"=>"ty"); foreach($a as $x => $val) { echo "Key=" . $x ; echo " Value=".$val; echo "<br>"; } ?> o/p Key=rollno Value=1 Key=name Value=amol Key=class Value=ty <?php $a = array("rollno"=>"1", "name"=>"amol", "class"=>"ty"); print_r($a); ?> o/p Array ( [rollno] => 1 [name] => amol [class] => ty) Traversing Array in php 1 Using foreach loop Syntax foreach ($array as$value) { // code } Numeric index array Associative array <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> o/p red green <?php $a = array("rollno"=>"1", "name"=>"amol", "class"=>"ty"); foreach($a as $x => $val) { echo "Key=" . $x ; echo " Value=".$val; echo "<br>"; } ?>
  • 26. 26 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP yellow o/p Key=rollno Value=1 Key=name Value=amol Key=class Value=ty 2.Using loop(while or for loop) <?php $a = array(1,2,3); $len = count($a); for($i = 0; $i < $len; $i++) { echo $a[$i]; echo "<br>"; } ?> o/p 1 2 3 3.Using iterator function 1.current():Returns the element currently pointed by the iterstor 2.next():Moves the iterator to the next element in the array & return it. 3.prev():Moves the iterator to the previous element in the array & return it. 4.reset():Moves the iterator to the first element in the array & return it. 5.end():Moves the iterator to the end element in the array & return it. <?php $colors = array("red", "green", "blue", "yellow"); echo "<br> current element".current($colors); echo "<br> next element".next($colors); echo "<br> prevous element".prev($colors); echo "<br> reset element".reset($colors); echo "<br> end element".end($colors); ?>
  • 27. 27 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 2.Multidimensional Arrays A multidimensional array is an array containing one or more arrays. 2D array 1.Indexed array Display array without using array function Display array using array function Display array using print_r function <?php $a[0][0]=1; $a[0][1]=2; $a[1][0]=33; $a[1][1]=22; for($i=0;$i<count($a);$i++) { for($j=0;$j<count($a[$i]);$j++) { echo $a[$i][$j]."<br>"; } } ?> <?php $a=array(array(1,2), array(33,22)); for($i=0;$i<count($a);$i++) { for($j=0;$j<count($a[$i]);$j++) { echo $a[$i][$j]."<br>"; } } ?> <?php $a=array(array(1,2), array(33,22)); print_r($a); ?> o/p Array ( [0] => Array ( [0] => 1 [1] => 2 ) [1] => Array ( [0] => 33 [1] => 22 ) ) Display array using foreach <?php $a=array(array(1,2), array(33,22)); $a=array(array(1,2), array(33,22)); foreach($a as $v1) { foreach($v1 as $v2) { echo $v2."<br>"; } } ?>
  • 28. 28 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 2.Associative Array Display array using array function Display array using print_r function <?php $a=array( array("rollno"=>"1", "name"=>"amol", "class"=>"ty"), array("rollno"=>"2", "name"=>"amit", "class"=>"ty"), ); for($i=0;$i<2;$i++) { foreach($a[$i] as $key=>$val) { echo $val; } echo "<br>"; } ?> <?php $a=array( array("rollno"=>"1", "name"=>"amol", "class"=>"ty"), array("rollno"=>"2", "name"=>"amit", "class"=>"ty"), ); print_r($a); ?> o/p Array ( [0] => Array ( [rollno] => 1 [name] => amol [class] => ty ) [1] => Array ( [rollno] => 2 [name] => amit [class] => ty ) ) Sorting Array 1.Sort 2.rsort 3.asort The sort() function sorts an indexed array in ascending order. <?php $a=array(4,6,2,); sort($a); print_r($a); ?> o/p Array ( [0] => 2 [1] => 4 [2] => 6 ) The rsort() function sorts an indexed array in descending order. <?php $a=array(4,6,2); rsort($a); print_r($a); ?> o/p Array ( [0] => 6 [1] => 4 [2] => 2 ) Sort an associative array in order, according to the valu <?php $a=array("amol"=>"16","a asort($a); print_r($a); ?> o/p Array ( [amit] => 13 [amol 4.ksort 5.arsort 6.krsort
  • 29. 29 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Sort an associative array in ascending order, according to the key <?php $a=array("amol"=>"13","amit"=>"16"); ksort($a); print_r($a); ?> o/p Array ( [amit] => 16 [amol] => 13 ) Sort an associative array in descending order, according to the value <?php $a=array("amol"=>"11","amit"=>"14"); arsort($a); print_r($a); ?> o/p Array ( [amit] => 14 [amol] => 11 ) Sort an associative array in order, according to the key <?php $a=array("amol"=>"13","a krsort($a); print_r($a); ?> o/p Array ( [amol] => 13 [amit array_multisort() array_multisort() function is used to sort multiple arrays Syntax array_multisort(array1,array2,array3...) <?php $a1=array("Dog","Cat"); $a2=array("Fido","Missy"); array_multisort($a1,$a2); print_r($a1); print_r($a2); ?> o/p Array ( [0] => Cat [1] => Dog ) Array ( [0] => Missy [1] => Fido )
  • 30. 30 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Converting between array &variables Creating variable from a array Creating array from variable 1.extract 2.Compact This function atomically creates local variable from a array Syntax extract(arrayname) <?php $a = array("rollno"=>"1", "name"=>"amol", "class"=>"ty"); extract($a); echo $rollno; echo $name; echo $class; ?> o/p 1 amol ty It Create an array from variables Syntax compact(var1,var2...) <?php $rollno = 1; $name = "amol"; $a = compact("rollno","name"); print_r($a) ?> o/p Array ( [rollno] => 1 [name] => amol ) Adding & Removing array function 1.Array_push() 2.Array_pop() The array_push() function inserts one or more elements to the end of an array. Syntax array_push(array,value1,value2...) The array_pop() function deletes the last element of an array. Syntax array_pop(array) <?php
  • 31. 31 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP <?php $a=array("red"); array_push($a,"yellow"); print_r($a); ?> o/p Array ( [0] => red [1] => yellow ) $a=array("red","yellow"); array_pop($a); print_r($a); ?> o/p Array ( [0] => red ) 3.array_filter() 4.array_splice() The array_filter() function filters the values of an array using a callback function Syntax array_filter(array,callbackfunction); <?php function test_odd($var) { if($var%2!=0) return(1); } $a1=array(2,3,4); print_r(array_filter($a1,"test_odd")); ?> o/p 3 It removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Syntax array_splice(array,start,length,array) <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"purple","b"=>"orange"); array_splice($a1,0,2,$a2); print_r($a1); ?> o/p Array ( [0] => purple [1] => orange [c] => blue [d] => yellow ) 5.Array_flip() 6.shuffle The array_flip() function flips/exchanges all keys with their associated values in an array Syntax array_flip(array); <?php The shuffle() function randomizes the order of the elements in the array. Syntax shuffle(array) <?php
  • 32. 32 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP $a1=array("a"=>"red","b"=>"green"); $result=array_flip($a1); print_r($result); ?> o/p "c"=>"blue","d"=>"yellow" $my_array = array("a"=>"red","b"=>"green"); shuffle($my_array); print_r($my_array); ?> o/p Array ( [0] => green [1] => red ) 7.count 8.array_merge The count() function returns the number of elements in an array <?php $cars=array("green","red"); echo count($cars); ?> o/p 2 The array_merge() function merges one or more arrays into one array. Syntax array_merge(array1,array2,array3...) <?php $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2)); ?> o/p Array ( [0] => red [1] => green [2] => blue [3] => yellow ) 9.array_intersect 10 array_diff The array_intersect() function compares the values of two (or more) arrays, and returns the matches. Syntax array_intersect(array1,array2,array3...); <?php $a1=array("red","yellow"); $a2=array("blue","yellow"); print_r(array_intersect($a1,$a2)); ?> Array ( [1] => yellow ) The array_diff() function compares the values of two (or more) arrays, and returns the differences. Syntax array_diff(array1,array2,array3...); <?php $a1=array("red","yellow"); $a2=array("blue","yellow"); print_r(array_diff($a1,$a2)); ?> o/p Array ( [0] => red ) 11 array_shift 12 array_unshift The array_shift() function removes the first element from an array, and returns the value of the removed element. The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array.
  • 33. 33 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Syntax array_shift(array) <?php $a=array("red","green","blue"); echo array_shift($a); print_r ($a); ?> o/p red Array ( [0] => green [1] => blue ) Syntax array_unshift(array,value1,value2,value3...) <?php $a=array("red","green"); array_unshift($a,"blue"); print_r($a); ?> o/p Array ( [0] => blue [1] => red [2] => green ) Union <?php $a1=array("red","green"); $a2=array("red","yellow"); $m=array_merge($a1,$a2)); $u=array_unique($m); print_r($u); ?>
  • 34. 34 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP COMPARING FUNCTION 1.EXACT COMPRISION 1.strcmp() Compare two strings (case-sensitive) &This function returns following result: • 0 - if the two strings are equal • <0 - if string1 is less than string2 • >0 - if string1 is greater than string2 Syntax strcmp(string1,string2); <?php echo strcmp("Hello","Hello"); ?> o/p 0 2. strcasecmp() The strcasecmp() function compares two strings but case-insensitive & return below result • 0 - if the two strings are equal • <0 - if string1 is less than string2 • >0 - if string1 is greater than string2 Syntax strcasecmp(string1,string2); <?php echo strcasecmp("Hello","hello"); ?> o/p 0 3. strncmp()(case sensitive) Strings comparison of first n characters(case sensitive) &This function returns following result: 4.strncasecmp() String comparison of the first n characters (case-insensitive) insensitive & return below result
  • 35. 35 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 2. APPROXIMATE EQUALITY 1.soundex() 2.metaphone() 3.similar_text() This function see whether two strings are approximate equal in their pronunciation. metaphone() is more accurate than soundex(), because metaphone() knows the basic rules of English pronunciation syntax soundex(string) metaphone(string) <?php $v1=”no”; $v2=”know”; If(soundex($v1)==soundex($v2)) The similar_text() function calculates the similarity between two strings. It can also calculate the similarity of the two strings in percent Syntax. similar_text(string1,string2,percent) Parameter Description string1 Required. Specifies the first string to be compared string2 Required. Specifies the second string to be compared • 0 - if the two strings are equal • <0 - if string1 is less than string2 • >0 - if string1 is greater than string2 Syntax strncmp(string1,string2,length) <?php echo strncmp("Hello","Hello",2); ?> o/p 0 • 0 - if the two strings are equal • <0 - if string1 is less than string2 • >0 - if string1 is greater than string2 Syntax strncmp(string1,string2,length) <?php echo strncasecmp("Hello world!","hello earth!",6); ?> o/p 0
  • 36. 36 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP echo “$v1 sound $v2 using soundex”; else echo “$v1 not sound $v2 using soundex”; echo "<br>"; If(metaphone ($v1)== metaphone ($v2)) echo “$v1 sound $v2 using metapone”; else echo “$v1 not sound $v2 using metaphone”; ?> o/p percent Optional. Specifies a variable name for storing the similarity in percent Return Value: Returns the number of matching characters of two strings <?php $c=similar_text("Hello World","HelloPeter",$percent); echo $percent; echo $c; ?> o/p 4.levenshtein() This function calculates the similarity of two string based on how many characters must be added, substituted or remove to make them the same. Syntax levenshtein(string1,string2,insert,replace,delete) Parameter Description string1 Required. First string to compare string2 Required. Second string to compare Insert Optional. The cost of inserting a character. Replace Optional. The cost of replacing a character. Delete Optional. The cost of deleting a character. Return Value: Returns the Levenshtein distance between the two argument strings or -1
  • 37. 37 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP <?php $c=levenshtein("sun","son"); echo $c; ?> o/p 1 3.Manipulating & Searching String 1.substr() 2.substr_count() The substr() function returns a part of a string Syntax substr(string,start,length) ParameterDescription String Required. Specifies the string to return a part of Start Required. Specifies where to start in the string Length Optional. Specifies the length of the returned string. Default is to the end of the string. <?php $c=substr("hello world",3); echo $c; ?> o/p The substr_count() function counts the number of times a substring occurs in a string. Syntax substr_count(string,substring,start,length) ParameterDescription String Required. Specifies the string to check substring Required. Specifies the string to search for Start Optional. Specifies where in string to start searching Length Optional. Specifies the length of the search Return Value: Returns the the number of times the substring occurs in the string <?php $str="That is php is"; echo substr_count($str,"is");
  • 38. 38 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP lo world ?> o/p 2 3.substr_replace() The substr_replace() function replaces a part of a string with another string. Syntax substr_replace(string,replacement,start,length) Parameter Description String Required. Specifies the string to check Replacement Required. Specifies the string to insert Start Required. Specifies where to start replacing in the string Length Optional. Specifies how many characters should be replaced. Default is the same length as the string. Return Value: Returns the replaced string. <?php echo substr_replace("Hello world","earth",6); ?> o/p
  • 39. 39 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP strpos() The strpos() function finds the position of the first occurrence of a string inside another string. Syntax strpos(string,find,start) <?php echo strpos(“bcs is”,”is"); ?> o/p 4 strstr() Function The strstr() function searches for the first occurrence of a string inside another string. strstr(string,search,before_search) Parameter Description String Required. Specifies the string to search Search Required. Specifies the string to search for. before_search Optional. A boolean value whose default is "false". If set to "true", it returns the part of the string before the first occurrence of the search parameter. <?php echo strstr("Hello world!","world",true); ?> o/p world!
  • 40. 40 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP strrchr() The strrchr() function finds the position of the last occurrence of a string within another string, and returns all characters from this position to the end of the string. Syntax strrchr(string,char) <?php echo strrchr("Hello world! What a beautiful day!",What); ?> o/p What a beautiful day! Decomposition a string function 1 explode Split a string by string & return array. Syntax explode(separator,string,limit) separator Required. Specifies where to break the string string Required. The string to split limit 2 Implode Join array elements with a string Syntax implode(separator,array) separator Optional. Specifies what to put between the array elements. Default is "" (an empty string) Array Required. The array to join to a string
  • 41. 41 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Optional. Specifies the number of array elements to return. <?php // Example 1 $a = "hello world"; $p = explode(" ", $a); print_r($p); ?> o/p Array ( [0] => hello [1] => world ) <?php $a = array('lastname', 'email', 'phone'); $c = implode(" ", $a); echo $c; ?> o/p lastname,email,phone
  • 42. 42 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 3.strtok() The strtok() function splits a string into smaller strings (tokens). Syntax strtok(string,split) string Required. Specifies the string to split split Required. Specifies one or more split characters <?php $string = "Hello bcs"; $token = strtok($string, ""); while ($token !== false) { echo "$token<br>"; $token = strtok(""); } ?> o/p Hello bcs ENCODING ESCAPING FUNCTION
  • 43. 43 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 1.Htmlentities 2. htmlspecialchars This function changes all characters with HTML entity into equivalent(except space character).This include less then(<),greater than(>),ampersand(&). Syntax htmlentities(string,flags,character- set,double_encode) Parameter Description String Required. Specifies the string to convert Flags Optional. Specifies how to handle quotes, invalid encoding and the used document type. The available quote styles are: • ENT_COMPAT - Default. Encodes only double quotes • ENT_QUOTES - Encodes double and single quotes • ENT_NOQUOTES - Does not encode any quotes The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are: • & (ampersand) becomes &amp; • " (double quote) becomes &quot; • ' (single quote) becomes &#039; • < (less than) becomes &lt; • > (greater than) becomes &gt; Syntax htmlspecialchars(string,flags,character- set,double_encode) <?php $str = "hello &'ok'"; echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes echo "<br>"; echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes echo "<br>"; echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes ?> o/p hello &amp; 'ok'<br> hello &amp; &#039;ok&#039;<br>
  • 44. 44 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP character-set Optional. A string that specifies which character- set to use. Allowed values are: double_encode Optional. A boolean value that specifies whether to encode existing html entities or not. TRUE - Default. Will convert everything & FALSE - Will not encode existing html entities <?php $str = "<&hello>"; echo htmlentities($str); ?> o/p &lt;&amp;hello&gt; hello &amp; 'ok' ---------------------------------------------- 3.strip_tags ---------------------------------------------- The strip_tags() function strips a string from HTML, XML, and PHP tags. Syntax strip_tags(string,allow) string Required. Specifies the string to check allow Optional. Specifies allowable tags. These tags will not be removed <?php echo strip_tags("Hello <b>"); ?> o/p Remove <b> tag Regular Expression A regular expression is a string that represent a pattern. The regular expression function compare that pattern to another string &check if any of the string matches the pattern. There are 2 types of regular expression 1. POSIX Regular Expressions 2. PERL Style Regular Expressions
  • 45. 45 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP POSIX regular expression are less powerful & slower then PERL ExpressionDescription [0-9] It matches any decimal digit from 0 through 9. [a-z] It matches any character from lowercase a through lowercase z. [A-Z] It matches any character from uppercase A through uppercase Z. [a-Z] It matches any character from lowercase a through uppercase Z. Quantifiers ExpressionDescription p+ [a-z]+ It matches any string containing at least one p. p* [a-z]* It matches any string containing zero or more p's. p? It matches any string containing zero or more p's. This is just an alternative way to use p*. p{N} It matches any string containing a sequence of N p's p{2,3} It matches any string containing a sequence of two or three p's.
  • 46. 46 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP p{2, } It matches any string containing a sequence of at least two p's. p$ It matches any string with p at the end of it. ^p It matches any string with p at the beginning of it. 1.ereg 2.ereg_replace The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.(case sensitive) <?php if(ereg("^[a-z]+$","amol")==null) echo "true"; else echo "false"; ?> o/p true This function scans string for matches to pattern, then replaces the matched text with replacement. <?php $string = "This is a test"; echo ereg_replace(" is", " was", $string); ?> O/P This was a test 3.eregi 4.split The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive <?php if(eregi("^[a-z]+$","amol")==null) echo "true"; else echo "false"; ?> o/p The split() function will divide a string into various elements. <?php $ip = "123.456"; $p = split (".", $ip); echo "$p[0]"; print_r($p); echo "$p[1]"; ?> o/p 123 456
  • 47. 47 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP true
  • 48. 48 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP FILE 1.fopen() The fopen() function opens a file Syntax fopen(filename,mode) File mode as follows • "r" (Read only. Starts at the beginning of the file) • "r+" (Read/Write. Starts at the beginning of the file) • "w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist) • "w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist) • "a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist) • "a+" (Read/Write. Preserves file content by writing to the end of the file) • "x" (Write only. Creates a new file. Returns FALSE and an error if file already exists) • "x+" (Read/Write. Creates a new file. Returns FALSE and an error if file already exists) e.g $file = fopen("test.txt","r"); 2.fclose() The fclose() function closes an open file Syntax fclose(file) e.g fclose($file)
  • 49. 49 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 3.fread() Function The fread() reads from an open file. The function will stop at the end of the file or when it reaches the specified length Syntax fread(file,length) Parameter Des File Required. Specifies the open file to read from Length Required. Specifies the maximum number of bytes to read e.g fread($file,"10"); 4.fwrite() or fputs() The fwrite() writes to an open file. Syntax fwrite(file,string,length) File Required. Specifies the open file to write to String Required. Specifies the string to write to the open file length Optional. Specifies the maximum number of bytes to write e.g fwrite($file,"Hello World. Testing!");
  • 50. 50 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP fgetc() The fgetc() function returns a single character from an open file Syntax fgetc(file) file Required. Specifies the file to check e.g echo fgetc($file) fgets() The fgets() function returns a line from an open file. Syntax fgets(file,length) File Required. Specifies the file to read from length Optional. Specifies the number of bytes to read. Default is 1024 bytes. e.g echo fgets($file); unlink() The unlink() function deletes a file. Syntax unlink(filename) e.g unlink($file) basename() Syntax basename(path) $path = "/testweb/home.php"; echo basename($path); o/p home.php • To Write a data into a file <?php $file = fopen("test.txt","w") or die(“can’t open file”); echo fwrite($file,"Hello World. Testing!"); fclose($file); ?>
  • 51. 51 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP • To read a file from a file <?php $file = fopen("t.txt","r") or die(“can’t open file”); echo fread($file,filesize("t.txt")); fclose($file); ?> Or <?php $file = fopen("t.txt","r") or die(“can’t open file”); while($ch=fgetc($file)) { echo $ch; } fclose($file);
  • 52. 52 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP file() The file() reads a file into an array. Syntax file(path,include_path,context) Path Required. Specifies the file to read include_path Optional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well Context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL. <?php $p=file("test.txt"); print_r($p); ?> fpassthru() The fpassthru() function reads all data from the current position in an open file, until EOF, and writes the result to the output buffer Syntax fpassthru(file) file Required. Specifies the open file or resource to read from <?php $file = fopen("test.txt","r"); // Read first line fgets($file); // Send rest of the file to the output buffer echo fpassthru($file); fclose($file); ?>
  • 53. 53 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP readfile() The readfile() function reads a file and writes it to the output buffer Syntax readfile(filename,include_path,context) <?php $preadfile("test.txt"); echo $p; ?> Random Access to file
  • 54. 54 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP fseek() The fseek() function seeks in an open file. Syntax fseek(file,offset,whence) Offset Required. Specifies the new position (measured in bytes from the beginning of the file) Whence Optional. (added in PHP 4). Possible values: • SEEK_SET - Set position equal to offset. Default • SEEK_CUR - Set position to current location plus offset • SEEK_END - Set position to EOF plus offset (to move to a position before EOF, the offset must be a negative value) e.g <?php $file = fopen("test.txt","r"); // read first line fgets($file); // move back to beginning of file fseek($file,0); ?> ftell() The ftell() function returns the current position in an open file Syntax ftell(file) $file = fopen("test.txt","r"); echo ftell($file);
  • 55. 55 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP rewind() The rewind() function "rewinds" the position of the file pointer to the beginning of the file Syntax rewind(file) $file = fopen("test.txt","r"); fseek($file,"15"); //Set file pointer to 0 rewind($file); ftell() The ftell() function returns the current position in an open file Syntax ftell(file) $file = fopen("test.txt","r"); echo ftell($file); Getting information on File file_exists() The file_exists() function checks whether or not a file or directory exists. Syntax Boolean file_exists(path) <?php echo file_exists("test.txt"); ?> Filesize The filesize() function returns the size of the specified file.This function returns the file size in bytes on success or FALSE on failure. Syntax filesize(filename) <?php echo filesize("test.txt"); ?>
  • 56. 56 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP filectime() The filectime() function returns the last time the specified file was changed. Syntax filectime(filename) e.g echo "Last change: ".date("F d Y H:i:s.",filectime("test.txt")); filemtime() The filemtime() function returns the last time the file content was modified. Syntax filemtime(filename) e.g echo "Last modified: ".date("F d Y H:i:s.",filemtime("test.txt")); pathinfo() The pathinfo() function returns an array that contains information about a path. Syntax pathinfo(path,options) <?php print_r(pathinfo("/bcs/test.txt")); ?> o/p Array ( [dirname] => /testweb [basename] => test.txt [extension] => txt )
  • 57. 57 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP stat() The stat() function returns information about a file. This function returns an array with the following elements: • [0] or [dev] - Device number • [1] or [ino] - Inode number • [2] or [mode] - Inode protection mode • [3] or [nlink] - Number of links • [4] or [uid] - User ID of owner • [5] or [gid] - Group ID of owner • [6] or [rdev] - Inode device type • [7] or [size] - Size in bytes • [8] or [atime] - Last access (as Unix timestamp) • [9] or [mtime] - Last modified (as Unix timestamp) • [10] or [ctime] - Last inode change (as Unix timestamp) • [11] or [blksize] - Blocksize of filesystem IO (if supported) • [12] or [blocks] - Number of blocks allocated Syntax stat(filename) e.g $stat = stat('test.txt'); echo 'file size: ' .$stat['size']; Ownership & permission
  • 58. 58 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP posix_getpwuid() Return info about a user by user id Syntax array posix_getpwuid ( int $uid ) • name: The username. • passwd: Contents of the passwd field (may be x or similar on systems with shadow passwords enabled). • uid: The user ID. • gid: The group ID. • gecos: Contents of the GECOS field; intended to hold the user's real name. GECOS stands for 'General Electric Comprehensive Operating System', for historical reasons. • dir: The user's home directory. • shell: The user's login shell (e.g. /bin/bash). e.g $userinfo = posix_getpwuid(10000); print_r($userinfo); fileowner():Return USER ID of specfied file filegroup():Return Group ID of specified file file_type():Return type of the file Is_dir():Return true if true as directory Is_file(): Return true if true as file Working with directories
  • 59. 59 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP opendir() Open a directory, read its contents, then close. Syntax opendir(path); path Required. Specifies the directory path to be opened readdir() Open a directory, read its contents, then close //list of entries which is specified by directory handle Syntax readdir(dir_handle); dir_handle Optional. Specifies the directory handle resource <?php $dir = "/bcs/"; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { echo "filename:" . $file . "<br>"; } closedir($dh); } } ?> closedir() Open a directory, read its contents, then close. Syntax closedir(dir_handle); chdir() Change the current directory Syntax chdir(directory); e.g chdir("images");
  • 60. 60 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP dir() Use the dir() function Syntax dir(directory) <?php $d = dir(getcwd()); echo "Handle: " . $d->handle . "<br>"; echo "Path: " . $d->path . "<br>"; while (($file = $d->read()) !== false){ echo "filename: " . $file . "<br>"; } $d->close(); ?> scandir() List files and directories inside the specified directory Syntax scandir(directory) <?php $dir = "/bcs/"; $a = scandir($dir); print_r($a); ?> PHP include and require Statements To insert the content of one PHP file into another PHP file with the include or require statement is used. Syntax include 'filename'; or require 'filename'; The include and require statements are identical, except upon failure: • require will produce a fatal error (E_COMPILE_ERROR) and stop the script • include will only produce a warning (E_WARNING) and the script will continue
  • 61. 61 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP e.g a.php <?php Hello ?> b.php <?php include ‘a.php'; ?>
  • 62. 62 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Databases There are two approaches to access databases from PHP. 1.Use a Database –specific extension. 2.Use the database –independent PEAR DB library. 1.Use a Database –specific extension. This done by following steps. 1. Create a connection to MySQL/Postgres Database. 2. Create a database (can be done in MySql/Postgres) 3. Create a table(Can be done in MySql/Postgres) 4. Execute Query(Select or any other) 5. Display Result in an HTML Table. 6 Close the connection. 1.pg_connect pg_connect() opens a connection to a PostgreSQL database specified by the connection_string. Syntax resource pg_connect ( string $connection_string ) connection string contains host, hostaddr, port, dbname,password etc 2.pg_query pg_query() executes the query on the specified database Syntax resource pg_query ([ resource $connection ], string $query )
  • 63. 63 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 3.pg_fetch_row pg_fetch_row() fetches one row of data from the result associated with the specified result resource Syntax array pg_fetch_row ( resource $result [, int $row ] ) 4.pg_close() Closes a PostgreSQL connection Syntax bool pg_close ([ resource $connection ] ) • To retrieve data from database <?php $con=pg_connect("host=localhost dbname=ty user=root")or die("Unable to connect"); $q="select * from stud"; $res=pg_query($con,$q) or die("Unable to execute query"); while($r1=pg_fetch_row($res)) { echo $r1[0]."<br>"; echo $r1[1]."<br>"; } pg_close($con); ?>
  • 64. 64 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP • To insert data into database <?php $con=pg_connect("host=localhost dbname=ty user=root")or die("Unable to connect"); $s1=111; $s2='ram'; $q="insert into stud values($s1,$s2)"; pg_query($con,$q) or die("Unable to insert query"); echo "insert successfully"; pg_close($con); ?> • Update data into database <?php $con=pg_connect("host=localhost dbname=ty user=root")or die("Unable to connect"); $s1=111; $s2='ram'; $q="update stud set sname='$s2' where rollno=$s1"; pg_query($con,$q) or die("Unable to update query"); echo "update successfully"; pg_close($con); ?> • Delete from database <?php $con=pg_connect("host=localhost dbname=ty user=root")or die("Unable to connect");
  • 65. 65 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP $s1=111; $q="delete from stud where rollno=$s1"; pg_query($con,$q) or die("Unable to delete query"); echo "delete successfully"; pg_close($con); ?> PEAR DB BASICS PEAR stands for PHP Extension and Application Repository. 1.PEAR DB library is object oriented. It provide mixture of class methods such as DB::connect(),DB::iserror() etc. 2.PEAR DB is portable. It allowed to use single API to work with many different type of databases. 3. Code Simplification Application involved multiple databases , It normally to learn the API for each of the databases. but using pear db allow to work with all databases using single API. PEAR DB codes the functions are generic 4. It provide a number of open source collection of free PHP modules and classes for many different function. <?php include_once('DB.php'); $user = "root"; $pwd = ""; $host = "localhost"; Web Browser Apache PHP Engine PEAR DB pgSql,Mysql driver Database Server
  • 66. 66 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP $database = "bca"; $dsn = “pgsql://$user:$pwd@$host/$database"; $db = DB::connect($dsn); if (DB::isError($db)) { die($db->getMessage()); } else { $r = $db->query("SELECT * FROM student"); while ($r->fetchInto($row)) { echo $row[0]; echo $row[1]; } $r->free(); } $db->disconnect(); ?> 1.Data Source Names A data source name(DSN) is a string that specifies where the database is located, what kind of database it is, the username and password to use when connecting to the database, and more. The components of a DSN are assembled into a URL-like string: type(dbsyntax)://username:password@protocol+hostspec/database Where Type:(Compulsory)which specifies the PHP database backend to use. The following lists the implemented database types at the time of writing. Name Database Mysql MySQL Pgsql PostgreSQL
  • 67. 67 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Ibase InterBase Msql Mini SQL Mssql Microsoft SQL Server oci8 Oracle 7/8/8i Odbc ODBC Sybase SyBase Ifx Informix Fbsql FrontBase Eg. The following valid DSN mysql://php_data:Only database name mysql://localhost/php_data:server name +database name. mysql://user@localhost/php_data:user+servername+database name mysql://user@tcp+localhost/php_data:user+protocol+server name+ database name mysql://user:user123@localhost/php_data:user+password+server name+ database name 2.Connecting to the database DB::connect() After a DSN is created ,establish a connection to the database using the connect() method Syntax: $db=DB::connect(DSN[,option]); DSN:Data source name Where option is Option Controls persistent Connection persists between accesses
  • 68. 68 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP optimize What to optimize for debug Display debugging information 3.Checking Errors DB::ISERROR This method is used to return if error occurs. if (DB::isError($db)) { die($db->getMessage()); } 4. Issuing Query Query() Using this method SQL query can be sent to the database If SQL statements as INSERT,UPDATE,DELETE are executed successfully then the function returns DB_OK message. Sr=$db->query(sql); 5.Fetching result from query It provides have 2 method for fetching data from a query result object. 1.Returing the row fetchRow():This method on a query result returns an array of the next row of result Syntax: $row=$r->fetchRow([mode]); Mode:(optional) It controls the format of the result array return 1. DB_FETCHMODE_ORDERED: Default value. 2. DB_FETCHMODE_ASSOC: It creates an array whose value keys are the column name and whose values are the values from column.
  • 69. 69 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP ON success it return an array of data It return NULL if there is no more data while ($row = $result->fetchRow( )) { --- } 2.Storing Row This method also returns the next row, but stores it into the array variable passed as parameter Syntax: $var=$result->fetchInto(array,[mode])); Array:array variable into which result will be stored while ($success = $result->fetchInto($row)) { -- } 6. Free up memory Free() The function is used to free up the memory consumed by the query. The memory is returned to the operating system. This is required since a query result object usually holds all rows returned by the query. $r->free() 7.Discconnected Database Disconnected() $db->disconnected() Advantage and Disadvantage of two approach 1.If we use database-specific extension, then the code is very much tied to that database only. So changing one database to other involves many changes in the code.
  • 70. 70 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 2PEAR DB approach is quit different than this and it is not bound to any specific database. It is object oriented approach. Advanced Database Techniques 1.Placeholders While writing query like insert or update, it can put a placeholder “?” in place of specific value Syntax $result = $db->query(SQL, values); Where Sql: either insert or update with a placeholder value Values:The array of values to insert or update into the SQL e.g $stud = array(array(1,’amol’),array(2,’amit’),array(3,’sagar’)); foreach ($stud as $s) { $db->query('INSERT INTO stud (rollno,sname) VALUES (?,?)', $s); } There are three characters that you can use as placeholder values in an SQL query: ? A string or number, which will be quoted if necessary (recommended) | A string or number, which will never be quoted & A filename, the contents of which will be included in the statement 2. Prepare/Execute When issuing the same query repeatedly, it can be more efficient to compile the query once and then execute it multiple times, using theprepare( ), execute( ), and executeMultiple( )methods.
  • 71. 71 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 1.prepare():The first step is to call prepare()method on the query. This method is used to create a generic statement. $compiled = $db->prepare(SQL); 2.execute():After preparing the statement it can execute query. $response = $db->execute(compiled, values); The values array contains the values for the placeholders in the query. The return value is either a query response object, or DB_ERROR if an error occurred. For example, we could insert multiple values into the stud table like this: $stud = array(array(1,’amol’),array(2,’amit’),array(3,’sagar’)); $compiled = $q->prepare('INSERT INTO stud (rollno,sname) VALUES (?,?)'); foreach ($stud as $s) { $db->execute($compiled, $s); } 3.executeMultiple():This method is used to avoid the foreach loop in above eg $responses = $db->executeMultiple(compiled, values); $stud = array(array(1,’amol’),array(2,’amit’),array(3,’sagar’)); $compiled = $q->prepare('INSERT INTO stud (rollno,sname) VALUES (?,?)'); $db->executeMultiple(compiled, $stud);
  • 72. 72 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 3.Shortcuts PEAR DB provides a number of methods that perform a query and fetch the results in one step: getOne( ), getRow( ), getCol( ), getAssoc( ), and getAll(). All of these methods permit placeholders. 1.The getOne( ) method fetches the first column of the first row of data returned by an SQL query: $value = $db->getOne(SQL [, values ]) Eg $m = $db->getOne("SELECT count(*) FROM stud"); echo "$m"; 2. The getRow( ) method returns the first row of data returned by an SQL query: $row = $db->getRow(SQL [, values ]]); Eg $m = $db->getRow("SELECT * FROM stud"); echo "$m"; 3.The getCol( ) method returns a single column from the data returned by an SQL query: $col = $db->getCol(SQL [, column [, values ]]); The column parameter can be either a number (0, the default is the first column), or the column name. Eg $t = $db->getCol("SELECT sname from stud"); foreach ($t as $p) { echo "$p"; }
  • 73. 73 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 4.The getAll( ) method returns an array of all the rows returned by the query: $all = $db->getAll(SQL [, values]); $r = $db->getAll("SELECT rollno,sname from stud); foreach ($r as $r1) { echo "$r1[0].$r1[1]"; } Details About a Query Response Four PEAR DB methods provide you with information on a query result object: numRows( ), numCols( ), affectedRows( ), and tableInfo( ). The numRows( ) and numCols( ) methods tell you the number of rows and columns returned from a SELECT query: $howmany = $response->numRows( ); $howmany = $response->numCols( ); The affectedRows( ) method tells you the number of rows affected by an INSERT, DELETE, or UPDATE operation: $howmany = $response->affectedRows( ); The tableInfo( ) method returns detailed information on the type and flags of fields returned from a SELECT operation: $info = $response->tableInfo( ); Sequences • Sequence is a database object that generates numbers in sequential order. • Some of the RDBMS support to feature to assign unique row id.PEAR DB sequences are an alternate to database specific ID assignment • nextID() method returns the next ID for the given sequence
  • 74. 74 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP $id=$db->nextID(sequence) • It can explicitly create and destroy sequences with the createSequence( )and dropSequence( ) methods: $res = $db->createSequence(sequence); $res = $db->dropSequence(sequence); Metadata The getListOf( )method lets you query the database for information on available databases, users, views, and functions: $data = $db->getListOf(what); The what parameter is a string identifying the database feature to list. Most databases support "databases"; some support "users", "views", and "functions". For example, this stores a list of available databases in $dbs: $dbs = $db->getListOf("databases"); Transactions Some RDBMSs support transactions, in which a series of database changes can be committed (all applied at once) or rolled back (discarded, with the changes not applied to the database). PEAR DB offers the commit( ) and rollback( ) methods to help with transactions: $res = $db->commit( ); $res = $db->rollback( );
  • 75. 75 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP EMAIL HANDLING WITH PHP Email Server Working 1. The sender composes a message using the email client on their computer. 2. When the user sends the message, the email text and attachments are uploaded to the SMTP (Simple Mail Transfer Protocol) server as outgoing mail. 3. All outgoing messages wait in the outgoing mail queue while the SMTP server communicates with the DNS (Domain Name Server–like a phone book for domain names and server IP addresses) to find out where the recipient’s email server is located. If the SMTP server finds the recipient’s email server, it will transfer the message and attachments. If the recipient’s server can’t be found, the sender will get a “Mail Failure” notification in their inbox. 4. Recipient download new message to their email client & received their message
  • 76. 76 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Internet Mail orE-mail Protocols E-mail Protocols are set of rules that help the client to properly send the information to or received from the mail server. It consist of protocols such as SMTP(sending email), POP 3(receiving email) , and IMAP(receiving email).
  • 77. 77 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP POP3 1. The POP (Post Office Protocol 3) protocol provides a simple, standardized way for users to access mailboxes and download messages to their local computers. 2. Using the POP protocol all your eMail messages will be downloaded from the mail server to your local computer. 3. The advantage is that once your messages are downloaded, the internet connection is not required so that it reduces further communication costs.(Internet charges).But when downloading the message, a a lot of message (including spam or viruses)are copied to the local computer. 4. When the message is downloaded to the client machine, the copy from server gets deleted. This makes to access the email only from that local computer & not from any computer using internet(Mails once downloaded cannot be accessed from some other location) The following table describes some of the POP commands: S.N. Command Description 1 LOGIN This command opens the connection.
  • 78. 78 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 2 STAT It is used to display number of messages currently in the mailbox. 3 LIST It is used to get the summary of messages where each message summary is shown. 4 RETR This command helps to select a mailbox to access the messages. 5 DELE It is used to delete a message. 6 RSET It is used to reset the session to its initial state. 7 QUIT It is used to log off the session. IMAP 1. IMAP (Internet Message Access Protocol) is a standard protocol for accessing e-mail from your local server. 2. IMAP is a client/server protocol in which e-mail is received and held for you by your Internet server. 3. This work even over a slow connection such as a modem since required only small data transfer. 4. It can also create and manipulate folders or mailboxes on the server, delete messages etc. 5. IMAP support both online & offline modes of operation
  • 79. 79 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 6. It Allows mails to be accessed from multiple locations. SMTP SMTP stands for Simple Mail Transfer Protocol. It is a standard protocol used for sending e- mail efficiently and reliably over the internet. • SMTP is application level protocol. • SMTP is connection oriented protocol. • SMTP is text based protocol. • It handles exchange of messages between e-mail servers over TCP/IP network. • Apart from transferring e-mail, SMPT also provides notification regarding incoming mail. • When you send e-mail, your e-mail client sends it to your e-mail server which further contacts the recipient mail server using SMTP client. • These SMTP commands specify the sender’s and receiver’s e-mail address, along with the message to be send. • The exchange of commands between servers is carried out without intervention of any user. • In case, message cannot be delivered, an error report is sent to the sender which makes SMTP a reliable protocol. HTTP Protocol 1. HTTP is the protocol that web browsers and web servers use to communicate with each other over the Internet.
  • 80. 80 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP 2. It is an application level protocol . 3. It is stateless protocol because each command is executed independently 4. It is request & response fro client server Structure Of email It consist of 1.Message Header The message headers contain information concerning the sender and recipients. Headers contain the following information: • Subject:Subject is a description of the topic of the message • Sender (From):This is the sender's Internet email address. • Date and time received (On): The date and time the message was received. • Reply-to: This is the Internet email address that will become the recipient of your reply if you click the Reply button. • Recipient (To:) Recipient email address. • Cc: Address of the recipient, who will received copies. • Attachments. Files that are attached to the message. 2.Message Body The body of a message contains text that is the actual content Sending Email Using PHP Mail(): mail() function allows you to send emails directly from a script. Syntax mail(to,subject,message,headers,parameters);
  • 81. 81 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP To Required. Specifies the receiver / receivers of the email Subject Required. Specifies the subject of the email. Message Required. Defines the message to be sent. Each line should be separated with a LF (n). Lines should not exceed 70 characters. Headers Optional. Specifies additional headers, like From, Cc, and Bcc. . parameters Optional. Specifies an additional parameter to the sendmail program. <?php $to = "bcs@gmail.com"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: visionacademy@gmail.com" ; mail($to,$subject,$txt,$headers) or die(“failed email”); ?> Email Validation Email validation using 2 ways 1.Using filter_var function 2. Using ereg function 1.Using filter_var The FILTER_VALIDATE_EMAIL filter validates an e-mail address. Syntax filter_var(var, filtername, options)
  • 82. 82 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Parameter Description Var Required. The variable to filter filtername Optional. Specifies the ID or name of the filter to use. Default is FILTER_DEFAULT, which results in no filtering options Optional. Specifies one or more flags/options to use. <?php $email = "visionacademy@gmail.com"; if (filter_var($email, FILTER_VALIDATE_EMAIL)) echo("email is a valid"); else echo("email is not a valid"); ?> 2 Using ereg function <?php $email = "visionacademy@gmail.com"; if(!ereg("^[A-Za-z]+[0-9]*[.]{0,1}[A-Za-z0-9]*[@]{1}[A-Za-z0-9]*[.]{1,2}[A-Za- z]{2,5}$",$mail)) echo "wrong Input for E-Mail"; else echo "correct"; ?>
  • 83. 83 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP POST OFFICE PROTOCOL (POP3) INTERNET MESSAGE ACCESS PROTOCOL (IMAP) POP3 is short for Post Office Protocol. With POP3 mail, it will connect and attempt to keep the mail located on the local device (computer or mobile). IMAP is short for Internet Message Access Protocol. With IMAP, the message does not remain on the local device, such as a computer, it remains on the server. The POP server listens on port 110, and the POP with SSL secure(POP3DS) server listens on port 995 The IMAP server listens on port 143, and the IMAP with SSL secure(IMAPDS) server listens on port 993. In POP3 the mail can only be accessed from a single device at a time. Messages can be accessed across multiple devices The user can not organize mails in the mailbox of the mail server. The user can organize the emails directly on the mail server.
  • 84. 84 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP POST OFFICE PROTOCOL (POP3) INTERNET MESSAGE ACCESS PROTOCOL (IMAP) The user can not create, delete or rename email on the mail server. The user can create, delete or rename email on the mail server. A user can not search the content of mail before downloading to the local system. A user can search the content of mail for specific string before downloading. When the message is downloaded to the client machine, the copy from server gets deleted. Multiple redundant copies of the message are kept at the mail server, in case of loss of message of a local server, the mail can still be retrieved POP3 works better if you are only using one device, IMAP is better if you are going to be accessing your email from multiple devices, such as a work computer and a smart phone What is CC &BCC?
  • 85. 85 Vision Academy (9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) PHP Cc means carbon copy and Bcc means blind carbon copy. For emailing, you use Cc when you want to copy others publicly, and Bcc when you want to do it privately. Any recipients on the Bcc line of an email are not visible to others on the email Ahmed, Barry and Carol can all see that the email was sent to Ahmed, Barry and Carol for their attention and they can also see that a copy of the email was sent to Darren, Elaine and Fred. Darren, Elaine and Fred can all see that the email was sent to Ahmed, Barry and Carol for their attention and they can also see that a copy of the email was sent to Darren, Elaine and Fred Gunter, Harriet and Ian can all see that the email was sent to Ahmed, Barry and Carol for their attention and they can also see that a copy of the email was sent to Darren, Elaine and Fred Nobody can see that the email has been sent to Gunter, Harriet or Ian