AWP Module2 PHP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Module 2 [16MCA42] Advanced Web Programming

Module -2
Introduction to PHP and Building Web applications with PHP

• Origins and uses of PHP


• Overview of PHP
• General syntactic characteristics
• Primitives, operations and expressions
• Output, Control statements
• Arrays, Functions, Pattern matching
• Form handling, Files, Tracking users
• cookies, sessions, Using databases
• Handling XML.

Text book to be refered:


Robert .W. Sebesta : Programming the Worldwide Web, 4th Edn, Pearson, 2012

ROOPA.H.M, Dept of MCA, RNSIT Page 1


Module 2 [16MCA42] Advanced Web Programming

2.1 Origins and uses of PHP

• PHP was developed by Rasmus Lerdorf a member of the Apache Group.


• Initial purpose of PHP was to track visitors in his personal web site.
• In 1995 Lerdorf originally named it Personal Home Page (PHP) but currently is known as
Hypertext Preprocessor.
• PHP is a server-side, scripting language executed on the server.
• PHP is a widely-used, open source scripting language .

What Can PHP Do?

• PHP can generate dynamic page content


• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data

Why PHP?

• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side

2.2 Overview of PHP

• When the browser requests an XHTML document that includes PHP script, the Web server
determines that a document includes PHP script by the filename extensions such as .php,
.php3, or .phtml and calls the PHP processor.

• PHP processor takes PHP document file as input file and produces as XHTML document file.

PHP PHP XHTML


document processor document
file file

• PHP processor has two modes of operations:


 Copy Mode
 Interpret mode.

Copy mode :
On the server side when the PHP processor finds XHTML code (which may include client side
script) in the input file, it simply copies it to the output file.

Interpret mode :
On the server side when it encounters a PHP script in the input file, it interprets it and sends
any output of the script to the output file.
ROOPA.H.M, Dept of MCA, RNSIT Page 2
Module 2 [16MCA42] Advanced Web Programming

• The output from a PHP script must be XHTML or embedded client-side script.
• The output file is sent to the requesting browser. The client never sees the PHP script. If the
user clicks view source while browser is displaying the document, only the XHTML will be
shown.

2.3 General syntactic characteristics


• PHP scripts can be embedded within the XHTML document by enclosing it between the
<?php and ?> tags.
• PHP scripts can be in a separate file and referenced by an XHTML document with the
include construct, which takes the filename as its parameter.

Example: <?php include("table2.inc"); ?>

• This causes the contents of the file table2.inc to be copied into the document where the call
appears.
• The included file can contain XHTML markup or client-side scripts, as well as PHP code.
• Any PHP script it includes must be the content of a <?php tag, even if the include appears in
the content of a <?php tag.
• The PHP interpreter changes from interpret to copy mode when an include is encountered.

• Comments in PHP : PHP supports several ways of commenting:

<!DOCTYPE html>
<html>
<body>
<?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
*/
// you can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>

PHP's Reserved Words

ROOPA.H.M, Dept of MCA, RNSIT Page 3


Module 2 [16MCA42] Advanced Web Programming

2.4 Primitives, operations and expressions

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 ($age and $AGE are two different variables)
• Variables are not declared in PHP; they have a value and type of NULL until they are assigned
a value, in which case, they take the type of the value.
• When an unbounded variable (without an assigned value) is used, its value of NULL is coerced
to a 0 or an empty string, depending on its context.

Example : IsSet($myVariable);

can be used to see, if $myVariable is unbounded (false) or assigned a value (true)

PHP Data Types


• Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:

 PHP has four scalar data types: – Boolean, integer, double and string.
 PHP has two compound data types: – array and object.
 PHP has two special types: – resource and NULL.

Numeric Types (scalar type)

PHP has one integer type,


– Corresponds to C's long integer.
– It is usually 32 bits.

PHP's double type corresponds to C's double type.


– It can have a decimal point, exponent or both.
– These are valid doubles in PHP:

.345 345. 3.45E2 .34e-2

String type (scalar type)

