0% found this document useful (0 votes)
61 views

PHP

Uploaded by

Farzan Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

PHP

Uploaded by

Farzan Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

PHP

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


Module IV PHP
• Origin and Use of PHP
• Overview of PHP
• General Syntactic Characteristics
• Operations and Expressions
• Control Statements
• Arrays- Functions
• Pattern Matching
• Form Handling
• Files
• Cookies
• Session Tracking
• Simple programs in PHP.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-2


PHP Introduction

•PHP code is executed on the server, generating


HTML which is then sent to the client.
•The client would receive the results of running
that script, but would not know what the
underlying code was.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-3


PHP Introduction

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-4


PHP Getting Started

•On windows, you can download and install WAMP. With one
installation and you get an Apache webserver, database server
and php.
•http://www.wampserver.com

•On mac, you can download and install MAMP.


•http://www.mamp.info/en/index.html

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-5


1 &2 Origin and Use of PHP,Overview
• PHP: “Personal Home Page Hypertext Preprocessor”
• Originally, PHP was an acronym for Personal Home Page
• open source general-purpose scripting language
• web development tool and can be embedded into HTML
• File ends in .php--this is set by the web server configuration
• Separated in files with the <?php ?> tag
• php commands can make up an entire file, or can be contained
in html.
• Program lines end in ";" or you get an error
• PHP scripts are executed on the server
• PHP supports many databases (MySQL, Informix, Oracle,
Sybase, Solid, PostgreSQL, Generic ODBC, etc.)

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-6


3. General Syntactic Characteristics
•>All variable names in PHP begin with dollar signs ($).
•> PHP runs on different platforms (Windows, Linux, Unix, etc.)
•> PHP is compatible with almost all servers used today (Apache,
IIS, etc.)
•> PHP is FREE to download from : www.php.net
•> PHP is easy to learn and runs efficiently on the server side
--------------------------------------------------
<P>
<?php $myvar = "Hello World!";
echo $myvar;
?>
</P>
---------------------------------------------------
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-7
Variables
• All variable names in PHP begin with dollar signs ($).
• The part of the name after the dollar sign is like the names of
variables in many common programming languages: a letter or
an underscore followed by any number (including zero) of
letters, digits, or underscores.
• PHP variable names are case sensitive.
• Assigned by value
– $foo = "Bob"; $bar = $foo;
• Assigned by reference, this links vars
– $bar = &$foo;
• Some are preassigned, server and env vars
– For example, there are PHP vars, eg. PHP_SELF, HTTP_GET_VARS

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-8


Table The reserved words of PHP

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-9


4.Operations and Expressions
• PHP has four scalar types: Boolean, integer, double, and string;
two compound types, array and object; and
two special types, resource and NULL
4.1 Integer Type
• PHP has a single integer type, named integer. (corresponds to
the long type of C)
• In most cases, this is 32 bits, or a bit less (not fewer) than ten
decimal digits.
4.2 Double Type
• PHP's double type corresponds to the double type of C and its
successors.
• Double literals can include a decimal point, an exponent, or
both. The exponent has an E or an e

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-10