• PHP characters are single bytes(UNICODE is not supported). A single character of string
length is 1.
• String literals are defined with either single (’) or double quotes (") delimiters.
• In single quoted string literals, escape characters such as \n, are not recognized as anything
special and the values of embedded variables are not substituted.
• To have variable values and escape sequences used in a string, enclose them in double
quotes.
• In double-quoted string literals, escape sequences are recognized and embedded variables are
replaced by their current values.

ROOPA.H.M, Dept of MCA, RNSIT Page 4


Module 2 [16MCA42] Advanced Web Programming

Example :
$sum=10; Output:
print ’the total \n is:$sum’; the total \n is :$sum
print "the total is:$sum"; the total is :10

Boolean Type (scalar type)

• Boolean values are either TRUE or FALSE, both of which are case insensitive.
• Other scalar types in boolean context:
• Integer values of 0 are interpreted as false; and others as true.
• Empty Strings or string "0" are interpreted false; and others are true.
• Doubles that are exactly 0.0 are false; others are true.

Arithmetic Operators and Expressions

• PHP uses the usual operators (+, -, *, /, %, ++, --)


• If both operands are integer,
• +, - and * will produce integer values.
• / will only produce an integer value if the quotient is integer; otherwise it is coerced to double.
• If either operand is double, the result is double.
• % expects integer operands and will coerce to integer if necessary.

Predefined Functions in PHP

ROOPA.H.M, Dept of MCA, RNSIT Page 5


Module 2 [16MCA42] Advanced Web Programming

Functions Examples Outputs


<!DOCTYPE html>
<html>
<body>
<?php
echo(floor(0.60). "<br>"); 0
echo(floor(0.40). "<br>"); 0
floor echo(floor(5). "<br>"); 5
echo(floor(5.1). "<br>"); 5
echo(floor(-5.1). "<br>"); -6
echo(floor(-5.9)); -6
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
1
echo(ceil(0.60). "<br>");
1
echo(ceil(0.40). "<br>");
5
ceil echo(ceil(5). "<br>");
6
echo(ceil(5.1). "<br>");
-5
echo(ceil(-5.1). "<br>");
-5
echo(ceil(-5.9));
?>
</body>
</html>
srand srand(mktime());
77
echo(rand());
echo(rand(). "<br>"); 31675
rand echo(rand(). "<br>"); 31110
echo(rand(10,100)); 63
echo(round(0.60). "<br>"); 1
echo(round(0.50). "<br>"); 1
echo(round(0.49). "<br>"); 0
round
echo(round(-4.40). "<br>"); -4
echo(round(-4.60)); -5

echo(abs(6.7). "<br>"); 6.7


echo(abs(-6.7). "<br>"); 6.7
abs
echo(abs(-3). "<br>"); 3
echo(abs(3)); 3
echo(min(2,-4,6,-8,10). "<br>"); -8
min
echo(min(22,14,68,18,15). "<br>"); 14
echo(max(-2,-4,-6,-8,-10). "<br>"); -2
max
echo(max(22,14,68,18,15). "<br>"); 68

ROOPA.H.M, Dept of MCA, RNSIT Page 6


Module 2 [16MCA42] Advanced Web Programming

String Operations:
Strings can be treated like arrays to access individual characters by specifying its position in
braces.
String operators are shown below:

Examples :

Commonly Used PHP String Functions

Examples outputs

echo strlen("Hello 11
world");
echo strpos("Hello 8
world!", "r");
$string="Bangalore"; galo
echo substr($string,3,4);

$string="bangalore"; BANGALORE
echo
strtoupper($string);

ROOPA.H.M, Dept of MCA, RNSIT Page 7


Module 2 [16MCA42] Advanced Web Programming

echo 0
strcmp("rnsit","rnsit");
$str = "mca,rnsit,mca"; ,rnsit,
echo trim($str,"mca");

$str = "mca,rnsit,mca"; ,rnsit,mca


echo ltrim($str,"mca");

$str = "mca,rnsit,mca"; mca,rnsit,


echo chop($str,"mca");

Scalar Type Conversion:


There are two types, those are,
1) Implicit Scalar Type Conversions
2) Explicit Scalar Type Conversions

1) Implicit Scalar Type Conversions


• In implicit (coercions) conversion, the context of the expressions determines what data type is
expected or required.
• There are also numeric-string conversions, where a string with e or a period is converted to
double and those without it are converted to integer. If no sign or digit, it fails and uses 0.
• Converting double to integer results in truncation.