4.4 String Type
• Characters in PHP are single bytes. no character type.
• A single character data value is represented as a string of
length 1.
• String literals with either single (') or double quotes (")
• In single-quoted string literals, escape sequences, such as \n,
are not recognized and the values of embedded variables are
not substituted. This substitution is called interpolation.
‘The sum is :$sum’ exactly as it is typed.
• In double-quoted string literals, escape sequences are
recognized, and embedded variables are replaced by their
current values.
$sum=10;
Print “The sum : $sum”;
o/p :The sum : 10

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-11


4.5Boolean Type
• The only two possible values for the Boolean type are TRUE
and FALSE, both of which are case insensitive.
• If an integer expression is used in Boolean context, it evaluates
to FALSE if it is zero; otherwise, it is TRUE.
• If a string expression is used in Boolean context, it evaluates to
FALSE if it is either the empty string or the string "0";
otherwise, it is TRUE.
4.6Arithmetic Operators and Expressions
• PHP has the usual (for C-based programming languages)
collection of arithmetic operators (+, -, *, /, %, ++, and --)
• If either operand is a double, the operation is double and a
double result is produced

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-12


PHP Operators

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-13


PHP Operators

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-14


PHP Operators

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-15


PHP Operators

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-16


Table Some useful predefined functions

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-17


4.7String Operations
•> The only string operator is the concatenation operator (.) ,used
to put two string values together.
•> To concatenate two string variables together, use the
concatenation operator:

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-18


Some commonly used string functions

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-19


4.8Scalar Type Conversions
• PHP includes both implicit and explicit type conversions.
• Implicit type conversions are called coercions
• The context can cause a coercion of the type of the value of the
expression.
• Whenever a numeric value appears in string context, the
numeric value is coerced to a string.
• whenever a string value appears in numeric context, the string
value is coerced to a numeric value.
• If the string contains a period, an e, or an E, it is converted to
double; otherwise, it is converted to an integer.
• When a double is converted to an integer, the fractional part is
dropped; rounding is not done

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-20


• Explicit type conversions can be specified in three ways.
• Using the syntax of C, an expression can be cast to a different
type. The cast is a type name in parentheses preceding the
expression. For example, if the value of $sum is 4 . 777, the
following produces 4: (int)$sum
• Another way to specify explicit type conversion is to use one of
the functions intval, doubleval, or strval. For example, if $sum
is still 4.77 7, the following call returns 4:
intval($sum)
• The third way to specify an explicit type conversion is the
settype function, which takes two parameters: a variable and a
string that specifies a type name. For example, if $sum is still 4
. 777, the following statement converts the value of $sum to 4
and its type to integer:
settype($sum, "integer");

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-21


5 Output
• The print function is used to create simple unformatted output.
• It can be called with or without parentheses around its
parameter
• Legal statements example
print "Apples are red <br /> Kumquats aren't <br />";
print( 47 ); produce 47
print "The result is: $result <br />";
• The general form of a call to printf is as follows:
printf (literal_string, param l, param 2, ...)
• The literal string can include labeling information about the
parameters whose values are to be displayed.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-22


contd
• It also contains format codes for those values.
• The form of the format codes is a percent sign (%) followed by a
field width and a type specifier.
• The most common type specifiers are s for strings, d for
integers, and f for floats and doubles
• Consider the following examples:
% 10 s—a character string field of 10 characters
%6d—an integer field of 6 digits
%5. 2f—a float or double field of 8 spaces, with two digits to the
right of the decimal point, the decimal point, and 5 digits to the
left

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-23


Display of the output of today.php
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1 //EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"> <head>
<title> today.php </title> </head>
<body>
<p>
<?php
print "<b>Welcome to my home page <br /> <br />";

print "Today is:</b>date("Y/m/d"); print "<br />";


?>
</p>
</body>
</html>

o/p

Welcome to my Home Page


Today is 2014/09/24

NB Try date(l,F,jS)=>Saturday June 1st


Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-24
6.Control Statements
• Relational Operators
• PHP uses the eight relational operators of JavaScript. The
usual six (>, <, >=, <=, ! =, and ==) have the usual meanings. It
also has ===, which produces TRUE only if both operands are
the same type and have the same value, and ! ==, the opposite
of ===.
• Boolean Operators
• There are six Boolean operators: and, or, xor, !, &&, and | |.
The and and && operators perform the same operation, as do
or and | |.
example of an if construct:
if ($day == "Saturday" || $day == "Sunday")
{$today = "weekend”;}
else
{$today = "weekday";}
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-25
Switch
• 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;
}
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-26
Loop Statements
• The while, for, and do-while statements of PHP are exactly like
those of Java. PHP also has a foreach statement
Example

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-27


Example
computes the sum of the positive integers up to 100using do while
$count = 1;
$sum = 0;
do
{
$sum += $count;
$count++;
} while ($count <= 100);

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-28


For ,Break ,continue

The break statement can be used to terminate the execution of a


for, foreach, while, or do-while construct. The continue statement
is used in loop constructs to skip the remainder of the current
iteration but continue execution at the beginning of the next.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-29


Example For

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-30


Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-31
Figure The output of powers.php

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-32


For each For every loop iteration, the
value of the current array
element is assigned to $value
(and the array pointer is moved
by one) - so on the next loop
iteration, you'll be looking at
the next array value

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-33


7 PHP Arrays
• In PHP, there are three kind of arrays:
• > Numeric array - An array with a numeric index
• > Associative array - An array where each ID key is
associated with a value
• > Multidimensional array - An array containing one or
more arrays
7.1 Array creation
7.2 Accessing Array elements
7.3 Functions dealing with Arrays
7.4 Sequential Access to Array
7.5 Sorting Arrays

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-34


7.1 Numeric Arrays creation
•> A numeric array stores each array element with a numeric
index.
•> There are two methods to create a numeric array.
•The assignment operation creates scalar variables. The same
operation works for arrays—assigning a value to an element
of an array that does not yet exist creates the array.
• For example, assuming no array named $list currently
exists, the following statement creates one:$list[0] = 17;
• If the script has a scalar variable named $list prior to this
assignment, $ list is now an array
• If the array currently has no elements with numeric keys,
the value 0 is used. For example, in the following code, the
second element's subscript will be 2:
• $list[l] = "Today is my birthday!"; $list[] = 42;
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-35
•The second way to create an array is with the array construct.
•In the following example the index is automatically assigned (the
index starts at 0):

•In the following example we assign the index manually:

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-36


7.2 Accessing Array Elements

•In the following example you access the variable values by


referring to the array name and index:

•The code above will output:

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-37


PHP Associative Arrays
•> With an associative array, each ID key is associated with a
value.
•> When storing data about specific named values, a numerical
array is not always the best way to do it.
•> With associative arrays we can use the values as keys and
assign values to them.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-38


PHP Associative Arrays
•In this example we use an array to assign ages to the different
persons:

•This example is the same as the one above, but shows a


different way of creating the array:

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-39


PHP Associative Arrays

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-40


PHP Multidimensional Arrays

•In a multidimensional array, each element in the main array


can also be an array.

•And each element in the sub-array can be an array, and so on.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-41


PHP Multidimensional Arrays

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-42


PHP Multidimensional Arrays

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-43


PHP Multidimensional Arrays

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-44


7.3 Functions dealing with Arrays
• A whole array can be deleted with unset, as with a
scalar variable.
• Individual elements of an array also can be removed
with unset, as in the following:
$list = array(2, 4, 6, 8);
unset($list[2]);
• Now $list has three remaining elements with keys 0,1,
and 3 and elements 2, 4, and 8.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-45


• The collection of keys and the collection of values of an array can be
extracted with built-in functions.
• The array_keys function takes an array as its parameter and returns
an array of the keys of the given array. The returned array uses 0, 1,
and so forth as its keys.
• The array_values function does for values what array_keys does for
keys.
For example:
$highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67,"Thu" => 62, "Fri" => 65);
$days = array_keys($highs);
$temps = array_values($highs);\
Now the value of $days is ("Mon", "Tue", "Wed", "Thu", "Fri"), and
the value of $ temps is (7 4 , 70, 67 , 62 , 65).

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-46


• The existance of an element of a specific key can be determined with
the array_key_exists function, which returns a Boolean value. For
example, consider the following:
$highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67,"Thu" => 62, "Fri" => 65);
if (array_key_exists("Tue", $highs))
{ $tues_high = $highs["Tue"];
print "The high on Tuesday was $tues_high <br />";
}
• The is_array function is similar to the is_int function: It takes a
variable as its parameter and returns TRUE if the variable is an array,
FALSE otherwise.
• The in_ array function takes two parameters an expression and an
array and returns TRUE if the value of the expression is a value in the
array; otherwise, it returns FALSE.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-47
• The number of elements in an array can be determined with the
sizeof function.
For example, consider the following code:
$list = array("Bob", "Fred", "Alan", "Bozo");
$len = sizeof($list);
After executing this code, $len will be 4.
• It is able to convert between strings and arrays.
• These conversions can be done with the implode and explode
functions

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-48


explode & implode
• The explode function explodes a string into substrings and
returns them in an array.
• The delimiters of the substrings are defined by the first
parameter to explode, which is a string; the second parameter is
the string to be converted. For example, consider the following:
$str = "April in Paris, Texas is nice";
$words = explode(" ", $str);
$words contains ("April", "in", "Paris,", "Texas", "is", "nice").
• The implode function does the inverse of explode. Given a
separator character (or string) and an array, it catenates the
elements of the array together, using the given separator string
between the elements, and returns the result as a string.
$words = array("Are", "you", “coming", "tonight");
$str = implode(" ", $words);
$str has "Are you coming tonight"
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-49
Internal structure of Arrays
• Internally, the elements of an array are stored in a linked list of
cells, where each cell includes both the key and the value of the
element.
• The cells themselves are stored in memory through a keyhashing
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.
• the elements all have links that connect them in the order in
which they were created, which allows them to be accessed in that
order if the keys are strings and in the order of their keys if the
keys are numbers.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-50


Figure Logical internal structure of arrays

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-51


7.4 Sequential Access to Array
•PHP includes different ways to access array elements in
sequential order.
• Every array has an internal pointer, or marker, that references
one element of the array called the "current" pointer.
• current pointer is initialized to reference the first element of
the array at the time the array is created.
$cities = array("Hoboken", "Chicago", "Moab", "Atlantis");
$city = current($cities);
print("The first city is $city <br />");
This code produces the following:
The first city is Hoboken

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-52


current() & next()
• The "current" pointer can be moved with the next function,
which both moves the pointer to the next array element and
returns the value of that element.
• If the "current" pointer is already pointing at the last
element of the array, next returns FALSE.
• For example, if the "current" pointer is referencing the first
element of the $cities array, the following code produces a
list of all of the elements of that array: 
$city = current($cities);
print("$city <br />");
while ($city = next($cities))
print("$city <br />");
NB:creates problem when array includes an element with false
value. each function avoids this problem.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-53
each function
• The each function, which returns a two-element array consisting
of the key and the value of the "current" element
• It returns FALSE only if the "current" pointer has gone past the
last element of the array. difference between each and next
❑ each returns the element being referenced by the "current"
pointer and then moves that pointer.
❑ next function first moves the "current" pointer and then returns
the value being referenced by the "current" pointer.
consider the following code:
$salaries = array("Mike" => 4250,"Jery" => 5250,"Fred" => 3792);
while ($employee = each($salaries))
{ $name = $employee["key"];
$salary = $employee["value"];
print("The salary of $name is $salary <br />");
}
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-54
prev(),reset(),end(),key()
• The "current" pointer can be moved backward (that is, to the
element before the "current" element) with the prev function.
• Like the next function, the prev function returns the value of
the element referenced by the "current" pointer after the
pointer has been moved.
• The "current" pointer can be set to the first element with the
reset function, which also returns the value of the first element.
It can be set to the last element of the array with the end
function, which also returns the value of the last element.
• The key function, when given the name of an array, returns the
key of the "current" element of the array.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-55


array_push and array_pop
• The array_push and array_pop functions provide a simple way
to implement a stack in an array.
• The array_push function takes as its first parameter an array.
After this first parameter, there can be any number of
additional parameters. The values of all subsequent
parameters are placed at the end of the array.
• The array_push function returns the new number of elements
in the array.
• The array_pop function takes a single parameter, the name of
an array.
• It removes the last element from the array and returns it. The
value NULL is returned if the array is empty.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-56


foreach statement
• The foreach statement is designed to build loops that process
all of the elements of an array.
• This statement has two forms:
foreach (array as scalar_variable) loop body
foreach (array as key => value) loop body
• In the first form, one of the array's values is set to the scalar
variable for each iteration of the loop body.
For example:
foreach (Slist as $temp)
print("$temp <br />");
• This code will produce the values of all of the elements of $list

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-57


foreach statement
• The second form of foreach provides both the key and the
value of each element of the array.
Syntax:
foreach (array as key => value) loop body
• For example:
$lows = array("Mon" => 23, "Tue" => 18, "Wed" => 27);
foreach ($lows as $day => $temp)
print("The low temperature on $day was $temp <br />");

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-58


7.5 Sorting Arrays
• The sort function, which takes an array as a parameter, sorts the
values in the array, replacing the keys with the numeric keys, 0,
1, 2, ....
• The array can have both string and numeric values.
• The string values migrate to the beginning of the array in
alphabetical order. The numeric values follow in ascending order
$original = array("Fred" => 31, "Al" => 27, "Gandalf" =>
"wizard", "Betty" => 42, "Frodo" => "hobbit");
foreach ($original as $key => $value)
print("[$key] => $value <br />");
$new = $original;
sort($new);

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-59


asort()
• The asort function is used to sort arrays that correspond to Perl
hashes.
• It sorts the elements of a given array by their values but keeps
the original key/ value associations.
• As with sort, string values all appear before the numeric values,
in alphabetical order. The numeric values follow in ascending
order
foreach ($new as $key => $value)
print("[$key] = $value <br />")-,
$new = $original;
asort($new);

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-60


ksort()
• The ksort function sorts its given array by keys, rather than
values. The key/value associations are maintained by the
process
<h4> Array sorted with asort </h4>
<?php
foreach ($new as $key => $value)
print("[$key] = $value <br />");
$new = $original;
ksort($new);?>
<h4> Array sorted with ksort </h4>
<?php
foreach ($new as $key => $value)
print("[$key] = $value <br />");
?>
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-61
Figure The output of sorting.php

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-62


8. FUNCTIONS
• PHP supports user-defined functions
• The general form of a PHP function definition is as follows:
function name( [parameters] ) { } 
• Function names are not case sensitive. So, you cannot have a
function named sum and another named Sum.
• the parameters in the call to a function actual parameters.
• the parameters that are listed in the function definition formal
parameters.
• The number of actual parameters in a call to a function does
not need to match the number of formal parameters defined in
that function.
• If there are too few actual parameters in a call, the
corresponding formal parameters will be unbound variables.
• If there are too many actual parameters, the excess parameters
will be ignored
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-63
pass-by-value
• Default parameter-passing mechanism of PHP is pass by value.
• the values of actual parameters are copied into the memory
locations associated with the corresponding formal parameters
in the called function.
• The values of the formal parameters are never copied back to
the caller, so passing by value a one-way communication to the
function.
function max_abs($first, $second)
{$first = abs($first);
$second = abs($second);
if ($first >= $second)
return $first;
else
return $second;}
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-64
Pass-by-reference
• Pass-by-reference parameters can be done in PHP in two ways.
• One way is to add an ampersand (&) to the beginning of the
name of the formal parameter that you want to be passed by
reference.
• The other way is to add an ampersand to the actual parameter
in the function call.
function set_max(&$max, $first, $second)
{ If ($first >= $second)
$max = $first;
else
$max = $ second;
}
In this example, the first actual parameter in the caller is set to
the larger of the second and third parameters.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-65
The Scope & Lifetime of Variables
• The default scope of a variable defined in a function is local.
• If a variable defined in a function has the same name as a
variable used outside the function, there is no interference
between the two.
• A local variable is visible only in the function in which it is used
• PHP has the global declaration. When a variable is listed in a
global declaration in a function, that variable is expected to be
defined outside the function. So, such a variable has the same
meaning inside the function as outside.
• The default lifetime of local variables in a PHP function is from
the time the variable is first used (that is, when storage for it is
allocated) until the function's execution terminates.
• The lifetime of a static variable in a function begins when the
variable is first used in the first execution of the function. Its
lifetime ends when the script execution ends.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-66
9 Pattern Matching
• PHP includes two different kinds of string pattern matching
using regular expressions:
• one that is based on POSIX regular expressions and one that is
based on Perl regular expressions.
• The POSIX regular expressions are compiled into PHP, but the
Perl-Compatible Regular Expression (PCRE) library must be
compiled before Perl regular expressions can be used.
• 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 searched.
if (preg_match("/"PHP/", $str))
print "\$str begins with PHP <br />";
else
print "\$str does not begin with PHP <br />";

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-67


Pattern Matching contd
• The preg_split function operates on strings but returns an
array and uses patterns
• preg_split takes two parameters, the first of which is a
Perl-style pattern as a string. The second parameter is the
string to be split.
• For example, consider the following sample code:
$fruit_string = "apple : orange : banana";
$fruits = preg_split("/ : /", $fruit_string);
The array $ fruits now has ( "apple", "orange", "banana").

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-68


10.Form handling
• when PHP is used for form handling, the PHP script is
embedded in an XHTML document, like other uses of PHP.
• The recommended approach is to use the implicit arrays for
form values, $_POST and $_GET.
• These arrays have keys that match the form element names
and values that were input by the client.
• For example, if a form has a text box named phone and the
form method is POST, the value of that element is available in
the PHP script as follows:
$_POST["phone"]
•The built-in $_GET function is used to collect values from a form
sent with method="get".
•> Information sent from a form with the GET method is visible
to everyone and has limits on the amount of information to send
(max. 100 characters).
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-69
PHP Forms - $_GET Function

Notice how the URL carries the information after the file
name.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-70


PHP Forms - $_POST Function

And here is what the code of action.php might look like:

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-71


PHP Forms - $_POST Function

•Apart from htmlspecialchars() and (int), it should be obvious


what this does. htmlspecialchars() makes sure any characters
that are special in html are properly encoded so people can't
inject HTML tags or Javascript into your page.

•For the age field, since we know it is a number, we can just


convert it to an integer which will automatically get rid of any
stray characters. The $_POST['name'] and $_POST['age']
variables are automatically set for you by PHP.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-72


PHP Forms - $_POST Function
• When to use method="post"?
• > Information sent from a form with the POST method is
invisible to others and has no limits on the amount of
information to send.
• > However, because the variables are not displayed in the
URL, it is not possible to bookmark the page.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-73


Exercise The display of
popcorn3.html

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-74


Figure The output of popcorn3.php

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-75


11. FILES
• All file operations in PHP are implemented as functions.
11.1 Opening and Closing Files
11.2 Reading from a file
11.3 Writing to a File
11.4 Locking Files
11.1 Opening and Closing Files
• The first step in some file operations is to open it,
• a process that prepares the file for use and associates a
program variable with the file for future reference. This
program variable is called the file variable.
• For example,
$file_var = fopen("testdata.dat", "r") or
die ("Error — testdata.dat cannot be opened");

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-76


fopen & fclose
• The fopen function takes two parameters: the filename,
including the path to it if it is in a different directory, and a use
indicator, which specifies the operation or operations that must
be performed on the file. Both parameters are given as strings.
• The fopen function returns the reference to the file for the file
variable.
• Every open file has an internal pointer(file pointer) that is
used to indicate where the next file operation should take place
within the file.
• The file_exists function takes a single parameter, the file's
name. It returns TRUE if the file exists, FALSE otherwise.
• A file is closed with the fclose function, which takes a file
variable as its only parameter.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-77
Table File use indicators

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-78


11.2 Reading from a file
• 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.
• The reading operation stops when either the end-of-file
marker is read or the specified number of bytes has been read.
• The filesize function takes a single parameter, the name of the
file (not the file variable).
• For example, to read the entire contents of the file testdata.dat
as a string into the variable $file_string:
$file_string = fread($file_var,filesize("testdata.dat"));
• One alternative to fread is file, which takes a filename as its
parameter and returns an array of all of the lines of the file
$file_lines = file("testdata.dat");
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-79
Contd..
• PHP has another file input function that does not require
calling fopen, file_get_contents, which takes the file's name as
its parameter. This function reads the entire contents of the
file. For example, consider the following call:
#file_string = file_get_contents("testdata.dat");
• 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. Consider the following statement:
$line = fgets ( $file__var, 100);
• This statement reads characters from testdata.dat until it finds
a newline character, encounters the end-of-file marker, or has
read 99 characters.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-80


11.3 Writing to a File
• The fwrite function takes two parameters: a file variable and
the string to be written to the file. It is possible to include a
third parameter, which would be used to specify the number of
bytes to be written.
• The fwrite function returns the number of bytes written.
$bytes__written = fwrite($file_var, $out_data);
• This statement writes the string value in $out_data to the file
referenced with $file_var and places the number of bytes
written in $bytes_written. Of course, this will work only if the
file has been opened for writing.
• The file_put_contents function writes the value of its second
parameter, a string, to the file specified in its first parameter.
file_put_contents("savedata.dat", $str);

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-81


11.4 Locking Files
• file lock prevents any other access to the file while the lock is set.

• Scripts that use such files lock them before accessing them and
unlock them when the access is completed.

• File locking is done in PHP with the flock function, which should
sound 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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-82
12. COOKIES
• A session is the time span during which a browser interacts
with a particular server.
• A session begins when a browser becomes connected to a
particular server. It ends when the browser ceases to be
connected to that server.
• The HTTP protocol is essentially stateless,it includes no means
to store information about a session that is available to a
subsequent session
• Cookies provide a general approach to storing information
about sessions on the browser system itself. The server is given
this information when the browser makes subsequent requests
for Web resources from the server.
• Cookies allow the server to present a customized interface to
the client. They also allow the server to connect requests from
a particular client to previous requests, thereby connecting
sequences of requests into a session.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-83
• A cookie is a small object of information that consists of a
name and a textual value.
• A cookie is created by some software system on the server.
• Every HTTP communication between a browser and a server
includes a header, which stores information about the message.
• A message from a browser to a server is a request; a message
from a server to a browser is a response. The header part of an
HTTP communication can include cookies. So, every request
sent from a browser to a server, and every response from a
server to a browser, can include one or more cookies.
• At the time it is created, a cookie is assigned a lifetime. When
the time a cookie has existed reaches its associated lifetime, the
cookie is deleted from the browser's host machine.
• a particular cookie is information that is exchanged exclusively
between one specific browser and one specific server.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-84


setcookie function
• 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. The second, if present, is the new value for
the cookie, also a string. If the value is absent, setcookie
undefines the cookie. 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
setcookie("voted", "true", time() + 86400);
• This call creates a cookie named "voted" whose value is "true"
and whose lifetime is one day (86,400 is the number of seconds
in a day).
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-85
• In PHP, cookie values are treated much like form values.
• All cookies that arrive with a request are placed in the implicit
$_COOKIES array, which has the cookie names as keys and
the cookie values as values.
• most browsers have a limit on the number of cookies that will
be accepted from a particular server site.
• In many cases, information about a session is needed only
during the session
• Rather than using one or more cookies, a single session array
can be used to store information about the previous requests of
a client during a session.
• In particular, session arrays often store a unique session ID
for a session.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-86


12 Session Tracking
• One significant way that session arrays differ from cookies is
that they can be stored on the server, whereas cookies are stored
on the client.
• In PHP, a session ID is an internal value that identifies a session.
• Session IDs need not be known or handled in any way by PHP
scripts.
• PHP is made aware that a script is interested in session tracking
by calling the session_start function, which takes no parameters.
The first call to session_start in a session causes a session ID to
be created and recorded.
• On subsequent calls to session_start in the same session, the
function retrieves the $_SESSION array, which stores any
session variables and their values that were registered in
previously executed scripts in this session.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-87
contd
• Session key/value pairs are created or changed by assignments
to the $_SESSION array.
• They can be destroyed with the unset operator.
session_start();
if ($_POST[“uname"])!=“ ”)
{
$_SESSION[“username"] =$_POST[“uname"]) ;
print("You are visitor: $_SESSION[“username"] <br />");
}
• Session tracking is relatively simple in PHP.
• The session_start function creates a session ID. Session
variables are stored in the $_SESSION array.

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-88


Simple php program
//Wt12.php
<html><title>A simple math calculator</title>
<body>Insert two numbers in the form and hit submit button
<br>
<form action="calculation.php" method="post">
Firstnumber: <input name="num1" type="text" /><br>
Secondnumber: <input name="num2" type="text" />
<input type="submit" />
</form>
</body>
</html>

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-89


……………………//calculation.php
<html><head><title>Simple </title></head><body>
<?php
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$a = $num1 + $num2;
$b = $num1 - $num2;
$e=sqrt($num1);
$f=pow($num1,$num2);
echo "The sum of the two numbers is ". $a;
echo "The difference of the two numbers is ". $b;
echo "The sqrt of the numbers is ". $e;
echo "The power of the numbers is ". $f;
?></body></html>

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-90

You might also like