2) Explicit Scalar Type Conversions


Explicit type conversion can be done in 3 ways:
1. Casting involves putting the type name in parentheses:
Ex:$sum = 4.777;
(int) $sum ; // produces 4

2. An explicit conversion can be done using the functions intval, doubleval or strval
Ex: intval($sum); //produces 4 .

3. The settype function can convert the first parameter to the type indicated by the second
parameter
Ex: settype($sum, "integer"); //produces 4

gettype:
• A program can determine the type of a variable in two ways:
• using the gettype function which returns the type as a string (which can also be "unknown")
• using one of the functions :
• is_int, is_integer, is_long ( which test for integers)
• is_double, is_real and is_float (which test for doubles)
• is_bool and is_string .

ROOPA.H.M, Dept of MCA, RNSIT Page 8


Module 2 [16MCA42] Advanced Web Programming

2.5 Output
• Any output from a PHP script becomes part of the document that the PHP processor is
building. Output must be in the form of an XHTML document.

1. The print function is easiest way to produce unformatted output:


print "Apples are red <br />";
The print function expects string but it will take other parameters:
print(47);
Double-quoted strings have their variable names replaced by their values:
print "The result is $result <br />";

2. PHP borrows the printf function from C, whose form is


printf( controlString, param1, param2, …);

The control string is a template that includes specifiers as to how the other parameters will be
printed:
%10s a character field of 10 characters
%6d an integer field of 6 character
%5.2f a float or double field of 5 characters and 2 decimal place
Example:
$day = "Tuesday";
$high = 79;
printf("The high on %7s was %3d", $day, $high);

2.6 Control statements


Relational Operators
PHP has 8 relational operators:
• The usual 6 (==, !=, >, >=, <, <=)
• === (which is true if both operands have the same value and type)
• !== (which is the opposite of ===)

Comparisons and Types


• If the operands do not have the same type, one is coerced into the type of the other.
• If one operand is a number and the other a string, the string is coerced and then compared
to the other.
• If the string cannot be coerced, the number is coerced and then the comparison is done.
• If both operands are strings and can be converted to numbers, they are converted and then
compared. This can be avoided by using strcmp.

Boolean Operators
• There are 6 Boolean operators (in order of precedence) : !, &&, ||, and, or, xor

Selection Statements
• The control structures in PHP are very similar to C/C++/Java.
• The control expression (or condition) can be any type and is coerced to Boolean.
• The control statements include:
 if and if-else
 while and do..while
 for and foreach

ROOPA.H.M, Dept of MCA, RNSIT Page 9


Module 2 [16MCA42] Advanced Web Programming

if Statements :
The if statement in PHP is like that of C, although there is also an elseif. An if statement can
include any number of elseif clauses. The condition can be of any type but it is coerced to
Boolean.
Example:

if ($day == "Saturday" || $day == "Sunday")


$today = "weekend";
else {
$today = "weekday";
$work = true;
}

Loop Statements

PHP has while, for and do-while loops that works exactly like those in JavaScript, as well as a
foreach statement.
Example :

Switch Statements

• PHP’s switch statement is the same as in JavaScript.


• The control expression and case expressions can be integer, double or string, with the case
expressions coerced into the type of the control expression.
• Break is necessary to avoid falling through to the next case.

Example:
switch ( $bordersize )
{
case "0": print "<table>"; break;
case "1": print "<table border = "1">"; break;
case "4": print "<table border = "4">"; break;
case "8": print "<table border = "8">"; break;
default: print "Error – invalid value:", " $bordersize <br />";
}

ROOPA.H.M, Dept of MCA, RNSIT Page 10


Module 2 [16MCA42] Advanced Web Programming

<!-- powers.php An example to illustrate loops Output:


and arithmetic operations -->
<html xmlns=
http://www.w3.org/1999/xhtml">
<head> <title> powers.php </title> </head>
<body>
<table border = "border">
<caption> Powers table </caption>
<tr>
<th> Number </th>
<th> Square Root </th>
<th> Square </th>
<th> Cube </th>
</tr>

<?php
for($number=1; $number<=10;
$number++)
{
$root = sqrt($number);
$square = pow($number, 2);
$cube = pow($number, 3);
print ("<tr align = 'center'>
<td> $number </td>");
print ("<td> $root </td> <td>
$square </td>");
print ("<td> $cube </td>");
}
?>
</table>
</body>
</html>

2.7 Arrays
• In PHP, there are two types of arrays:
 Indexed arrays
 Associative arrays or Hashes

• Each element in the array consists of a key and value.


• If the array's logical structure is like indexed arrays, the keys can happen to be simply non-
negative integers in ascending order.
• If the array's logical structure is like hashes, the keys are string and their order is based on a
system-designed hashing function.

Array Creation:
There are two ways:
1. By Assignment
2. By array() Construct

ROOPA.H.M, Dept of MCA, RNSIT Page 11


Module 2 [16MCA42] Advanced Web Programming

1. By Assignment:

Arrays in PHP can be created by simply assigning a value to its element .


Examples:

$list1[0] = 17; # if $list1 does not exist, it creates and initializes the array
$list2[] = 5; # if Not previously defined this is the 0th element
$list2 [1] = "Today is my birthday!";
$list2 [] = 42 # stored in $list[2];

2. By array() Construct :
Arrays in PHP can be created by using the array() construct
Examples:

$list = array(17, 24, 45, 91); #list begins at index 0


$list = array( 1 =>17, 2 => 24, 3 => 45, 4 =>91 ); #list begins at index 1
$list = array( ); # empty array
$list = array("Joe" => 42, "Mary" => 42, "Bif" => 17); # hashed array
$list =array("make"=>"Cessna", "model"=>C210,"year"=>1960,3=>"sold"); #mixed array

Accessing Array Elements


• Individual array elements can be accessed by subscripting the key.
– Brackets are used for both a numeric and a string key.
– $ages['Mary'] = 29;
• Multiple elements of an array can be assigned to different variables using the list construct:
$trees = array("oak", "pine", "binary");
list( $hardwood, $softwood, $data_structure )= $trees;

Functions for Dealing with Arrays


There are many functions to deal with an array, some of the functions listed below
• count( )
• unset( )
• array_keys( )
• array_values( )
• array_key_exists( )
• is_array( )
• in_array( )
• sizeof( )
• implode( ) and explode( )

 count( ) function: is used to return the length (the number of elements) of an array.
 sizeof( ) function: returns the number of elements in an array.
 unset( ) function: is used to delete entire array or a single element in the array.
 array_keys ( ) and array_values( ) function: is used for the keys and the values can be
separately extracted from the array.
 array_key_exists( ) function: The existence of an element in an array with a specific key can
be determined using array_key_exists, which returns a Boolean.

ROOPA.H.M, Dept of MCA, RNSIT Page 12


Module 2 [16MCA42] Advanced Web Programming

 is_array( ) function: returns true if its parameter is an array.


 in_array( ) function: takes 2 parameters:
o an expression and an array.
o If the expression is a value in the array, it returns true.

 implode( ) and explode( ) function: Strings can be converted to arrays and vice versa using
explode and implode.
– explode : allows a string to be separated into different array elements
– implode : allows the elements of an array to be joined into a string

Examples Outputs
<?php
$cars = array("Volvo", "BMW", "Toyota");
3
echo count($cars);
?>
<?php
$list = array("Bob", "Fred", "Alan", "Bozo");
$len = sizeof($list); length = 4
Print "length = $len";
?>
<?php
$list = array(2, 4, 6, 8);
unset ($list[2]); 2,4,8
print_r( $list);
?>
<?php

$highs=array("Mon"=>74,"Tue"=>70,"Wed"=>67);
keys: Array ( [0] => Mon [1] => Tue
$days=array_keys($highs);
[2] => Wed )
$temps = array_values($highs);
print " keys: ";
Values : Array ( [0] => 74 [1] => 70
print_r($days);
[2] => 67 )
print "Values : ";
print_r($temps)
?>
<?php
$highs =
array("Mon"=>74,"Tue"=>70,"Wed"=>67);
The key exist
if (array_key_exists("Tue", $highs) )
{ print "The key exist"; }
?>
<?php
$rnsit=array(45,78,12,34);
$bms=25;
if(is_array($bms) )
false
{ print "true"; }
else
{ print "false"; }
?>

ROOPA.H.M, Dept of MCA, RNSIT Page 13


Module 2 [16MCA42] Advanced Web Programming

<?php
$people = array("vijay", "rakesh", "venu",
"pratheek");
if (in_array("venu", $people) )
Match found
{ echo "Match found"; }
else
{ echo "Match not found"; }
?>
<?php
$str = "rnsit mca dept";
$words = explode(" ", $str);
Array ( [0] => rnsit [1] => mca
Print_r( $words);
[2] => dept )
$str = implode(" ", $words);
rnsit mca dept
Print_r($str);
?>

Logical Internal Structure of Arrays

 Internally, the elements of an array are stored in a linked list of cells, Where each cell
includes both key and the value of the element.
 The cell themselves are stored in memory through a key hashing function.So that they are
randomly distributed in a reserved block of storage.
 Accesses to elements through string keys are implemented through the hashing function.
 However, the elements all have links that connect them in the order in which they were
created.
 The following figure shows the internal logical structure of an array. It shows how the two
different access methods could be supported.

Sequential Access to Array Elements


• current( )
• next( )
• each( )
• prev( )
• key( )
• array_push( ) and array_pop( )
• foreach( )

ROOPA.H.M, Dept of MCA, RNSIT Page 14


Module 2 [16MCA42] Advanced Web Programming

 current( ) : Every array has an internal pointer that references one element of the array,
which is initially pointing to the first element. It can accessed using the current function.

 next( ):next function moves the next pointer to the next element in the array, if it is already
pointing to the last element, it returns false.

 each( ) :it returns 2-element array, consisting of the key and "current" element's value.
o It only returns false if the current pointer has gone beyond the end of the array.
o The keys of these values are "key" and "value"
 prev( ): the function prev returns the value of the previous element in the array.
 key( ): the function key returns the key of the current element.
 array_push( ) and array_pop( ) :allow the programmer to implement a stack.
 foreach( ): allows each element in the array to be processed.
There are two forms:
o foreach (array as scalar_var) loop body
o foreach (array as key => value) loop body

Examples Outputs
<?php
$cities = array ("Bangalore", "Chennai");
$city = current ($cities); The first city is Bangalore
print "The first city is $city <br />";
?>
<?php
$city = current ($cities);
print "$city <br />"; Bangalore
while ($city = next ($cities)) Chennai
print "$city <br />";
?>
<?php
$salaries=array("a"=>4250,"b"=>5120,
"c"=>3790);
while ($employee = each ($salaries)) a salary is 4250
{ $name = $employee ["key"]; b salary is 5120
$sal = $employee ["value"]; c salary is 3790
print ("$name salary is $sal: <br/>");
}
?>
<?php
$cities = array_push ($cities,"Andhra");
Bangalore Chennai Andhra
print_r($cities);
?>
<?php
foreach ($cities as $temp)
Bangalore Chennai Andhra
print "$temp";
?>
<?php
$lows = array("Mon" =>32,"Tue"=>36); Temperature on Mon was 32
foreach ($lows as $day => $temp)
print "Temperature on $day was $temp"; Temperature on Tue was 36
?>

ROOPA.H.M, Dept of MCA, RNSIT Page 15


Module 2 [16MCA42] Advanced Web Programming

2.8 Functions
The general form of a function is:

function name ( [ parameters ] )


{ …… }

• The parameters are optional.


• A function can be placed anywhere in the document.
• Function overloading is not allowed.
• Functions can be nested but it is not a good idea.
• A return statement is only necessary when the function is returning a value.

General Characteristics of a Function

• The main program passes actual parameters; the function receives formal parameters.
• The number of actual and formal parameters do not have to match.
– Excess formal parameters are unbounded.
– Excess actual parameters are ignored.
• Parameters are passed by value. If the function needs to return more than one variable, a
reference to the variable can be passed.

Pass by value Pass by reference


<?php <?php
$x=10; $x=10;
$y=20; $y=20;
print "before swap x=". $x ."y=" .$y; print "before swap x=". $x ."y=" .$y;
swap($x,$y); swap($x,$y);
print "after swap x=". $x ."y=" .$y;
Function swap($x,$y)
{ Function swap(&$x , &$y)
$temp=$x ; {
$x=$y ; $temp=$x ;
$y=$temp; $x=$y ;
print "after swap x=". $x ."y=" $y=$temp;
.$y; }
} ?>
?>

Scope of Variables

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of
the script where the variable can be referenced/used.

PHP has three different variable scopes:


• local
• global
• static

ROOPA.H.M, Dept of MCA, RNSIT Page 16


Module 2 [16MCA42] Advanced Web Programming

Global and Local Scope


• A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function
• A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:

Global scope Local scope


<?php <?php
$x = 5; // global scope
function myTest( )
function myTest( ) { $x = 5; // local scope
{ /* using x inside this function will echo "Variable x inside function is:
generate an error */ $x";
}
echo "Variable x inside function is: myTest();
$x ";
} /* using x outside the function will
myTest( ); generate an error */

echo "Variable x outside function is: echo "Variable x outside function is:
$x"; $x";
?> ?>

Output: Output:
Variable x inside function is: Variable x inside function is: 5
Variable x outside function is: 5 Variable x outside function is:

The global Keyword


The global keyword is used to access a global variable within a function. To do this, use the
global keyword before the variables (inside the function)

The static Keyword


Normally, when a function has completed its execution, all of its local variables are deleted.
However, sometimes we may need those local variables for further use. So the variables can
remain alive even after function execution by using the static keyword when you first declare
the variable.
global Keyword static Keyword
<?php <?php
$x = 5; $y = 10; function myTest( )
{
function myTest( ) static $x = 0;
{ echo $x;
global $x, $y; $x++;
$y = $x + $y; }
} myTest( );
myTest( ); myTest( );
echo $y; myTest( );
?> ?>

Output: 15 Output: 0 1 2

ROOPA.H.M, Dept of MCA, RNSIT Page 17


Module 2 [16MCA42] Advanced Web Programming

Default Argument Value

The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:

Ex:
<?php
function setHeight($minheight = 50)
{
echo "The height is : $minheight <br> ";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>

2.9 Pattern matching.


• PHP includes two different kinds of string pattern matching using regular expressions.
• They are:
 preg_match function
 preg_split function
• The preg_match function takes two parameters.
• The first of which is the Perl-style regular expression as a string.
• The second parameter is the string to be search.
• The preg_match( ) function searches string for pattern, returning true if pattern exists, and
false otherwise.

Example:
<?php Output:
$college="Master of computer applications“;
if(preg_match("/of/", $college)) true
{ print "true"; }
else
{ print "false"; }
?>

• The preg_split function takes two parameters.


• The first of which is a Perl-style pattern as a string.
• The second parameter is the string to be split.
Ex:
<?php OUTPUT
$course=“master%of%computer applications”; Array ( [0] => master [1] => of
$rns=preg_split(“/%/”, $course); [2] => computer applications )
print_r($rns);
?>

ROOPA.H.M, Dept of MCA, RNSIT Page 18


Module 2 [16MCA42] Advanced Web Programming

2.10 Form handling

• When PHP is used for form handling, the PHP scripts is embedded in an XHTML document.
• Based on the request method, we have to use implicit arrays for form values, $_POST and
$_GET.
• Both GET and POST create an array
(e.g. array( key => value, key2 => value2, key3 => value3, ...)).
• This array holds key/value pairs, where keys are the names of the form elements and values
are the input data from the user.
• These($_GET and $_POST) are superglobals, which means that they are always accessible,
regardless of scope - and you can access them from any function, class or file without having
to do anything special.
• $_GET is an array of variables passed to the current script via the URL parameters.
• $_POST is an array of variables passed to the current script via the HTTP POST method.

Form.html Form.php
<html> <html>
<body> <body>
<form action="form.php" method="post"> Welcome
Name:<input type="text" name="name"><br> <?php echo $_POST["name"]; ?><br>
E-mail:<input type="text" name="email"><br>
<input type="submit" value="submit"> Your email address is:
</form> <?php echo $_POST["email"]; ?>
</body> </body>
</html> </html>

• When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named “form.php". The form data is sent with the HTTP POST
method.

2.11 Files
• PHP is a server-side technology, it is able to create, read and write files on the server system.
• PHP can deal with files residing on any server system on the internet, using HTTP and FTP
protocols.
All file operation in PHP is implemented as functions:
1. Opening and closing files
2. Reading from a file
3. Writing from a file
4. Locking files

1. Opening and closing files


 fopen
 file_exists
 fclose

ROOPA.H.M, Dept of MCA, RNSIT Page 19


Module 2 [16MCA42] Advanced Web Programming

fopen :
• The fopen function is used for to open a file, it takes two parameters, the filename, including
the path to it and a use indicator, which specifies the operation or operations that must be
performed on the file. Both parameters are given as string.
• Every open file has an internal pointer that is used to indicate where the next file operation
should take place within the file, we call this pointer the file pointer.
• The fopen function returns the reference to the file for the file variable.

Example: $file_var= fopen("count.dat","r") or die("Error – count.dat cannot be opened");

File use indicator


Use Description
indicator

r Open a file for read only. File pointer starts at the beginning of the file

r+ Open a file for read/write. File pointer starts at the beginning of the file

Open a file for write only. Erases the contents of the file or creates a new file if it
w
doesn't exist. File pointer starts at the beginning of the file

Open a file for read/write. Initializes the file pointer to the beginning of the file;
w+ creates the file if it does not exist. Always initializes the file pointer to the
beginning of the file before the first write, destroying any existing data.

Open a file for write only. The existing data in file is preserved. File pointer starts at
a
the end of the file. Creates a new file if the file doesn't exist

Open a file for read/write. Creating the file if necessary; new data is written to the
a+
end of the existing data.

file_exists:
The file_exists function takes a single parameter, the file’s name. It returns TRUE if the file
exists, FALSE otherwise.
Example: if( file_exists("count.dat") )

fclose :
A file is closed with the fclose function, which takes a file variable as its only parameter.
Example: fclose($file_var);

2. Reading from a file


• fread
• file
• file_get_contents
• fgets

fread:
 The fread function reads part or all of a file and returns a string of what was read.
 This function takes two parameters, a file variable and the number of bytes to be read.

ROOPA.H.M, Dept of MCA, RNSIT Page 20


Module 2 [16MCA42] Advanced Web Programming

 The reading operation stops when the specified number of bytes has been read or when
it reaches end-of-file.
 If the whole file is to be read at once. the file's length is given as the second parameter to
fread.
 The filesize function takes a single parameter, the name of the file(not the file variable).
Example: $file_string = fread ($file_var, filesize("count.dat"));

file:
 One alternative to fread is file, which takes a filename as its parameter and returns an
array of all lines of the file.
 Advantage of file is that the file open and close operations are not necessary.
Example: $file_lines = file("count.dat");

file_get_contents :
 This function reads the entire contents of the file, which takes the file's name its
parameter.
 It does not require to call fopen function.
Example: $file_string1 = file_get_contents ( "count.dat" );

fgets
 A single line of a file can be read with fgets, which takes two parameters, the file
variable and a limit on the length of the line to be read.
Example: $line = fgets($file_var, 100);
 The above statement reads characters from count.dat until it finds a newline character,
encounters the end-offile marker, or has read 99 characters.

3. Writing from a file

fwrite:
 The fwrite function takes two parameters, a file variable and the string to be written to
the file.
 The fwrite function returns the number of bytes written.
Example: $bytes_written = fwrite ($file_var, $new_file);
 The above statements writes the string value in $new_file to the file referenced with
$file_var and places the number of bytes written in $bytes_written.

4. Locking files flock:


• The flock is used for to lock and unlock the file for security purpose.
• Scripts that use lock before accessing the file and unlock them when the access is
completed.
• The locking is done in PHP with the flock function, which is familiar to UNIX
programmers.
• The flock function takes two parameters, the file variable of the file and an integer that
specifies the particular operation.
• A value of 1 specifies that the file can be read by others while the lock is set,
• A value of 2 allows no other access, and
• A value of 3 unlocks the file.
Example: $file_lock = flock ( $file_var, 3);

ROOPA.H.M, Dept of MCA, RNSIT Page 21


Module 2 [16MCA42] Advanced Web Programming

2.12 Tracking users


Tracking Users Tracking users can be done in two ways:
1. Cookies and
2. Sessions

2.13 Cookies

• A cookie is used to identify a user or tracking users.

• A cookie is a small text file that the server embeds on the user’s computer.

• Each time the same computer requests a page with a browser, it will send the cookie too.

• A cookie is set in PHP with the setcookie function.

• This function takes one or more parameters.

• The first parameter, which is mandatory, is the cookie’s name given as a string. All other
parameters are optional.

• The second, if present, is the new value for the cookie, also a string.

• The third parameter, when present, is the expiration time in seconds for the cookie, given
as an integer.

• The default value for the expiration time is zero, which specifies that the cookie is destroyed
at the end of the current session.

• The time function returns the current time in seconds.

• So, the cookie expiration time is given as the value returned from time plus some number.

• Cookies variables are set with the PHP global variable: $_COOKIE.

Create Cookies with PHP

Example-1
<?php
setcookie("rnsit","webclass" , time()+3600*24); //3600 = 1hour
?>

Here, this call creates a cookie named rnsit whose value is webclass and lifetime is one day.

Create/Retrieve a Cookie
• The following example creates a cookie named "rnsit" with the value "webclass ". The cookie
will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire
website (otherwise, select the directory you prefer).
• We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set

ROOPA.H.M, Dept of MCA, RNSIT Page 22


Module 2 [16MCA42] Advanced Web Programming

Example :

<?php

Note: The setcookie() function must appear BEFORE the <html> tag.

Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:

Example :

2.14 Sessions
• A session is a way to store information (in variable) to be used across multiple pages.
• Unlike a cookie, the information is not stored on the user’s computer.
• A session arrays often store a unique session ID for a session.
• Session files are usually stored in /tmp/ on the server, and named sess_{session_id}.
• A session is started with the session_start( ) function.
• Session variables are set with the PHP global variable: $_SESSION.
• To remove all session variables use session_unset( ).
• To destroy the session use session_destroy( ).

ROOPA.H.M, Dept of MCA, RNSIT Page 23


Module 2 [16MCA42] Advanced Web Programming

Favourites.html Output:
<?php
session_start( ); Session variables are set.
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "dog";
echo "Session variables are set.";
?>
</body>
</html>

Get PHP Session Variable Values

• Session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start( )).

• Also notice that all session variable values are stored in the global $_SESSION variable:

ROOPA.H.M, Dept of MCA, RNSIT Page 24


Module 2 [16MCA42] Advanced Web Programming

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous example Favourites.html

echo "Favorite color is " . $_SESSION["favcolor"] . ":<br>";


echo "Favorite animal is " . $_SESSION["favanimal"] . ":"; ?>

</body>
</html>
Output: Favorite color is : green
Favorite animal is : dog

• Another way to show all the session variable values for a user session is to run the
following code

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Output: Array ( [favcolor] => green [favanimal] => dog )

• Destroy a PHP Session : To remove all global session variables and destroy the session,
use session_unset( ) and session_destroy( ).
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php session_unset(); // remove all session variables
session_destroy(); // destroy the session
echo "All session variables are now removed, and the session is destroyed."
?>
</body>
</html>
Output: All session variables are now removed, and the session is destroyed.

ROOPA.H.M, Dept of MCA, RNSIT Page 25


Module 2 [16MCA42] Advanced Web Programming

Difference between cookies and sessions

Cookies Sessions

Cookies are client-side files that contain user Sessions are server-side files that contain
information user information

We have to set cookie max life time manually Session Max life time is 1440 Seconds(24
with php code with setcookie Minutes) as defined in php.ini file

In php $_COOKIE super global variable is In php $_SESSION super global variable is
used to manage cookie. used to manage session.

You don't need to start Cookie as It is stored Before using $_SESSION, you have to write
in your local machine. session_start();

Official MAX Cookie size is 4KB You can store as much data as you like
within in sessions.The only limits you can
reach is the maximum memory a script can
consume at one time, which by default is
128MB.

There is no function named unsetcookie( ) session_unset( ); is used to remove all session


variables.

2.15 Using databases

2.16 Handling XML.

ROOPA.H.M, Dept of MCA, RNSIT Page 26

You might also like