Documente Academic
Documente Profesional
Documente Cultură
Introduction
Programming languages use variables to store values. An array is a variable that can store a list of values. Arrays can be single-dimensional or multidimensional. All the values are referred by the same array name. In this session, we will learn how to create and use arrays. We will also learn how to initialize arrays, use single-dimensional and multidimensional arrays. In addition, we will learn to use array-related functions.
111 Defining. an A
A variable can store only one value at a time- We can change the value of the variable as many times as we want in the program. However, we can store only one value in the variable. An array is a variable that can store a set of values of the same data type. Each value in an array is termed as an element. All the elements are referenced by a common name- Each element of an array can be referred by an array name and an index. An array index is used to access an element. An index can be a number or a string. If the index is a string, the array is an associative array. If the index is a number, the array is an indexed array. By default, the index value in an array starts at zero. As a result, the index number of the last element in an array is one less than the total number of elements. For example, if there is in an array of five elements, the index number of the last element will be four.
6
Session 13
WIDE
PHP provides us with two ways of initializing an array: array () function Enables to assign value to all the elements of an array array identifier Enables to assign value to a specific element of an array
session 13
~_~AprIE
R LOWIDE
To view the value of the first element, enter the following: echo $department[1]
Note the result of the above code would be Finance.
Associative Arrays An associative array is an array where the index type is string. In associative arrays, the index value must be specified within double quotes. To create an associative array named department: $department = array("a" => 'Finance', 'HR', "d" => 'Purchase') 'Sales',
In the above code snippet, the array index type is a string. Note the index value starts from a. The index values are specified within double quotes. The department array contains .three values Finance, Sales, and HR.
To view the value of the third element, enter the following: echo $department["c"];
Note the result of the above code would be HR.
A P- FW C H,
Session 13
WORLDWIDE
To view the value of all the elements in the department array along with their respective index values, enter the following code:
$no_of_element = count($department); for ($i=0; $i< $no_of_element; { $rec = each($department); echo "$rec[keyl $rec[valuel echo "<br>";
In the above code snippet, the count () function calculates the number of elements that the array contains and stores the result in the $no_of_element variable. The each ( ) function retrieves each key value pair of an array and stores the result in the $rec variable. The for statement Y."11 continue to retrieve values of the array, till it reaches the last key value pair. The following will be the result of the above code:
0 1 2 3
Session 13
(APrECM ~= L D W I D E
Working with Arrays
Where, $merged_array_name - Specifies the name of the new array that will contain the merged element values $first array and $second_array - Specifies the names of the arrays whose elements are to be merged For example, we have two arrays, ITdept and SalesPurchasedept. The array, ITdept, contains values such as, Testing and Training. The second array, SalesPurchasedept, contains values such as Advertising and Marketing. To merge ITdept and SalesPurchasedept, use the following code: <?php $ITdept = array(O => "Testing", 1 => "Training"); $SalesPurcahsedept = array(O => "Advertising", 1 => "Marketing");
$AdminDept
array_merge($ITdept, $SalesPurchasedept);
The array AdminDept, will have values, such as Testing, Training, Advertising, and Marketing. Note that the element of the array that is mentioned first in the array merge( ) function gets the first index number. By default, PHP allots zero as the index number to the first array element. The first element value of the next array, SalesPurchasedept is allotted index numbers after allotting index numbers to the first array. The following code snippet would display $AdminDept [O] = Testing: echo "\$AdminDept[0] = ", $AdminDept[O]; Now, try to interchange the order of the arrays in the array merge following code: function, as shown in the
$AdminDept = arraymerge($SalesPurchasedept, $ITdept); echo "\$Ad-TninDept[O] = ", $ AdminDept[O],In the above code snippet, we have changed the order of the arrays' specified in the array_merge ( ) function. The output for this code snippet would be, $AdminDept [ 0 1 I Advertising.
.:)
Eil-PFECH
Session 13
WORLDWIDE
In a multidimensional array, one array is stored within another array. All the arrays specified in the earlier sections are single-dimensional arrays. In a single-dimensional array, the element includes only one level of key value pairs. Each element in a single-dimensional array requires an array name and an index. In the multidimensional array, each element is an array. Each element requires an array name and multiple set of indices. For example, in case of the two-dimensional array, each element requires array name and two set of indices instead of one. The syntax for creating a multidimensional array is: $array name = array(array(key => value), array(key => value)); Where,
$arrayname Specifies the name of the multidimensional array key - Specifies the index number of the array element
value - Specifies the value of the array element Note that we have one array() function within another. For example, to create an array named country_mdlist containing another array that includes information such as capital and currency of each country: $country_mdlist array( "USA" => array( "Capital" => "Washington D.C.", "Currency" => "US Dollar"), "England" => a.rray( "Capital" => "London", "Currency" => "Pound Sterling") , "Australia" => array( "Capital" => "Canberra", "Currency" => "Australian Dollar"), "New Zealand" => array( "Capital" => "Wellington", "Currency" => "NZ Dollar")); In the above code snippet, country_mdlist is a multidimensional associative array. It contains k e y i n d i c e s s u c h a s U S A , E n g l a n d , A u s t r a l i a , a n d N e v a E a c h a r r a y e l e m e n t of a multidimensional array includes another set of array within it that contains key indices such as Capital and Currency.
_-sssion 13
(A_PYTCM woRLowIoE
Working with Arrays
`o $country--mdlist["England"]["Currency"];
We can also create a multidimensional indexed array or a combination of associative and indexed array. Suppose we want to create an array that stores commission details of all the employees of an organization earned during the last six months, we can use a two-dimensional array. The first level of the array will store the names of the employees and the second level of array will store the commission of the employee earned during the last six months. To create the array that stores the employee commission details, enter the following code: e-moloyee_det = array( "Joe Brown" => array( 1 "$100", 2 "$150", 3 "$100", 4 "$160", 5 "$250", 6 -$148-), "T odd Mar tin" => array(
1
z
2 3 4 5 6
In the above code, we have used both associative and indexed indices to create a multi-dimensional array. To view the amount of commission earned by Todd Martin during the fifth month, enter the following code: echo $employee_detf"Todd Martiri")[5]; The result of the above code will be $280.
(APrecm
Session 13
WOR LDWIDE
Function
function arranges the
PHP enables us to sort an array based on the element value. The sort element values into an alphabetical order. The syntax for the sort sort(ArrayName) For example, to sort the department array, enter the following code: sort($department); After using the sort ( ) function, the order of the element values will be: 0 1 2 3 Finance HR Purchase Sales function is:
Note the order of the element values have changed and not the order of the index values.
13.6.2 rsort ()
Function
The rsort ( ) function is similar to the sort ( ) function- The only difference between the two is that instead of sorting in ascending alphabetical order the rsort function sorts the element values in the descending alphabetical order. The syntax for the rsort ( ) function is: roost (ArrayName) For example, to sort the department array in the descending alphabetical order, enter the following code: rsort($department); After using the rsort. ) function, the order of the element values will be: 0 1 2 3 Sales Purchase HR Finance
Note the order of the element values have changed and not the order of the index values.
~PTEC'/SiWORLDWID
Session 13
Working with Arrays
The syntax for the arsort arsort(ArrayName) For example, to apply arsort arsort($department);
function is:
The above code snippet instructs PHP to modify the array, as shown in the following output. 1 3 2 0 Sales Purchase HR Finance
Et.i117FECH
Session 13
LOWtOE
After using the array_f lip () function, the department array will be as follows:
F inance 0 Sales 1 HR 3 Purchase 3
To reverse the order of elements of the department array, enter the following code:
$dept 0 1 2 3 array_reverse($department);
To view all the key values of the department array, enter the following code:
array_keys($department);
I
2 3
F unctio n Name e n o t p i r c s D
count
nue n Iinb er dm ta c rma a o sy t f in ee s l h sizeof To remove an element value from the department array, enter the following code: Idaseu br nitt nme ce h array_pop ($departizient) ; olmnaay eautif fe eti nr . cnsh e s aW es n ) ( d a e o t c n u Kmem )plnm (eeebe o lf a c aov a vlt s tren uul n sc u ta ius hy f rn e Ia r .s o sm ch m After using the array-pop ()function, the department array will be as follows: array 0 Finance _flip 1 Sales Cneh ovre s t 2 HR emnaeidxaenidxae e vut ua n ut l et l snevl s d evl s o u a v n m l e o array To add an element value to the department array, enter the following code: _intersec array_push($deparUrient, "Marketing"); t Ietsnrrse diadtn n et f uh e cm oemtaemnaruo o mn ev a ogop e u l nl g f s y r a After using the arraypush ( ) function, the department array will be as follows: () 0 Finance D p s ir y a l h t k e n d c o f 1 Sales array 2 11 R reverse 3 Purchase Re vt een te sl rf s h o d r h tm y a 4 Marketing () V 1.0 2004 Aptech Limited Scripting with PHP Re m etr asa sef no rv ut to dn l r i fy h m () I hterir deaos etnkty nrgie f iex i on t ond w ya s vn array push V 1.0 2004 Aptech Limited Page 162 of 274 Ase omtted dnr rl eho do e nnf ome s o Web Scripting with PH: ar n a y
o o o o
(A P rECH
Session 13
\1WORLDWID E
s y a A h t w g n i k r o W
A variable can store only one value at a time. An array is a variable that can store a set of values of the same data type. Each value in an array is termed as an element. All the elements are referenced by a common name. An array index is used to access an element. An index can be a number or a string. If the index is a string, the array is an associative array. If the index is a number, the array is an indexed array. We can combine the element values of two or more arrays. This process is called as merging arrays. In a single-dimensional array, the element includes only one level of key value pairs. In the multidimensional array, each element is an array. Each element requires an array name and multiple set of indices. There are two types of arrays: Indexed array Associative array
An indexed array is an array where the index type is integer. An associative array is an array where the index type is string. In associative arrays, the index value must be specified within double quotes. We can combine the element values of two or more arrays. This process is called as merging arrays. Multidimensional arrays are arrays that store another array within it. In a single-dimensional array, the element includes only one level of key value pairs. In the multidimensional array, each element is an array. Each element requires an array name and multiple set of indices.
V 1.0
~PTE'CH
Session 13
WORLDWID E
sort ( )
The sort() function arranges the element values into an alphabetical order. The rsort ( ) function sorts the element values in the descending alphabetical order. The arsort function can sort both associative and indexed arrays.
count()
array_count_values() array flipo array_intersect() array _-keyso array pop( array push
o
.:;Sion 13
Working with Arrays
;1~11
a. b.
C.
array
f u n c t i o n
d.
Use the __________________ to assign values for all the elements in an array at once.
a. c.
C.
d.
To combine the element values of the two arrays, we use _______________________ function.
a. b.
C.
arraycombine( )
d The order
a. b.
C.
d.
in an array. aarraycount( b.
C.
d.
array_countvalueso
Page 13 of 274
Elf:PFECII
Session 13
WORLDWIDE
function identifies the common element value among a specified group of array.
a. b.
C.
d.
7.
a. b.
C.
d.
Page 14 of 274
Objectives
At the end of this session, you will be able to:
>
Create and use arrays Merge arrays Use single and multidimensional arrays Use array- related functions
The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are m6t and the understanding of the tool is complete. Please follow the steps carefully. Part I - For the first 1.5 Hours:
14.,JIJI &I
We can create an array and set the initial values of array elements using the array() function. The arrayo function uses key value pairs separated by a comma to create an array. The number of key value pairs in the arrayo function determines the number of elements in an array. Using arrayo function, we can create both associative and indexed arrays.
We will create an array that contains names of various programming languages such as, VB,
Java, Perl, PHP, VC++, C++, .NET, and Delphi_ 1. 2. Open the gedit text editor. To create an array named lang, enter the following code: <?php $ 1 2 3 4 5 6 lang = array
=> - "VB",
=> ".NET",
7 => "Delphi")
A P - T IE C A - i l l -
W Z ALLD W 4-0-4E
Session 14
Working with Arrays ,6w It'd M , 6 tf
in
The each () function retrieves each key value pair of an array and stores the result in the $row variable. The for statement will.continue to retrieve values of the array till it reaches the last key
value pair. After entering the code, the PHP file appears as shown in Figure 14.1.
ew
Open
0 n~
Cut , C6py P
Paste
R#W'Replace
Untitled 1* x
<?php Slang = array( 1 => "VB", 2 => "Java", 3 => "Perl", 4 => "PHP", S => "VC++", 6 => "NET", 7 => "Delphi"); Selnits = count($lang); for ($i=O; $i<$elmts; $i++) f L $row=each($1ang); echo "$row[key] $row[value] echo "<br>";
INS
Page 16 of 274
Sessuon 14
APTECH
waa~ow1ae
142 Using
We can initialize value of a specific element in an array using the array identifier. The array identifier also helps us to create both associative and indexed arrays. We can also create the lang array using the array identifier.
ds'
Session 14
_ __________________________________________
Working with Arrays
To calculate the total number of elements in the array and store it in a variable,. enter the following code:
4e2mts
,
count ($1ang),;
fangiarray.,along.~ h th-jr.respecti h e . . , v e d e x , v a l u e s ,
After entering the code, the PHP file appears as shown in Figure 14.3.
Untitled! ~ _ t q gedit j f q (modified) ~ -
<?php $lang[] "U"; Slang[] "Java"; $1 ancy"Pert", Slang[] PHP Slang[] " VC++ Slang[] "'.NET" Slang[] "Delphi"; $elints = count($lang); for ($i=0; $i<$elmts; $i++) $ro;v=each($lang); echo "$row[key] $row[value] echo "<br>";
Ln 20, Col. 3
INS
Figure 14.3 : Using the Array Identifier 5. Save the file as mylang.php under the Open the Mozilla Web browser.
/var/www/html
directory.
Session 14
wonLowIoe Crte
Type http: //localhost/mylang.php in the address bar and press Enter. The PHP. script is executed and all the element values of the array along with their respective index values are displayed, as shown in:. Figure 14.4.
File Edit View Go Bookmarks Tools Window Help Back OVB I Java 2 Per] 3 PHP 4 VC++ 5 .NET 6 Delphi Forward Reload Stop http:/Aocalhostfmylanlv LASearchl Print
!~j Home I *Bookmarks Red Hat Network 6Support (Shop eft Products Training
Note the index value starts from 0. PHP automatically assigns the index value from zero when
we do not specify the index value.
s ,:and
,
$applic
"Windows 2003");
=>
zz Scripting
with PHP
Sess~
n 14
(,-4PY-,EC,M
LMW I'DE
zz Scripting
with PHP
$rec[valuel
recto
ht n on
sN;
Back
jWoad Stop
Search
51i[440~ toduels~~
1 Windows 2000 2 Windows 2003 Application Operating systems 1 Windows 95 2 Windows 98 3 Windows ME Merged array ofOperatin g Systems Windows NT 1 Windows 2000 2 Windows 200 3 Windows 95 4 Windows 98 5 Windows ME
Q
1 4 . 4 U in, g Multidimen
nsional Array
In the Multidimensional array, one array is stored within another. Each element in the multidimensional array is an array. Each element is referenced by an array name and multiple sets of indices. For example, in case of the two-dimensional array, each element requires array name and two set of indices instead of one.Web
WOWk, S e s s i o n 1 4
A P rECITI
D W I'D -9
I-
Session 14
APTECK
WO, R'L'U W1 D E
text editor.
".Luce -
'GrAc.
'%ff6i 1 0:
"Grade-; "Gender"
=>
lace .'d 0
"Female"),
004 => array( "Name" => "Jack Thompson", "Email" => "jack.t@flaymore.edu", "Grade" => "B+ "Gender" => "Male"),
Note that the $student array is a multi-dimensional array. 001, 002, 003, and 004 are the index values of the elements which in turn are arrays that includes student information, such as the name, email address, grade and gender.
3.
display 11 n ormation stored in the $student array.-,, enter the .:code as To ~!gpi theAid;
,
Page 22 of 274
Session 14
W0 A
View
Search
Tools
p o c u m e n t s Eelp
ID t: [q 9
Save Print Undo Redo Cut Copy Paste
Find Replace
$row=each($student); $val= $row[key]; echo "$val echo "<br>"; Svalcount=count($student[Sval]); for ($t=0; $t<$valcount; $t++) $rec=each($student[$va1]); echo "Srec[key] Srec[valuej"; echo "<br>"; echo "<br>";
1'f.FAM3,CoIAT
mozilla
;x
4 G4
S~;-:~,
Formel
Back
Reload Stop -
31
_B
&
!,j Home;
001 : -NanK: Chris Edwards Email : chris.eO'na% awre.edU Grade : A Gender - Male (X)2 : Nmw Marlin. Lake Email. martina.K&Ilaynxire.edu Grade A+ Gender : Female 003 : Name Luce Grace Email lucc.g. eflaviwre.edu Grade B Gender : Female 004 Nam : Jack Thompson Grade : 13+ Gender: Male
-j-_ L.1 ~~ LA)
(V I Done
1 .1 ............
Session 14
W0::RLDWVD:E
.1 4.5-:'Sorting PHP provides us with various functions, such as s o r t enables us to sort the element values of an-array.
rsort
and arsort
that
We will use the various functions to sort the elements of the Slang array.
echo echo
for($i=0;
$i<$total_elmt;.
$rec = each ($lang)echo "$rec (key] 6 c [value] echo "<br>"; echo "<br>"; To sort. the $immcr array inthe w alphabetical .
777
P H P s c r i p t :
sort
($1axit'r)
Page 24 of 274
Session 14
(APrEcm 0 R'L D W I VE
Slang = array( 1 => "VB", 2 => "Java", 3 => "PHP", 4 => "Delphi",); $totalelmt = count($lang); echo "Original array"; echo "<br>"; for ($i=0; $i<Stotalelmt; $i++) $rec = each($lang); echo "$rec[key] $rec[value] echo "<br>";
I
echo "<br>"; sort($1ang);j
~
"
M A
~~IMINJ'/
Figure 14.8 : Sorting the Array Alphabetically 5. To display all the: .- elements of. --,`tKfIIani'g following code:
4rrayi, e prItIh, th ',Viriray en erW, enter
the
for($i=0; $i<$tota1e1mt; $i++) $rec = each($lang); echo "$rec (key] $rec [value]"; echo "<br>";
6. 7. 8.
Save the file as modLang.php under the jv6tjww/htxnI dIfW ry. Open the Mozilla Web browser. Type http://localhost/mbdLang.php in the address bar and press Enter. All the elements of the lang array before and after sorting are displayed, as shown in Figure 14.9.
Session 14
rAPywcm
11WOR VDW11-0Z
It F
:..A.ack Forward
j Home 1(
h
-
1v
Reload Stop
jp-Search
C-4 , Print
Marks* Red Hat Network 6S.ppwt (gs hop CdPr ducts (:lTraining
Original array 1 VB 2 Java 3 PHP 4 Delphi Modified array 0 Delphi 1 Java 2 PHI? 3VB
Figure 14.9 :
Tqoj.ried) - gedit
R i i Edit
I ew
Bids
olk
U T41
-f-
Save Open
7j' modLang.php* x
echo "<br>
echo "<br>"; rsort($1ang);1 $total_elmt = count($lang); echo "Modified array"; echo "<br>"; for ($i=0; $i<$total_elmt; $i++) $rec = each($lang); echo "$rec[key] $rec[value] echo "<br>"; I
Ln 20, Col.
INS
~Z I
Page 26 of 274
Web Scripting ,: :- =
Session 14
(A'Prrcm WORLDWIDE
Working with Arrays
11.
12. Open the Mozilla Web browser. pe http://localhois.tlmodLan bp and press Enter T- e .,b inal
Rip
,-the
s000
ar
4 i , Zg r a y 4 . . . ~
-sh6
ppe p
0~gure
-WRIP'M
(APT.PCH
Session 14
7" LOWIDE
s y a A h t w g n i k r o W Part II - For the next half an hour: Venture Capital Inc. is a trading company that deals in automobile parts. It has branches in countries, such as USA, Australia, Russia, Japan, Africa, China, and New Zealand. 13. Create an indexed array that includes the names of the seven countries where the branches of Venture Capital Inc. are located using the array identifier. Also, display the contents of the indexed array. 14. Sort the contents of the indexed array in the alphabetical order. 15. Sort the contents of the associative array in the descending alphabetical order. 16. Create and display the contents of a multi-dimensional array that contains the following information:
F L E S U O I Y R T I
Page 28 of 274
Objectives
At the end of this session, you will be able to:
Discuss about Database APIs Connect to the database Use data access functions );11 Perform SQL queries using PHP Build HTML tables using SQL queries
Introduction
A database is used to store the data. Many RDBMS such as Access, Oracle, and MySQL are available. On the Linux operating system, MySQL is mostly preferred because it is open source software. It is easy to use and can run on any platform. In this session, we will learn how to connect to a database through PHP. We will also learn how to use the data access functions and perform SQL queries using PHP. In addition, we will learn to display the records of the table in HTML tables using SQL queries.
6-4py-'Ecm S es s i on 1 5
W"LDW D
password Specifies the user password. This is an optional argument. This value can be entered later in the codes
link_id Stores the return value of the connection. This variable is used to check
whether the connection is established or not. For example, to connect to the MySQL server: $linkid = mysql_connect("localhostl,"rooL","abc123"); Here, the user is considered as root. It has localhost as the server name and abc123 is password.
r-:z
Session 15
(APr,ECJV
WORLDWIDE WO
$server $username = "root"; $password = ""; $connectmysql = mysqlconnect($server, $username, $password); $db_list = mysqllist_dbs($connectmysql); echo "Connected to the Server"; echo $db_list;
The above codes show the connection to MySQL server. The hostname or the server name and the password are left blank. Here, the root user is not assigned to any specific host. As well as it does not have any password. The username is assigned as root. In the above code, connection is established with the MySQL server. All the names of the databases on the server are stored in the $dblist variable. mysq1_se1ect_dbO Sets the specified database as the current database. The syntax for the mysqlselect_db() function is:
mysqlselectdb("database_name", $link_id);
Where,
database_name Specifies the database name linkid Specifies the return value of the connection
$connect m sql Y
Session 15
echo "Current Database is selected";
Oft-LDWIE
In the above code, we have set the mysql database on the server as the current database. If the database is present on the server, the message with the echo command is displayed. If the connection fails with the server, the message with the die () function is displayed. A die ( ) function is equivalent to the exit function. This function terminates the current program>
mysq1_1ist_tab1es () - Displays a list of all the tables available in the specified database.
The syntax for the mysqllisttables ( ) function is: mysql_list_tables("databasename", $link_id); Where, database name Specifies the database name linkid Specifies the return value of the connection For example, to list all the tables of the mysql database: <?php $server $username = "root"; $password = ""; $connectmysql = mysql_connect($server, $username, $password); $tab_list = mysqllisttables("inysql", $connectmysql); it(!$tablist) echo "Database does not contains tables"; exit; else echo "$tab_list";
In the above code, connection is established with the server. All the tables available in the mysq.l database are listed and stored in the $tab list variable. If the database contains the tables, they will be displayed. If the table does not exist in the database, the message with the echo command is displayed and the execution will come to an end. mysqlnum_rows () Displays the number of rows present in the specified table.
Page 32 of 274
Session 15
('APr,FCM
11~
w" LOWIDE
Handling Databases with PHP The syntax for the mysalnumrows ( )function is-, mysqlnumrows("tablename"); Where, table_name specifies the name of the table for displaying the number of rows present in it. For example, to list the number of rows of the specified table: <?php $server $username $password
.11 ;
"root";
$connectmysql = mysal_connect($server, $username, $password); $row_num = mysqlnumrows("usercontact"); if(!$row_num) { echo "Table does not contains any data"; exit; else echo "Row number.
In the above code, the numbers of rows from the table are listed. If there are no rows in the table, the message specified with the echo command is displayed. If the rows are present in the table, the total numbers of rows are displayed.
function.
2 0 0 4
A p t e c h
L i m i t e d
<?php $se.rver
(4,-;]7PECif
Session 15
L D W A O-E
In the above code, we have set the mysql database on the server as the current database. If the database is present on the server, the message with the echo command is displayed. If the connection fails with the server, the message with the die () function is displayed. A die () function is equivalent to the exit function. This function terminates the current program. mysq1_1ist_tab1es () - Displays a list of all the tables available in the specified database. The syntax for the mysqllisttables() function is:
mysql_list_tables("databasename", $link_id);
Where,
databasename Specifies the database name linkid Specifies the return value of the connection
For example, to list all the tables of the mysql database:
<?php $server $username = "root"; $password = "" $connect_mysql = mysql_connect($server, $username, $password); $tab_list = mysql_list_tables("mysql", $connect_mysql); if(!$tab_list) echo "Database does not contains tables"; exit; } else echo "$tab list";
In the above code, connection is established with the server. All the tables available in the mysql database are listed and stored in the $ , c.ab list variable. If the database contains the tables, they will be displayed. If the table does not exist in the database, the message with the echo command is displayed and the execution will come to an end.
mysq1_num_rows () Displays the number of rows present. in the specified table.
(APY-ECM
Session 15
WORLDWORLDWIDE
Hnl g abss i P P ad Dt aewh H i a t n The syntax for the rnysalnumrows ( )function is: mysqlnumrows("tablenaiiie"); Where, table name specifies the name of the table for displaying the number of rows present in it. For example, to list the number of rows of the specified table:
<?php
"rooL";
11 It ;
$connect_mysql = mysql_connect($server, $username, $password); $row_num = mysql_numrows("usercontact"); if(!$row_num) echo "Table does not contains any data"; exit; else echo "Row number I $row_num";
In the above code, the numbers of rows from the table are listed. If there are no rows in the table, the message specified with the echo command is displayed. If the rows are present in the table, the total numbers of rows are displayed.
function is:
$server
ARTECAW
Session 15
WO R L D W I D E
if(!$tab_list) f echo "Database does not contains any table"; exit; else $row-nuin = roysql_num_rows($tab_list); I if(!$row_num) echo "Table does not contains any data"; exit; I else echo $row_num;
s end s q u erie s t o the a ctiv e d at aba se . T h e My SQL co m mand s su ch as SE L EC T , S H C - . , - , EXPLAIN, and DESCRIBE works with this function The syntax fo r the irvsql_query( )function is: inysal_query(querv, link-id); Where,
Page 36 of 274
query Specifies the MySQL query. 1 1, inkid Specifies the return value of the connection
F-
Session 15
The queries must be enclosed within the double quotes and must not end with a semicolon (;) symbol. The link-id. is optional. > mysq1_fetch_rowO- Fetches the resultant rows as an array. Each row of the table is placed in an array. These rows are accessed with the index numbers starting from 0. The syntax for the mysql_fetch-rowo function is: mysql_fetch_row("table_name"); Where, result specifies the table argument of the () function.
mY9q1_fetch_arrayO- Fetches the rows of the table and saves it as an array. It is an extended version of () function. The syntax for the mysql_fetch-array ()function is: mysql-fetch-array("table-name"); Where, table namespecifies the name of the selected table. myogl - fetch - fieldo- Displays the details of the column, such as the column name, table name, and maximum length of the column, column constraints, and column type. The syntax for the mysql-fetch-field( ()function is: mysql-fetch-field("table_name"); Where, table namespecifies the table name. mysq1_fie1d_1enO- Displays the length of the specified field The syntax for the mysql-field-leri ()function is: n)ysql_field_].eri("table_name", "field-name."); Where, table-name - Specifies the table name field name - Specifies the field name for which the length needs to be displayed mysq1_num fields O- Displays the number of fields in the specified table. The syntax for the mysql_num-f fields ()function is: rr,ysql_num_1"ields (" table-na.me") Where, table_name specifies the table name.
V 1.0 Oc 2004 Aptech Limited Page 187 of 274
-'.ab
Session 15
Handling Databases with PHF To display the records of the table from the USER database, enter the following code:
if($connectmysql) f echo 'Connection established"; I else die("Unable to connect"); $mysqldb = mysqlselectdb(-USER"); if($mysqldb) echo "Connected to the database"; I else die("Unable to connect to the database");
I
FROM usercontact;");
while($row = mysqlfetcharray($sqlquerv)) echo "<BR><BR>$row[user_idj"; echo " $row[user_namel"; echo " $row[user_einail__id1"I if(mysql_num_rows($sqlquery)<1) echo "No result";
Page 38 of 274
C4-PTIECII
Session 15
R LOM IV 6
1
Table 15.1 : user contactTable To create a table using the SOL commands in PHP: 1. 2. Open the gedit text editor. Enter the following code:
U";
"root";
$connectmysql = mysqlconnect($server, $username, $password); if($connect_inysql) echo "Connection established"; else die("Unable to connect");
$mysql_db = MYsql_select_db(,'USER"); if($mysqldb) echo "Connected to the database"; el se die("Unable to connect to.the database");
39
Session 15
Wamllulb?. lam
"CREATE TABLE USER CONTACT(".-USERID INT NOT NULL .RY KEY,-."USERNAME CHAR(25) NOT `d LL, "-"USEREYLAILID CHAR(25)".
In the above code, the USER CONTACT table is created in the USER database. The table is created using the CREATE command of SQL. 3. 4. 5. Save the file as mysqltable.php under the, /var/www/html directory. Open the Mozilla Web browser. Type http: // localhost/mysql table. php in the address bar and press the Enter key. The output appears, as shown in Figure 15.1.
0 a
File Edit View Go Bookmarks Tools Window Help Back Forward Reload Stop
4*f
http://loci
Search
I
!jHorne 'jBookmarks
Done
Figure 15.1 : Creating a Table We need to insert records in the table once we have created the table. PHP enables us to store the form data in the database. The records in the table are inserted with the HTML method.
Page 40 of 274
Ei-PTE-CDA 0 R V WWA
Handling Databases with PHP
To insert records in the USER CONTACTtable:
< ?php
$server Susername = "root"; $p a ss wo r d = $connectmysql = mysq1connect(Sserver, $username, $password); if($connect_mysql) echo "Connection established"; else I
r
die("Unable to connect"); I $db = "user"; $mysqldb = mysql_select_db($db); if($mysql_db) echo "<BR><BR>Connected to the database"; else die("Unable to connect to the database"); I "INSERT INTO user contac $S UJ_ 4 n se rt ( u s e r i d , u s e r n a me , u s e r e m a i - l i d) V A I - I I JE S ( 10 1 , ' Jo h n ' , ' j o l i r i @ m a i i . c o m ' Sresult = mysqlcruEry(';sql--irisei-t) ;
4 1
ult)
{ f($res echo "<BR><BR>THE RECORDS ARE INSERTED"; else e c h o " R E C O R D S C O U L D N O T B E I N S E R T E D I N TH E TA B L E " ; mysql_erroro;
In the above code, records are inserted in the table using the 1 N S E R T command. If there exist any error, the m sqi erl or() function returns the error message that is sent by the MySQL server.
y
AprITCA41
Session 15
Handling Databases with PHP
Using the SELIECT command, we can access data from the tables. For example, to display all the records from the user contact table: <?php
$server $username = "root"; $password = ""; $connectmysql = mysql_connect($server, $username, $password); if: ($connectmysal.) echo "Connection established"; } else die("Unable to connect"); I $db = "user"; $mysqldb = mysql_select_db($db); if($mysqldb) { echo "Connected to the database"; else die("Unable to connect to the database"); $sql_disp=("SEIIECT FROM usercontact;");
Page 42 of 274
session 15
A4
( .A;~PrFcm
WO-K L; WW 10 E
Hnl g aaaewh H a d Dtbss i P P i n t In the above code, the records such as USERID, USERNAME, and USEREMAILID from the user contacttable are displayed. The DELETE and UPDATE commands helps to modify the contents of the table. For example, to delete a record from the table: <?php
$server $username = "root"; $password = ""; $connectmysql = mysqlconnect($server, $username, $password); Jf($connectmysql) echo "Connection established"; else die("Unable to connect");
I
$mysqldb if($mysal_db)
mysql_selectdb("USER");
ecl-)o "Connected to the database"; else die("Unable to connect 4-o the database"); $sq7 dolete= ("DELEETE FROM usercontact ',,,7.HERE user_id $resul-t=mysqlqiiery($sql._delete); if($result) echo "$result- RECORDS ARE DELETED"; } else echo "RECORDS NOT FOOND IN THE TABLE"; mvsql_erroro; '101
Page 43 of 274
Session 15
W *0 RALID W 1-10-6
Handling Databases with PHP After deleting the records from the table, check the table contents at the MySQL command prompt using the SELECT command. For example, to update a record in the table: <?iDhp $server $username $password
"root"; "";
echo "Connection established"; else die("Unable to connect"); $mysql_db = mysqlselect_db("USER");if($mYsaldb) echo "Connected to the database";
I
update= ("UPDATE user contact SET username ='Jenniffer' WHERE userid ='101'");
$resulll=mysql_qLiery($sql_t2pd,ate); if($result) echo "RECORDS ARE UPDATED"; else echo "RECORDS COULD NOT BE UPDATED !N THE TABLE"; mysql _error() ;
After updating the records in the table, check the table contents at the MySQL command prompt by using the SELECT command.
Page 44 of 274
Session 15
64 P T E C H O RLDWIDE
<BODY> <?php $server $username = "root"; $password = "'; $connectmysql = mysql_connect($server, $username, $password); if($connectmysql) echo "Connection established"; $mysqldb = mysqlselectdb("USER"); if ($my-sql_djD) echo " <BR><BR >Connected to the datahase<BR><BR>"; echo "<TABLE BORDER BGCOLOR="WIIITE">"; echo <TR><T]I>USERI*Y)<'!'H><TH>US"--RNAME<Tll><TII>USEREMAI'LID </TH>"; e c h o " < D B Q U E R Y q > s e l e c t * f ro m u s er c ont a ct "; echo "<DBROW><TR><TD><? qJJSERID>-:::/TD><TD><? q.USERNAME></ TD><TD><? q.USEP--EM---"LLI])><./TD><iTR>"; echo "</DBQUERY>"; echo "<I/TR>"; echo "</TAI3LE>"; </BODY> </IITML>
The above code will display the records of the user contact table on the Web browser in the tabular format. The DBQUE:i? y and the DBI R low are the HTML tags. The DDQUERY tag executes records for the SQL query. The i)RRow tag is used for placing text in the row.
1.0 C(`
2004
Aptech Limited
Sess qn 15
o
EifprEchr
O WLOAV1404r.
Database APIs allows developers to write applications that are movable or between the database products. The common databases APIs are Native-Interface
,
easily accessible
PHP is connected to MySQL using three arguments. The three arguments are the MySQL server host name, the MySQL u ser name, and the MySQL user password. The connection with e server is established with the help of mysq1_connect( ) function The b sic PHP functions those are used with respect to the database are
() mysqlfetchrowo,mysqlfetchfieldo,mysql_fieldleno, mysq1numfieldso'
-77
--
1.0 C(`
2004
Aptech Limited
Session 15
(-4-12TECH
0 UL W: O IO 3 0
1.
function.
mysq1.se1ectdbO mysgl_connect() connect_mysq1() function displays the total number of rows of the specified table. mysgl_fetch_array() mysgl_select_db() mysgl_list_tables()
2.
The a. b.
C. d.
mysqlnumrowso function displays the details of the columns of the table. mysqlfetchfieldo mysgl_fetch_row() mysal_fetch_array() mysgl_num_rows()
3. Th a. b.
C.
d.
4.
5.
_________________________
command in PHP. a. b. C.
d.
Records can be modified in the table using the ___________ command in PHP.
a. b. C. DELETE INSERT SELECT UPDATE
d.
Page 48 of 274
Obi ecflves
At the end of this session, you will be able to: Set a cookie > Retrieve a cookie in PHP Delete a cookie
I n t r o : - thon..
Web sites store information of registered users in databases to keep a track of regular visitors. There are majority of users who do not register with the Web site but frequently visit the Web site. For storing information of such visitors, we use cookies. Cookies enable Web sites to store user information. In this session, we will learn how to set, retrieve, and delete cookies in PHP. In addition, we will learn about the various security issues relating to cookies.
id.--i -Injor'odudin-ra-. Cookie.HTTP is a stateless protocol because the execution of the Web commands happens independently. The execution of the current command is without the knowledge of commands that came before it. When a Web browser requests for a static Web page, the server responds by sending the Web page the browser requested for. The process does not involve any interaction with the user. The user simply clicks the hyperlink on the Web site and accesses the Web page having some content. Figure 16.1 shows the transfer of static data from Web server to Web browser.
Request Response
)01
Figure 16.1 : Transfer of Static Web Page For dynamic Web pages that require user interaction, scripting languages such as JavaScript, PHP and ASP are used. Dynamic Web pages take in information from the user and record it for further processing. For example, on an online shopping Web site, the user browses through the Web site. The product that the user purchases are added to the shopping cart. On completion
APYIEC"
Sessuon 16
W00 : R L D W9.0 19
Working with Cookies of the order, the Web site prompts the user to enter personal details for order confirmation and delivery. Figure 16.2 shows the working of the dynamic Web pages. Data sent for Processing Data is A Processed Processed Data to Web server
Figure 16.2 : Transfer of Dynamic Web Page Web sites store two types of data, such as temporary and permanent data. Temporary information is stored in cookies for a certain period. Web site stores permanent data in cookies for a certain period and then saves the required information in the database. Web sites use two types of cookies: Persistent - Exist in the Web browser for a period specified at the time of its creation Non-persistent - Deleted from the Web browser as soon as the user exits the browser For example, on an online shopping Web site, a user selects few products and adds them to a shopping cart. The user moves on to the next page to select some other products. In such a situation, the user information needs to be stored somewhere before the user moves to the next page. Although the user has not completed the transaction, the Web site stores the data in a temporary variable called cookie. Figure 16.3 shows the temporary data being stored in a cookie.
User adds a product to shopping cart confirmation
................... .
Temporary data For
Beforeorder
When a user cancels the order, the products added to the cart are no longer useful to the Web server and the Web browser. Such temporary data stored in the cookie is deleted as soon as the user cancels an order or exits the Web browser. Figure 16.4 shows the deletion of the temporary cookie when the user cancels the order.
V 1.0 :D 2004 Aptech Lin)ited
Page 50 of 274
When a user visits the Web site for the first time, the Web server creates a unique ID and sends the ID in the cookie to the Web browser. The browser stores the cookie and sends it back to the Web site in subsequent requests. The Web server can read the information stored in the cookie only when it is related to the Web site. The life of a cookie depends on the expiration time and date. The cookie is stored on the hard disk of the user. This enables the Web site to keep a track on the user visiting the Web site. The information about the user is generally stored in the name-value pair. Web servers and Web browsers send cookies to each other in HTTP headers. The Web server sends the cookie to the browser in the Set-Cookie header field. This field is a part of the HTTP response. The Web browser stores the cookie and uses the same in subsequent requests to the same Web server. Consider the following HTTP response header: HTTP/2.0 207 Content-Lengch: 8451 Coast e,n(:.-Type: text/]"itrnl Date: Hon, 27 Dec 2004 05:29:24 GMT Expires: Mon, 27 Dec 2004 05:29:44 GIRT Set.-Cookie: city-(_,asL-(-:oasL._USa In the above HTTP response header, the following is displayed: > > Version number of the HTTP protocol Size of the content Type of the content Date and time of response Expiry date and time of the cookie Cookie header
Sessuon 16
WORLDWISS .4 R F, U Cif
Session 16
Working with Cookies
wn~ The Web browser records the cookie information and saves it on the hard disk of the system. In subsequent requests made to the Web server for a Web page, the information is sent along with the HTTP request header. Consider the following HTTP request header:
GET /usa/florida.Dhp HTTP/21.0 Connection: Keep-Alive Cookie: city=east-coast-usa Host: www.Webworldmaps.com Referrer: hLtp://vAN-,v.Webworld-maps.com/
Note the cookie in the above sample request. This cookie can be set by using the set-cookie function. The above code snippet shows the subsequent request that a Web browser sends to the Web server.
value - Refers to the value of the cookie that is stored on the client system. This is a mandatory attribute.
expiry daL.C., - Indicates the date and time (UNIX timestamp) when the cookie will expire. The cookie is not used once the expiry date is reached. This is an optional attribute.
6;~- UNIX
timestamp signifies the time and date that the time H function returns. The time is measured in the number of seconds from 'Is' January 1970 00:00:00 GMT.
Page 52 of 274
subset of the URLs present in the domain where the cookie is applicable. If the path attribute is not specified in the setcookie function, the path of the document present in the header is taken. domain - Refers to the domain name where the cookie is made available Indicates the type of HTTP connection that the cookies will pass through.
When the value of the secure parameter is set to 1; the bookie will be'-set only if a secure
secure -
When the cookie is set, the value is automatically URL encoded- When the script retrieves a cookie, it automatically decodes the value. PHP executes codes in a particular sequence. HTTP headers are executed before the scripts. Cookies are a part of the HTTP header. There can be more than one cookie in the header but it should relate to the same domain or website- The code related to the cookies must be specified before: HTTP header Displaying any content Any white space
If any content is displayed before calling the setcookie ( ) function, the function will fail and return False. So before displaying any output or even the white space, setcookie ( ) function must be called. If the setcookie ( ) function runs successfully, the function returns True. c,- The setcookie () function returning True does not indicate that the Web browser has
accepted the cookie. Suppose, a Web site displays country maps when a user enters a country name in the search feature of the Web site. To set a cookie that expires in 1 day, enter the following code: $mapname = $_GET['fmapname'l ; setcookie("mycookie", $mapname, timeo+86400, ".Webworldmaps.com");
/Webmap/",
In the above code snippet, fmapname is the variable that contains the country name that the user enters. The $mapname variable stores the value that the GET method retrieves from the form. The setcookie ( ) function includes:
mvcookic- Name of the Bookie time ( ) -1 86400 Time when the cookie will expire /Webmap Path where the cookie will be stored l N eb)woridlmaps.com Domain that the cookie will use
Page 53 of 274
Session 16
Working with Cookies
To create a cookie that lasts till the browser is open, enter the following code: $val $GET [ 'unaino' I ; setcookie("uname",$val); In the above code snippet, uname is the variable that contains a value. The $val variable stores the value of uname that the GET method retrieves. The setcookie ( ) function in the above code snippet sets a cookie named uname. The value of $val is assigned to the cookie, uname. PHP script can include more than one setcookie ( ) function. Multiple calls to a cookie in the same script can be made in a specific order depending on the version of PHP. In PHP 3, multiple setcookie ( ) function within the same script are called in the reverse order. For example, if a cookie is to be deleted before creating another, the set cookie statement must be stated before the delete command. In PHP 4, multiple setcookie ( ) function within the same script are called in the specified order.
variable as the cookie name. The following code displays a cookie value: echo sc(Dokiename; The above method of retrieving the cookie value is not recommended- This is because PHP will start searching all the variables present in the client system. The register_globals option must be enabled in the configuration file if we want to use this method to retrieve cookie value.
Using $HTTPCOOKIE VARS [I array - PHP uses cookie name as a variable to retrieve the
cookie value. PHP can also use an associative array called $1zTTP('O'0KIE VA.RS F 1 to retrieve the cookie value. The $HTTP_COOKIE_VARS [I is a global variable that reads a
Page 54 of 274
Sessoon 16
WO N L-0 W 1-*D'Z
APTECH
( $ cook i enanie
T h e a b o v e m e t h o d i s m o r e r e l i a b l e a n d f a s t e r t h a n r e t ri e v i n g t h e c o o k i e v a l u e t h r o u g h a variable.
Using
$--COOKIE[
] variable -
$_COOKIE['$cooki.e_name'1;
The above method of ret ri ev ing the cookie value is recommended, but it requires PHP 4.1. It is also considered the best method. It is also known to be simpler and more secured than using the $HTTP_C00KIE_VARS [ ] associative array. To retrieve a cookie value using the $IJTTP COOKIE VARS [] global variable, enter the following code snippet: <?php
$cookieval
$HTTP_COOKIE_VARS['unam4'];
<HTML> <BODY> <?rjhp if (isseu($cookieval)) echo "Welconie $cookieval "; } else echo "You need W log -in
</F301)y> </HTML> In the above -code snippet, stores the cookie value. The function checks whether the cookie is set. If the cookie is set, the echo statement will display a welcome message along with the cookie value. I f the cookie is not set, the message appears prompting the user to log in.
Page 55 of 274
Session 16
Wo"ALID-W401E
C o d k i e . :
Cookies can be deleted automatically or manually. There are two ways to delete a cookie: > Resetting the expiry time of the cookie to a time in the past Resetting a cookie by specifying the name of the cookie Deleting the cookie with the same name and a time in the past forces the Web browser to delete the cookie from the client system. To delete a cookie with a date in the past, enter the following code snippet: setcookie("$cookie i-iame", "", timeo-8000);
In the above code snippet, $cookie name refers to the name of the cookie. The value of the cookie is not specified and the time ( ) function takes in the expiration date in the past.
M
We can use a new cookie statement with the cookie name as the variable to delete a cookie. This process is called as deconstructing the variable. To delete a cookie through deconstruction, use the following syntax: setcook-ie($cookiename); For example, to delete the cookie named uname, use the following code: setcookie($uname);
16.5 Problen
,with Coo
Web sites store user-related information on the client system. Cookies are not secure and reliable because the user-related information can be accessed by anyone who has full access to the client system. The user-related information can contain sensitive information, such as credit card information, passport number, password, or an identification number. Following are some of the drawbacks of cookies: Cookies cannot contain more than a certain amount of information. The cookies work well when the size limits to 4 KB. Web sites cannot use cookies to store a large amount of data. Only a maximum of 20 cookies of a domain can be maintained.
>
Page 56 of 274
Session 16
W0. L DW*IDE
Working with Cookies A browser can maintain a maximum of 300 cookies. Older cookies that were stored earlier are deleted to accommodate the newer cookies of the different Web site. Storing large number of cookie files slows down the system. To enhance the performance of the system, users often delete temporary files that contain cookies. Web site statistics may go wrong when users delete such cookies to improve the performance. Some users disable cookies while accessing Web sites. The Web sites that depend on cookies lose information of such users. There can be multiple users using the same system visiting the same Web site. Web sites assign cookies to the system and not to the user. This can hamper the number of visitors' statistics. Cookies need to be called on each Web page. There might be instances when there is lots of information that we want to retrieve from a cookie. Retrieving larger amount of information on each page requires repetitive coding across the pages.
Session
AprECH
II
w:-0.e
L D WJ'Dle
>
Web sites use cookies to store user-specific information. Cookies are stored on the hard disk of the client system.
);> In the static Web pages, there is no user interaction. Dynamic Web pages gets information from the user and record it for further processing > Types of cookies: Persistent Non-persistent Persistent cookie is stored in the Web browser for a period specified during the time of its creation Non-persistent cookie is deleted from the Web browser as soon as the user exits the browser. Web servers and Web browsers send each other cookies in HTTP headers. Web server sends the cookie in a Set-Cookie header field. PHP provides three ways of retrieving a cookie value: Passing a variable as cookie name
0'
PHP uses the following functions to set a cookie: setcookie() setrawcookie() Two ways to delete a cookie:
Resetting the expiry time of the cookie to a time in the past Resetting the cookie by specifying the name of the cookie
lotech Limited
Session 16
(A'pr,Ecm WORLDWID
E
W k r o w g n ii h t C
>
Some of the drawbacks of cookies: Cookies cannot contain more than a certain amount of information Only a maximum of 20 cookies of a domain can be maintained A browser can maintain a maximum of 300 cookies Storing large number of cookie files slows down the system Some users disable cookies while accessing Web sites
Sesskon 16
-0 R.L.DIS.a W,
? py-Ecm
1.
a. b.
C.
d. 2.
a. b. C.
d. 3. a. b.
C.
d. 4.
d5.
The _____
a. b.
C. d.
6.
The __________________________ option must be enabled in the configuration file to pass a variable as cookie name.
a. b.
C.
d.
er)ab1e_register__g1.oba1,,
P a g e
6 0
o f
2 7 4
Objectives
At the end of this session, you will be able to:
Set a cookie Retrieve a cookie in PHP
Delete a cookie
The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully. Part I - For the first 1.5 Hours:
Cookies are incorporated in HTTP request and response headers. Setting a cookie means sending the cookie to the browser. The setcookie () function generates the cookie header field that is sent along with the rest of the header information'. Suppose a Web site accepts username and password to login before they can shop online. The Web site saves the user information in a cookie- The subsequent Web pages retrieve the user details from the cookie. To create a form that accepts the username and password: 1. 2. Open the gedit text editor. Enter the following code:
<HTML> <HEAD> <TITLE> Login Page </TITLE> </HEAD> <BODY> <H4> Please enter your details </H4> <FORM ACTION="validate.php" METHOD="GET"> <TABLE> <TR> <TD>Login name</TD>
Page 61 of 274
14,0F,,EC,f,F
Session 17
W L!WW-"1;0:* 0R
Working with Cookies ~T'><I14PUT TYPE="text" NAME="logname"></TD> </TR> TR> <TD>Password</TD> <TD><INPUT TYPE="password" NAME="pass"></TD>. </TR>. </-TABLE> <INPUT TYPE="submit" VALUE="LOGIN"> <FORM> </BODY> </HTML>
Save. the file ,as InformatioriAtmi under the,Jv r/ a , . To validate the information that the user enters in the form:
/ 4.~mi A rye c t o . . ir
W,
[: logname %
~t~Mk_
Enter the following code to set a cookie for logname that does not expire for a
week: setcookie("logname",$vall)
The above code snippet sets a cookie named logname that expires as soon as the user closes the browser. The value that gets stored in the $val variable is assigned
to the cookie. Enter the following code to validate whether the Login Name and Password fields are left blank: if ($vali==) echo "Please enter the name!"; echo "<HTML>',; echo "<H7_AD>"; echo "<TITLE> Validate< /,1,i-.TLE>"; Page 212 of 274 'v C,, 2004 Aptuc,;, Llirlted
_;.1, DUD
Et2_17TECif
Session 17
LOWIDE
Header("Location:. homepage.php");
The above code snippet uses the ,leader that is the home page of the Web site To create the home page of the Web site:
1.
Enter the following code to retrieve the login name from the cookie and store it in the variable:
<?php
//Store the value of the cookie logname $1oc-icoo'kie $HTTP COOKTE _VARS['logname'];
L
2.
Enter the following code to display the various items available for shopping: echo "<HTML>11 ; echo "<HEAD>";
V 1 .0 @ 2 004 Ap te c h Li mite d
Page 63 of 274
Session 17
WOULOW1,02 AprIC-CH
//Display the value of the cookie 16 olkie, echo "Welcome $logcookie echo '<BR><A HREF='logout.php'>Logout</A>";. echo "<CENTER>";
. echo "<TR..ALIGN='center'.>"; echo "<TD><A HREF=Iaccess.php'>Accessories</A></TD>"; echo "</TR>"; echo "<TR ALIGN='center'>"; echo "<TD><A HREF='perf.php'>Perfumes</A></TD>"; echo "</TR>"; echo "<TR AL!GN='centcr'>"; echo "<TD> <A HREF='apparel.php'>Apparel</A></TD>"; echo "</TR>"; echo "</TABLE>";
echo "</CENTER>"; echo "</BODY>", echo "</HTML>fl The above code displays the cookie value stored in the variable, $logcookie. It also displays items such as, Confectionery, Flowers, Accessories, Perfumes, and Apparel on the Web page.
Page 64 of 274
Session 17
APrecm
WORLDWIDE
<?php $logcookie
:
$HTTP_C00KIE_VARS['logname'1;
//Deletes .,.logname cookie setcookie("logname"); //Redirects sers. to the main. Information.ht-n page for login Header("Location: Inf6rmation.-Mm");
Widdigs"
(V
. Q
j-
77
Forward
Reload Stop
,4 http-alh.st/inform
/A.
jp -s Search] Print
Bookmarks
<~_,7 1--Done
Figure 17.1 : Login Page 9. Click the LOGIN button. The Validate page appears, as shown in Figure 17.2.
APTECH
Session 17
Working with Cookies
I..".:
i,.File
Edit View
Window
Help
i21! x
1
;!,114orne
5
,
Back
h,tp:j/loi:alhost/homepaq
F o r w a r d
E, Search] ~O
C-4
Print i
UA. C4 -,?, 93 G9
Done
OGIN
Back
3 Ho me
F.)nvxJ
Reload Stop
http://1oi:alhostjhomepagf
I .. ......... ....
Print Training
Con1*1.Ci:01)er%,
L.,s.::::sories
Perl'unu-,
Apparel
4 z
GE2
Done
............ -
........... -
d n i g m o f I h t l a V : 2 . 7 1 e r u F
n h J e i l o c O v N M , ~ 0 I
X L M
I
1 . 0 (c ,
0 1 D L R O W
2004 W tH ih S bP
Aptech Li it d
APYIIEC
Session 1
WORLDWIDE
1. Open a new file. in the text editor. 2. Enter the following code to display the various items for the Confectionery category:.
$HTTPCOOKIEVARS['logname'
echo "<H3> Shopper's Paradise </H3>"; echo "<H5> Shop till you drop!!! <H5>"; echo "<HR>"; echo "<BR>"; echo "<TABLE BORDER-,1,>"; echo "<TR ALTGN='center'>"; echo "<TI-I>Code</TfI>"; echo "<TH>Name</TH>"; echo "<TH>Price</TH>"; echo "</TR>"; echo echo echo echo echo "<TR ALIGN='center'>"; "<TD>C001</TD>"; "<TD><A HREF= '' >Choco Delight</A></TD>"; "<TD>$40</TD>I "</TR>";
echo fi<TR ALIGN='ccnter'>"; echo "<TD>C002</TD>"; echo TD><A HREF= >Van i 1!a Crush< /A>< /'I'D>" echo " .-TD>$'110</TD>"; echo < /TR > echo "<./TABLE->";
V 1.0
Page 67 of 274
Session 17
Working with Cookies
echo "</CENTER>";
</BODY>
</HTML>
r
W111 im-Al FI I I
Coo :'Bookmarks
Reload s w a r d '
I o ol s Wndow- LW 4 - '
/Axo
Back'
Ito P
dhost/conf.pl vi
&.S,.-, h
. P r i n t .1
Shopper's Paradise
Shop till you drop!!!
C . d 7 cF N a m e
..........
;Prrcel
KtqiChoco-Dcli,zhd $4010002.1
42
tZ
nn~
G9 I Done
Page 68 of 274
Session 17
rAJ:FrEcff
WORLDWIDE
Product Category
Flowers
Product Code
F004 F010 F011
Name
Tulip Bouquet Red Rose Lily Diamond Bracelet Diamond Ring Diamond Anklet Charlie Maui Rain Night Mist Black Suit Wrinkle-free Suit Wrinkle-free shirt
Price
$75 $10 $8 $950 $800 $500 $180 $90 $80 $480 $190 $180
Accessories
Perfumes
Apparel
1 . 0
O K
2 0 0 4
A p t e c h
L i m i t e d
Session 17
CilP7'ECH
OR L DW I WE
JRY IT YOURSELF
Part II - For the next half an hour:
Full name > Address Email Address Credit Card Number Number 1. Create a cookie that stores all the above-mentioned user information. T elep hone
S h o p p e ' r s P a r a d i s e i s a s h o p p i n g c o m p a n y t h a t d e a ln s is e l i n g g o o d s o n l i n e . T h e W e b i s t e s o e fi s r t e m s , s u c h a s C o n f e c i t o n e r y , F l o w e s r , A
Page 70 of 274
Objectives
At the end of this session, you will be able to: Define a session
Work with the session Start the session Register the session End the session Work with the php.ini file
kliftodtioi'op
Cookies provide us with the functionality of storing the temporary user information. Cookies store information in the remote locations. One of the disadvantages of cookies is that it stores information on the local computer of the user. Sessions in PHP offers the same functionality of storing the user information. The only difference is that sessions enable PHP to store user information on the Web server. In this session, we will learn about sessions and session variables. We will also learn how to register and work with PHP session IDs. In addition, we will learn about the php.ini file.
18.1 Sessions.:"-..
Web browsers and Web servers have a stateless interaction. HTTP. is a stateless protocol that enables the Web browsers to communicate with the Web servers. This protocol has no methods or functions to maintain the state of a'particular user. Even the Web server is not able to distinguish user specific data. It does not recognize the user sessions. Users can browse and search for information using the hyperlinks despite of HTTP being stateless. Figure 18.1 shows the interaction between the Web browser and the Web server. Request from Browser f Response from Server
Figure 18.1 : Interaction between the Web Browser and the Web Server
V 1.0 (c)
Page 71 of 274
In the above code snippet, the variable $name stores the value that the script retrieves from the form that a user fills. This process of transferring user information is unnecessary and time consuming, especially for a large Web site. Figure 18.2 shows the above code has to be used across all the Web pages of the Web site. Page 1
$na.nc S CIEF[rlalnel;
Page 2
Page 3 0.
$name =
$--GET[name]
r-/
r-11
Figure 18.2 : Traditional Transfer of User Information The above figure shows the transfer of user information from one page to another. Imagine having to store and retrieve 20 more user information across 10 different pages. Due to this disadvantage of using the GET and POST methods, Web developers prefer using cookies. Figure 18.n shows how the Web server assigns cookies to the browser.
Page 72 of 274
rl Figure 18.3: Assignment of Cookies to the Web Browser Cookies enable us to store data into a variable and access it across all the pages of the Web site. Cookies are prone to security risks because the user information is saved at the client end. The risks involved are greater when users access Web sites from a public computer or a shared computer. Anyone who works on the computer can misuse the information. For example, a user purchases an item from a Web site from a shared computer. While placing the order, the user enters all his personal information, such as name, age, address, credit card information. All these personal information are stored in the cookies on the shared computer. There are chances that another user on the shared computer misuses the information using cookies. There are some other disadvantages of using cookies: Deletion of cookies Users can easily delete cookies from the client system. We can access a list of cookies from the systems temporary file saving location. Users often delete the temporary internet files to improve the performance of the system. Web sites allot a new cookie to the user without a cookie. This proves disadvantageous to the Web sites who keep a count of the visitors who return to their Web sites. Multiple cookies to the same user - Cookies enable Web sites identify the users according to the computers they use. Web sites aliot a different cookie to the same person every time the user accesses the Web site from different computers. The statistics of the Web site records new user entry of the same person using different computer. In addition, a user has to set all the preferences again on different computers to visit the same Web site. Size of the cookie - Cookies adds on to the page size. So more the information stored in the cookie, larger is the page size. This results to lower performance because users experience slow browsing of the Web site. Cookies disabled - Web sites store cookies on the hard disk of the client. This reduces the performance of computers with the low memory space. To improve the performance of such computers, users disable cookies. This makes the process of assigning cookies pointless.
V 1.0 (c)
Page 73 of 274
Session 18
W O'R L 0 WIVIE
Session Management in PHP Sessions play an important role in such situations. The security of the information increases on the Web server because unauthorized users cannot access the information. Sessions eliminate the chance of deletion and new cookies assigned to the same user. The size of cookie also doesn't affect the performance of the Web site. Both the Web server and Web browser benefit because statistical information in the server database is accurate. The user information is not lost from the server database. Table 18.1 shows the difference between cookies and sessions: Cookies Stores user information on the client system (Web Browser) Available even after the user exits the Web browser Users can disable cookies Have size limits Sessions Stores user information on the Web server Destroyed when the user exits the Web browser Users cannot disable sessions Do not have size limits
i
i
Cookies disabled - Web server allots the session ID to the browser using the Uniform Resource Locator (URL). URL transfers user information from the browser to the.server. PHP stores session variables in a file. PHP names the file based on the session ID. The scripts access the required user information by retrieving it through the URL. While using a session, PHP stores all the user information in a file on the Web server. The file includes session ID that is related the user's session variable. Each session ID identifies a different user and relates to a file that belongs to that user. Session ID is referred to as a key that links user and user data. PHP destroys the session file once the user exits the Web site.
Session
AprIECH WORLDWSOE
Session Management in PHP
O
1<
)01
PHP works with session in the following sequence: 1. 2. 3. User accesses the session-enabled Web site Web site checks the identity of the user whether the user is a new visitor or an ongoing session user If the user is a new visitor, the Web site allocates a unique session ID to the user. We sites save the cookie containing the session ID on the Web browser. PHP engine creates a file that stores the session-related variables on the Web server. The Web browser records the cookie that holds the session ID. The browser uses the same cookie to retrieve session ID and record all the session-related information. When the user exits from the Web site, the session file is destroyed from the Web server.
4. 5.
-4'Lif6d cle- -the, Session- Y, Based on the communication between the Web browser and the Web server, there are three stages in the life cycle of a session. They are:
V 1.0
Cc,
Aptech Limited
Starting the session Registering the session variable Ending the session
Session 18
A session starts when a user logs on to the Web site. In PHP, the sessionstart ( ) function enables to start a session- The process of starting a session is also called as initializing a session. PHP creates a session file on the Web server when a new session starts. The session file is created in the /tmp directory. PHP names this file on the unique session identifier value that the PHP engine generates. The session identifier is also known as the session ID. The session ID is a hexadecimal string of 32 digits. The file naming convention for the session file is:
sess_<32_digit_hexadecimal_value>
The session file name always precedes with less_ and is followed by a random 32 digit hexadecimal value. For example, Bessdenkhu7869jhnkh789jas543hk87p5u3 is a session file name containing session ID as denkhu7869jhnkh789jas543hk87p5u3. The Web server passes the session ID as a response to the browser. The Set-Cookie header field is sent along with the session ID. The response sets up a session cookie in the browser with the name PHPSESSID and the value of the identifier. PHP scripts access the value of the session ID from the $HTTP_COOKIE_VARS associative array and the $PHPSESSIID variable. The session--start ( ) function must be specified on the top of every Web page or before the start of the actual coding. The session star.( ) function always returns True. When the session starts, PHP checks whether or not the session is a valid session. If session is valid and existing, it activates the frozen variables of the session. If session is invalid or non existing, it creates a session ID for the new session. The scripts can use the session variables only when the variables are registered with the session library. The syntax for session start( ) function is:
session starto;
While using cookie-based sessions, we must call sessionstart () before anything is send to the browser as an output. For example, to start a session enter the following code in the text editor:
P a g e
Session 18
O W I'D E
Er-Ecw
ethic,
"The Sessior) i d i s
sessionid
V
File Edit View Go Bookmarks Tools Window Help Back Forwaal hUp:[/localhostisess Reload Stop ..... ......... .... ...... ... .. ... . .......
.............. ...................
!Home ':;Bookmarks _e Red Hat Network t: jSupport ;Shop ;_j'Products CjTraininq echo "Wc1conic to slloppcn Paradise": Wal-ning: Cannot send session Cache 111111(cf. - headers already scent (output started at in on line 4 The session id is 324219,,0805 1 fiOcfd7 ll1)09c8',6',07',c
No
Fil
Edit Vi
rA P Tr CH Session 18
11!!~ L-D'W-2:tr-F
-2 Registering the-S
ession Variable
Variables in a session file contain user specific information. To work with the sessions across all the Web pages, session variables need to be registered with the session library. Session library enables creation, serialization, and storage of session data. We can use three methods to set a session variable. They are: $-SESSION( I - Recommended for PHP 4.1.0 $HTTP-SESSION. VARS - Recommended for PHP 4.0.6 or less session register () Not recommended as it has been deprecated
-
Sessions variables can be of any data type such as integer, string, Boolean, or object. PHP stores the session variables in a session file by serializing the values. PHP automatically handles the process of serializing the session variables.
sd
For example, to register the value of the session variable, enter the following code in the text editor: <?php s e s s L o n - s t a r t o ; $H-,-,P SESSION VARS['mvname']= "Jessica";
. -
<HT1,dL> <HEAD> <TITLE> Session </TITLE></HEAD> <BODY>F <A HRE page. -hp"> Homepage of MyPage. corn <'A> </130DY> < / HTM 1-1> Save the file as session.php. To display the value of the session variable, enter the following code: < ? IDI-ID $myname $HT'rP-SESS-FON--,..,7, RS['ir.yna,-Qe']-
< YPM L
< .i ~
HEAD> <TITLE> Eoinepl,ge <,/'_7 1VLE>-:_ /HEAD> <BODY> Welcome < -- o l cn .: aivame > l..o M Page.com P < BODY> < HTM L >
Page 228 of 274 V 1.0 Cm 2004 Aptech Limited
EePTECIF
Session 18
ORLDWID8
We can alter the lifetime of a session...cookie by modifying ing:theAefault, value. in; the-!PH R.
The syntax of sessiondestroy () function is: session destroy(); The Web server performs several steps to determine that the session has ended. PHP uses the following configuration directives when a session ends:
gc maxlifetimeo Enables PHP to determine the time to wait before ending a session after the user exits the browser. This process of cleaning up the old session is called as garbage collection. gc_probability() Enables PHP to determine with what probability the garbage collection routine must be invoked. If the value of this directive is set to 100%, then the process of garbage collection is performed on every request that the Web browser makes. We will use the my-page. phu file to destroy the session. To destroy a session, enter the following
code in the mypage.pi-p file: < ?ph,,) $myname = $i-:'rTP_SFSSIONVARS['myna-ne']; sessiondestorv();
To see the effect of -iession dosLroyo function, open the Sessions page in the Mozilla Web browser. Click on the Homepage ollhyperlink. Note that the message Welcome -1 . ~iypage Jessica to MyPage.com still appears. The value of the session, mvname still appears because the value of the session variable can be accessed on the current page where sessiondestroy function is used.
P a g e 2 2 9 o f 2 7 4
Session 18
WOR LOWIDIE
Session Management in PHP To destroy the variable completely from the current page, add the following code before the session_des troy() function: sessionunseLo; The session_unset ( function unregisters a session variable.
'x
Edit Vi e w Te rm i nal Go Help
J:t
WARNING ;
This is the default settings file for new PHP installaiions. 1 By default, 1 14P installs itself with a configuration suitable for development purposes, and *NOT' for production purposes. For several y i securit -oriented considerations that should be taken before going onl ne w i t h y o u r s i t e , p l e a s e c o n s u l t p h p . i n i - r e c o m m e n d e d and lit tp: //php. net/manual/en/security. phi).
; About this file : lhi file controls many aspects of PHP's behavior. In order for PHP to read i t , i t m u t ,i t b c - W a d e d ' p h p . i n i ' . P H P l o o k s f u r i t i n t h e c u r r e n t w o r k i n g d i r , c l o r % , i n t h o p a t h d e s i g n a,t e d b y t h e e n v i r o n m e n t v a r i a b l e P H P R C . a n d i n t h e p a t h t h a t w a s d e f i n e d i t . c o m p i l e t i m e ( i n t h a t o r d e r ) . U n d e r W in d ow s, t he path is the Windows directory. 'file p a t h i n w h i c h t h e p h p . i n i f i l e i s l o o k e d f o r c a n b e o v e r r i d d e n u s i n g the -c argument in command line mode.
s
.. .......
23,1
Top
64-PTEC'H
Sessuon 18
ORLDWIVE
~
S e s s io n M an a g e me n t i n P HP
T h e p h p . i n i f i l e c o n t a i n s d i r e c t i v e l i s t e d i n t h e d i r e c t i v e = va l ue f o r m a t . W e c a n u s e a semicolon to add a comment to the file. PHP ignores lines that begin with semicolon or a singl e whi t e sp a ce. W e c an edit th e php .i ni fi l e to cu sto mi ze the se tti ngs. Table 18.2 lists the categories containing various options available in the php.ini file.
Table 18.2 : Categories of the PHP Configuration File Categories Options that
Session 18
WO R LD'W I 81E
S e s s io n M a n ag e me n t in P HP Several options can modify the functionality of the PHP session. Session category of the php.ini file includes options, such as: session. save hand1er Specifies how PHP stores and retrieves session variable. We can use either of the following values for this option: files: Indicates the use of the session files. This is the default value. mm: Stores and retrieves data from a shared memory user: Stores and retrieves variables with the custom defined handlers session. savepath Specifies the name of the directory where the session files will be stored. By default, the session files are saved in the /tmp directory. session.use cookies Indicates whether PHP must send session ID to the Web browser through a cookie. By default, the cookie stores the session ID. The value to enable cookies to store a session ID is 1. session. useonlycookies Indicates whether the modules can use only cookies for storing session IDs. By default, this option is disabled. session. cookie 1 if etime Specifies the lifetime of the cookie. The value is specified in seconds. By default, the lifetime of a cookie is set to 0 which means the cookie is destroyed once the browser is closed. session . name Manages the cookie name and form attributes such as GET and POST that holds the session ID. By default, the value of this option is PHPSFSSID. session .auto '-- start Enables sessions to automatically initialize if the session ID is not found in the browser request. It is recommended to disable auto start feature because it increases overheads if not all the scripts require the session ID. Specifies whether the cookies must be sent over secured connections. By default, the cookies are not sent through secured connections. We can also change the other settings in the php.ini file, such as: register alobals Controls the functioning of server, forms, and environment variables. When we enable this option, we can directly access the forms, server, and environment variables by their names. If this option is disabled, we can retrieve variables using the GET or POST methods as follows:
' $ vari a ) . - ) 1 e n a m e ' j $ GET[ 'svariabienaiiie' I $_POST[
or
Sessaon 18
If the register_globals is enabled, we can directly access the variable using the variao name as follows:
$sroreValue = $var-Jable--name;
In the above code snippet, variablename is the name of the variable that holds sessio data of another Web page. The variable storeValue stores the information included in th
variable name. upload_tmp---dir. Sets the location of the temporary file that is uploaded with the HTM
form. Any user can access the uploaded files in the default location of the Web server. W can create a directory and specify the path for storing the uploaded files in the php.ini HE
log errorsand error log Enables PHP to display logs errors. The error--c-variable stores the path of the directory where the logs get stored. It is recommended log errorsvariable, when the displayerrors and enable the displaystartupe--r-ror! variables are disabled.
Session 18
WORLDWIDE
APEUCH
Cookies provide us with the functionality of storing temporary user information. Cookies store information on local computer of the user. Sessions enable PHP store user information on the Web server. HTTP is considered a stateless protocol that enables Web browsers communicate with the Web servers. Web server is not able to distinguish a user specific data. Web sites that require complex user interaction and cannot depend only on HTTP and Web servers. Sessions enable Web sites store user requests and information on the Web. Session refers to the time the Web user accesses information on a particular Web site. Session management involves managing data related to a particular user in a specific session. Session life refers to the total time a user spends on a Web site before the user closes the Web site windowThe scripts gain access to the session ID depending on two situations, such as: Web user enables cookies Web user disables cookies
I
There are three stages in the life cycle of a session, such as: Starting a session Registering a session variable Ending a session
ituo
Session 18
(AprEcAr LOWIDE
Session Management in PHP
The php.ini file contains options that are grouped under categories, such a s :
V 1 . 0 O c , 2 0 0 4
Aptech
L i m i t e d
Pa
Language Options Safe Mode Font Colors Misc Resource Limits Error hanling and logging Data Handling Magic Quotes Paths and Directories File Uploads Session
W 0 R L:D W PD :E
Session
Session Management in PHP
C K YOU 8 PROGRESS
1. The __________________ option indicates whether or not the modules will use only cookies for storing session IDs. a. b.
C.
d.
2. The _________________ function enables PHP determine the time to wait before ending a session after the user closes the browser. a. b.
C.
d.
3. PHP uses the ______________________ function to remove the session variable from a session. a. b.
C.
d.
The _________________ option enables session to automatically initialize if the session ID is not found in the browser request. a. b.
C.
d.
Sessi
n 18
WORLDWIDE
(AiPTECiir
S e s s i o n M an a g e me n t i n P HP
5.
The ____________________ specifies whether or not the cookies should be secured connections. a. b.
C.
d. 6.
Obi ectives
At the end of this session, you will be able to:
Introduction
E-mail is a fastest way of communicating with people across the world. It takes only few minutes to send and receive messages as compared to the usual hand written letters. PHP provides the facility to send e-mail. In this session, we will learn how to send e-mail within PHP. We will also learn how to attach files with the e-mails.
19.. 1 SendingE-mail
In PHP; we can send an e-mail using the mail () function. To work with the mail () function, we need to specify the location of the current local mail server in the php.ini configuration file. The php.ini file is present in the /etc/php. ini location of the Linux operating system. Figure 19.1shows the contents of the php.ini configuration file. x
File Fdit View Search Tools Documents Help
x-
[ n a i l f u nc t io n ] ; For Win32 only. SMTP -- localhost ; For Win32 only. sendinailfrom = ineZlocalhost. coin For Unix only. You may supply arguments as well (default: sendinail -t -1 11 ). sendmail_path = /usr/sbin/seiidinail -t 4
i
Lr. __01. 16
1N5
Figure 19.1 : php.ini Configuration File The above figure shows the mail function section in the php.ini configuration file.
Web Scripting with PHP V 1.0 ( q ) 2004 Aptech Limited Page 239 of 274
Sess~un 19
L1D W 1.0-E
[additi.onalheaders])
to Specifies the e-mail address of the recipient subject Specifies the subject for the e-mail message Specifies the message that is to be written in the e-mail. The body of the e-mail is
the message
If the e-mail reaches to the recipient address, the control is passed to the statement following the mail () function. Otherwise, PHP displays the error message. For example, to send an e-mail using the mail 0 function:
<HTML> <BODY> <?php $to"john@bluemountain-com"; $from "tom@bluemountain.com"; $subject "Ilm example"; $body = "This is an example for show i ng the usage of the mail() function."; $send = mail($to, $subject, $body, $from); if($send) echo "Mail sent to $to 'address! else echo "Mail could not be sent to $to address!!!";
i ! 11;
</BODy> </IITML>
The mail () function is also used for sending mails to more than one recipient. A comma symbol is used for separating the e-mail addresses of the recipients.
V 1.0 Cc,~ 2004 Aptech Limited Page 240 of 274 W e b S c r i p t i n g w i t h PHP (,)
Session 19
rAJi:Pr,ECff WO R L D W I D E
Handling E-mail with PHP
<?php $to = "john@bluemountain.com, samson@bluemountain.com, jenny@bluemountad.n.com"; $from = "tom@bluemountain.com"; for($i=0;$i<count($to);$i++) { sto[sil trim(sto(sil); $subject = "An example"; $body = "This is an example for showing the usage of the mail() function."; $send = mail($to, $subject, $body, $from); if($send) { echo "Mail was sent to all the addresses!!!"; }}
</BODY> </,IITML>
In the above code, the mail ( ) function is used to send an e-mail. If there is any blank space placed in between two recipient's e-mail address, the mail () function removes it. A comma symbol is used for separating recipient addresses. In this code, the for statement is used for
reading the number of recipient addresses. Suppose we have stored all the e-mail addresses of the recipients in the text file. PHP enables us to read the e- mail addresses of the recipients from the text file and send an e-mail to them. For example, to send e-mail to multiple recipients whose addresses are stored in the multimail.txt file:
<HTML> <BODY> <-php
$ mu i ti /va /mul. Lima i I . Lxt o_ma i i f i 10 (5AT-1 -1 t i ) ; $from =-- " toi0bli-iemountain. com";
$ -C. 1
Eifir2TECifOR
Session 19
Ha
O g0E W ro 11
for ($ i = 0; $ i<C0U3'1t ($ tO_Ma 11) ; $ -i A- 4-) $to_ma_il [ $ i 1 = t r i m ( $ t o _ m a i l [ $ i 1 ) ; $to = implode(",",$to_mail); $subject = "A-n example"; $body = "This is an example for the mail() function."; mail($to, $subject, $body, $from); echo "Mail was sent to all the addresses!!!"; } </BODY> </HTML> In the above code, we have used functions such as the file () , trim () , and implode (). The file () function reads the e-mail addresses from the multimail.txt file. It stores all the e-mail addresses in an array. The trim() function removes the blank spaces inserted between the email addresses. The implode () function joins all the e-mail addresses in the array by separating each one of them with a comma.
APYIECH
Session 19
44
OLDWIDE R
Handling E-mail with PHP Sheader.= "MIME-VERSION: 1-0\r\n"; $header.="Content-type: multipart/mixed"; $header.= "bounday,y=.\"".$mimeboundary."\""; $message.="This is an example for mail attachment.",$message.="\r\n\r\n"; $message.="".$mimeboundary."\r\n"; $message.="Content-type:text/plain;charset=\"iso-88591\ " \r\n" ;
V 1.0 ~P 2004 Aptech Limited
$inessage.="".$mimeboundary."\r\n"; $message.="Content-Disposition:attachment;\r\n"; $message.="name=\"filename extn\"\r\n"; $message.="\r\n\r\n"; $message.=$file; $message.="\r\n\r\n"; $message.="".$mimeboundary."\r\n"; $ c o n t e n t = " < P > . $ C o n t e n t < / P > " ; $content=str_replace(chr(10i,"<P></P>",$content); $mail_send = mail($to, $subject, $body, $message, $header); if($mail_send) f echo "<BR><BR>Mail sent to $to address!!!"; } else echo "<BR><BR>Mail could not be sent Lo $to address!!!";
</BODY> < /17 T- L - I1 > In the above code, a boundary is created between the actual e-mail and the attachments. The boundary is created using the uniq d O function. The uniqid O function assigns a unique identifier to the original mail. The value of this function is assigned to the $mail_boundary variable. The content-type header indicates the type of the file that will be attached with the e-mail. The fo d en () function opens the file that is attached with the e-mail in the read mode. The f read() function reads the contents of the opened file. The base64 encode and chunk_split are the two built-in PHP functions. The ._)c1,.-.,c64_encode function is used for encoding the specified string. The function is used for splitting the data into smaller chunks. These two functions can be used in the codes for reading the file content. The basc64_encode() and c1-unk_,sp*1.it() functions are optional.
AprIECM
Session 19
WORLDWIDE
)>
The mail () function is the inbuilt function of PHP that is used for sending mails By default the path for the local mail server is chosen while installing Linux in the machine If there is any blank space placed in between two recipient's e-mail addresses, the trim () function removes it The implode () function is used for joining all the addresses present in the array with a comma operator An attachment can also be sent with an e-mail by setting up the header of the mail function A boundary is created in between the actual e-mail and the attachment with the help of
the
() function
The uniqid () function assigns a unique identifier to the original mail We need to specify the type of messages that will be attached to the e-mail with the help of the content-type header
The chunk split ( ) function is used for separating the data into smaller portions The base64 encode () function is used for accepting the data in the form of a string and returns the data in the original form to the user
V 1 . 0 Cc)
(A,PY-,FC,ff
Session 19
7" LOWIDE
C .
d.
The
C.
d.
3.
The trimo function removes ______________ from the recipient address. a. b. C. d. 4. The
a. b.
C .
d.
ascii character comma operator blank space wide space function joins all the e-mail addresses in the array.
file() trim -mail implode
5.
b.
C .
uniqid trim ()
d.
i m pl od e .... ..... ..
Session 19
WORLDWI-DE
AprECH
6,
The
a.
function opens the attached file in read mode. f read() implode() uniqid fopen()
bC.
d.
7.
chunksplit(
fread()
base64_encode()
fopen()
Objectives
At the end of this session, you will be able to:
2. Enter the following code to create a form that accepts the recipient address, subject, and e-mail message:
<HTML> <BODY> <FORM METHOD "GET" ACTION "multiusers.php"> To: <INPUT TYPE "TEXT" NAME "to" SIZE = 60><BR><BR> From: <INPUT TYPE "TEXT" NAME "from" VALUE "jack@bluemountain.com" SIZE=60> <BR><BR> Cc : <INPUT TYPE = "TEXT" NAME "cc" SIZE 60><BR><BR> Bcc : <INPUT TYPE = "TEXT" NAME = "bcc" SIZE 60><BR><BR>
Subject:
<INPUT TYPE = "TEXT" NAME = "subjec t " SIZE = 60> <BR><BR> "6" COLD TS <TEXTAREA NAME = "mailbody" ROWS "50"></TEX'PAREA>
Web Scripting with PHP V 1 . 0 ` 2004 Aptech Limited Page 247 of 274
Session 20
WORLDWIDE
APMCCA?
Enter the following code to accept the recipient address, , - subject, and
,
message:
Al
N2
0"O'
$body = $_GET['mail body']; $confirm = mai-l($mail_to,$mailsubject,$bodv,$mailheader); if($confirm) echo "To: $mail_to  "; echo "From: $mail_from <BR><BR>"; echo "Cc: $mailcc  "; echo "Bcc: $mail_bcc <BR><BR>"; echo $body; echo fl<BR><BR>Mail Sent to all the e 1 echo "<BR><BR>Mail could not be sent!!!" addresses!!!";
Session 20
(APywcmWoa
LOWIDE
6. 7. 8.
Save the file as multiusers.php under the /var/ww4/htTn1 directory. Open the Mozilla Web browser. Type htt p ://localhost/multiusers.html ' - in the-Address bar and press the Enter key. The E-mail form appears, as shown in Figure 20.1.
Figure 20.1 : E-mail Form 10. Enter john@mail.com, jenny@hotmail.com, and samson@bluemountain.com as the recipient addresses. Enter Birthday Reminder as the subject. Enter the message, Wish you many many happy returns of the day H!, in the body. Click the SEND button. The output appears, as shown in Figure 20.2.
ptec
ted
age
9 o
Session 20 V..:
W 0A L D WIME
APFECAV
File Edit .... ........ Bookmarks Tools Window Help View Go . . .......... Back Forward Home
1
To :john @ mail.comjcnn) @ hotinail.coiii.saiii-soiiC-lbluetiiouiitaiii.coiii From : jack (F-blueniountain.com Cc: l3cc Subject : Birthday Reminder Wish you many many happy returns of the day '!I
Lm t , Q "A*
ICI v
To: <INPUT TYPE "TEXT" NAME <BR><BR> From: <INPUT TYPE "TEXT" N11ME "jack@bluemounta-in-com" > Cc : <INPUT TYPE = "TEXT" NAME :
"to" SIZE=60>
Session 20
WO R L D'WO-D E
APBCj K,
<INPUT TYPE
$fp. fopeni($fi1'e""j'-,,#-k $content fread($fp,filesize($file)); fclose($fp); $to $GET['$to']; $ fr o m $GET['from']; $subject = $GET['subject'],$body = $GET['body']; $mirrieboundary = uniaid(""); $header.= $from; $header.= $to; $header.= $header.= $header.= $message. $message $message $message
1\"',\r\n";
$-m,e s s a g (-. ="". $iTtiiv.e_boundarv. Co n : ten t - Di snos i t i on: aa t t a c h m e n t ; $message name = \ . r., -, 1._-lename.extn\"\r\n'; $message $message - = " \ r \ n \ r \ n " ; .,f ile; $ --n C? s S a g C,
Web Scripting with PHP V
1.0
S e s s i
n 20
W a-lit-Va W U.D*E
A PrEcAlff
8. Type http://i66alhost/mail.html in ..the address bar and press the Enter key.,-., The form appears, as shown in Figure 20.3.
rF":-,-'.---,44'..t77:3r.,../:, e Edit View .0 Rookmarks Tools window Help 1 I!tjMorne : %fBookmarks "Red Hat Network !:ASupport rjShop CalProducts ATralrOng To:
SEND i
Session 20
Handling E-mail with PH 9. Enter samson@bluemountain.com as the recipient address.
10. Enter An Urgent Opening as the subject. 11. Enter the message, Please check the job d&ahsAn -..the /var/ww/htm3-/Job.t-Xt file.
,
12. Click the SEND button. The output appears,.as-.,,shown in,.,Figure ;Q.4.
Mozilla
File Edit View Go Bookmarks Tools window Help --- --------Back Home Forward Not Reload Stop
)n
0
i
Done
Page 253 of 2
Session 20
WO R CD W I D'E
A P FECH
If
Objeedves
At the end of this session, you will be able to:
Explain the OOP concepts Explain inheritances Create classes Create constructors Create and use objects
Introductio
In object-oriented programming, programs are viewed as a collection of distinct objects. These objects are self-contained collection of data structures and functions and interact with each other. C++ and Java are the most common examples of object-oriented programming languages. In this session, we will learn how to create a class in PHP and how to derive a new class from a base class. In addition, we will also learn to create a constructor for a class.
Session 21
(APFECH
WORIOW W 1.0 E
OOP Concepts Polymorphism - Process of using a single function or an operator in different ways. The behavior of that function will depend on the type of the data used in it Inheritance - Process of creating a new class from the existing class. The new class is called the derived class while the existing class from which the new class is derived is called the base class iL21-.2
Inheritance
The process in which objects of one class acquires the properties of objects of another class is called inheritance. For example, the Lancer car is a part of the class Car, which is again a part of the class Vehicles. Inheritance means creating a new class with the help of a base class. A base class is also known as the parent class and a derived class is also known as the child class. A class is an object that contains variables and functions of different data types. The properties such as variables, functions, and methods of the base class are transferred to the newly derived class. We use the extends keyword for inheriting a new class from the base class. A derived class can also have its own variables and functions. The different types of inheritances are:
I>
Single Inheritance - Contains only one base class- The derived class inherits the properties of the base class. In single inheritance, the derived class works with the derived properties of the base class along with its own properties.
Multiple Inheritance - Contains more than one base class. The derived class inherits the properties of all the base classes. A derived class in this inheritance works with the derived properties along with its own properties. Hierarchical Inheritance - Contains one base class. In hierarchical inheritance, the properties of a single base class can be used multiple times in multiple subclasses. The derived class contains its own properties. It also uses the derived properties of all the base classes. Multilevel Inheritance - Contains one base class. The base class of the derived class can be a derived class from another base class. The properties of one base class are inherited to another base class and the derived class may become a base class for another derived class. Hybrid Inheritance - Uses the combination of two or more inheritances. This inheritance is normally a combination of multiple and multilevel inheritances. In PHP, multiple inheritances is not supported.
Page 256 of 274
Web
Sess~cn 21
APFIC-ClAf
W O-R,L. 0 IMMO E
OOP Concepts
21-.3 Creating a
A class is a collection of variables and functions that operate on that data. A class can be inherited from a base class to create a new derived class. A new derived class uses all the properties of the base class including its own properties. The syntax for declaring a class is: class class nam var class-variable; function function-name{)
Where, class - Is the keyword used to declare a class class-name - Specifies the class name var - Specifies that the variable is not just an ordinary variable but a property class-variable - Specifies the variable name functon - Is the keyword used to define a function function-name Specifies the function name
The class definition is placed within the curly braces. The variables defined in the class are local to the class. A class can also use global variables. The variable inside a class is declared with the var keyword. The functions inside a class may use its own local variables or may use the class variables. For example, to create a class named OR .]Ddet.ail in PHP:
.Pl1p class a ss emodeta-il var $e7',11, i'&; var $empname; var V1-7,i' S-imodepart; -,.0 S'r)z) i:' el . d : . 1 )
-, e
~Y)
-inc
a onLer nD
V 1.0
- 1 I-
(Al"WrIEC'Ar,
Session 21
-3~-
O:RL'VW-VD-R
s t p e c n o C P O
$this->e.mpcity=c:i-ty;
We have to save this file with an extension, .inc. This is because the file that needs to be included in the .php file must have the extension, .inc. In the above example, the enLeremp () and enterdet ( ) functions are user defined. These functions are defined in the empdetail class. These two functions are used for entering data of an employee. The enteremp ( ) function enters the employee id, employee name, and city. The enterdet () function enters the employee department and the designation. The this is a pointer that points to the object. Here the class variables are the objects of the class. The filename.inc file is included in, the filename.php file with the help of the include keyword. This is done in order to create an instance for the classes those are defined in the filename.inc file. The include keyword helps in including any type of file with the main file. The syntax to include a file in the program is:
include "i-iiename.inc";
A new class can be inherited from an existing class. The new class uses the properties of the parent class along with its own properties. The syntax for inheriting a new class is:
class newcless extends class name{ va2:- classvariable; function functionmine
Where,
ne--.-,,c.1.ass Specifies the name of the derived class extends Is the keyword used to derive a new class from the base class class name Specifies the name of the class from which the new class is to be derived
Session 21
OOP Concepts For example , to de rive the net sa l a ry class from the salary c lass in PHP: <?php
class salary
r
class netsalary extends salary function net($basic,$hra,$ta,$tax) return $basic i ($hra + $ta) $tax;
Save the above file with the name, salary.inc. In the above code, the n e r s a - l a n y class is derived from the base class, salary. The net. sa - lany class inherits the properties of the s a i , a r - , ' - c l ass . T h e n c t _ s a l a r y c lass us e s the f unc tion s de f in e d in the c l ass along with its own functions. and tax functions are the user-defined functions. The hra;%*! The hra(), travel__al low function calculates HRA from the basic salary of the employee. The trave~l_a' l low( ) function calculates traveling allowance from the basic salary of the employee. The Lax ( ) function calculates function calculates the net salary of the tax from the basic salary of the employee. The net the employee. 21.4 4Creating -a sConstructor ,t,
o,
. 4
A constructor is a special function that is a member of the class. This function has the same name as that of its class name. A constructor is called in the main program by using the new operator. We use the constructor t o initialize objects of the class of which it is a member. The constructor function is invoked whenever an object of the class is created.
scripting with PHP
V 1.0 20Vi Aptech
Limited
I
TE CH Session 21
OOP Concepts When a constructor is declared, it provides a value to all the objects that are created in the class. This process is known as initialization. This allots a specific amount of memory to every object. The syntax for creating a constructor is:
class class nam var class variable; function constructor name(
specifies the
Once the constructor is defined, we can call the constructor of the class using the nev .) operator. Before we call the constructor of the class, we need to include the file that contains the class. To call the constructor of the cmpaleta-ils class:
<?
p
hp
em,_'d e
include echo
t nc derails:
< fi T3
!--ew e!-, l P
",.J--
o hi -i
"T"roy", "I.1echarlical")
Session 21
ei?PrIECII LDWIDE
OOP Concepts
The new operator creates a new object of the empdetail class. It calls the functions that are defined in the empdetail class. For example, to call a constructor from the derived class
class display extends string function displaystringo echo "This is a new class and a new function"; I
$disp $displ
In this example, the display class is inherited from the string class. As a result, the display class uses all the properties of the string class. Here, the string() function of the string class is the constructor. As the display class is inherited from the string class, therefore the display class will behave as a constructor for the string class.
21.5
An object is a self-contained entity that consists of both data and procedures to manipulate the data. We use objects in programming because an object makes the codes easier to understand and are used for more than one time. It maintains the codes in the program. An object is an instance of a class. It gives a reference to the class. An object can be manipulated as needed. The new operator to initialize the object. There can be more than one object for a single class.
6-1-PrECII
Session 21
OR L DWI WE
OOP Concepts The syntax for creating an object is: $objectname = new class name; Where, object_name Specifies the name of the object new Initializes the object class name Specifies the class name For example, to create an object for the class, usermail: <?php class usermail { var $username = "john"; var $password = "abc123"; function dispuser() echo "$username , $password";
class userdetails extends usermail var $secretquery = "favourite food"; var $answer = "chinese"; function dispdetail() echo "<BR><BR>$secretquery , $answer"; I
In the above example, the $mail object is created for the class, userdetails. The userdetails class is an extended class of the usermail class.
(A_.~VFECH
Session 21
= L D-W I D E
OOP Concepts
In object-oriented programming, we not only define the data type of the data structure but also the type of functions that can be performed on the data structure The main concepts of an OOP are objects, class, abstraction, encapsulation, polymorphism, and inheritance A polymorphism is a process of using a single function or an operator in different ways A process of joining data and objects into another object is called encapsulation
A process of creating a new class from the existing class is termed as inheritance. Inheritance of a new class is done with the help of the extends keyword In hierarchical inheritance, the properties of a single base class can be used multiple times in multiple subclasses A class is a collection of variables and functions that operate on that data. A class can be inherited from a base class to create a new derived class A constructor is a special function that has the same name as that of its class name A constructor is called in the main program by using the new operator When a constructor is declared, it provides a value to all the objects that are created in the class An object is a self-contained entity that consists of both data and procedures to manipulate the data An object is an instance of a class. It can be manipulated as needed
Sessocn 21
W 0 8.W0 1W a 0 E,
00113 Concepts
1.
The process of selecting the common features from different functions and objects is known as _____________________ a. bC.
d. 2.
The process of using a single function with its operators and variables in different ways is termed as ________________________ a. Abstraction Encapsulation Polymorphism Inheritance inheritance is a combination of multiple and multilevel inheritances, a. b.
C.
b.
C.
d. 3.
d. 4.
d. 5. a. b.
C.
d.
Ci-fprEcigt ORLDWIDE
Session 21
-1
s t p e c n o C P O
6.
An object is an ___________ of a class. a. b. C. d. entity reference instance constructor makes the codes easier to understand and can be used for more than one
A _________ inheritance contains more than one base class. a. b. C. d. multilevel multiple hybrid hierarchical
Objecflves
At the end of this session, you will be able to > Create a class Create a derived class Create a constructor Create an object of a class
The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully. Part I - For the first 1.5 Hours:
Session 22
(A'PrECH \= LDWIDE
OOP Concepts
Calculate: <BR><BR> <INPUT TYPE T1PE RADIO NAME E - "RA',Dio,, -NAME= .tLb ~ ,NU . IPT
;
Y-PE'
VALUE="DIVIS ION">Division <BR><BR>, ,INPUT TYPE "RADIO" .<INPUT TYPE -';v 0* <INPUT TYPE=AAbib, <BR><BR>" TYPE="SUBMIT"
Session 22
CP T E f f
LDWIDE
OOP Concepts
Page 269 of 274
$calculate $caiculate
(A'~jPF,FCffg
Session 22
1-
L- D W 1 0 1E
OOP Concepts elseif($n3 ) $prod $calculatel->multiply($first, $second); echo "<BR><BR>"; echo "The product of $first elseif($n4) $div = $calculatel->division($first, $secoriO.", echo "<BR><BR>"; echo "The quotient for elseif($n5) .$pine $calqulate->sinvaluP1 echo "<.BR><1q)R5'"; echo "The sine::::. value
? r !
In this example, $calculate and $calculatel are the instances of the calculator and calci classes. The functions defined in these classes are called by using the class instances with the help of the '->' sign.
WO
?e ittpx'JN~aZo
VIN . ......
Irke A, i
PIUMMIM11
nonezaaaress
i - ar.; nagpress.m.,
~ 4X
S e s s i o n
2 2
Elie Edit view go Bookmarks rods Wndow L4elp h.,:Mocalhosticalculate.htral Back Forward Reload Stop Print
# ,-- ---
T~
] 40_5earch __________
Addition
Division
Sine
SUBMIT
, v
, 0 (V " Dli*
ears ,0 ,'a" -.
ma c
Division
1 T Cli k h l
Web Scripting with PHP o e g a V 1.0 2004 Aptech Limited o a
bt
(APPLD, EW
Session 22
OOP Concepts
J~n lix
Elie
Window Help
&A_Search
CA Print
I
_4 Home 4Bookmarks
-A, LZI - / 1 90 ( 0 ~ Do ne
Session 22
fIPTECIIO
RLDWIDE
OOP Concepts
In this example, oddnum is the user-defined class. This class has a function named, oddnum. The oddnum function is the constructor of the oddnum class.
3. Save the-;file as construct.inc under the:./var/WW/"`-hOpen a new file in theVedit text editor.' odd "order iiu rn W94 e- .Teve&i% r -
The new operator is used for calling the oddnum constructor. It is assigned to a variable x. The variable x is created as an object for the oddnum class.
File Edit View Go Bookmarks Tools Dndow Help hlp-14ocalhosticonstructor.plp 11F,;_~,;;rch] Back Forward Reload stop . Print f, ,Home 13ookmarks.**---Red Hat Netwoik Asupport [;Shop (6, Products ZITralning
Displaying odd numbers in reverse order
1.
_T
i Mp.
19 17 15 13 11 9 7 5 3
Session 22
WORLDWIDE
OOP Concepts
TRY IT-YOURISSELF 1-Part II - For the next half an hour: 1. Create a class named Circle with a function that calculates the area of a circle. Derive another class from the Circle class. Create a function that calculates the circumference of i the circle in the derived class.
Abstraction Process of selecting the common features from different functions and objects Arithmetic Operators Performs mathematical calculations Array Variable that can store a list of values. Array Identifier Enables us initialize value of a specific element in an array. arsort Function Similar to rsort() function that can sort both associative and indexed arrays Assignment Operators Enables us to set the operand on the left side to the value of the expression on the right side Associative Arrays An array where the index type is string
Bitwise Operator Operates on the bits of an operand. They are similar to the logical operators- They work on smallscale binary representation of data. Boolean Data type stores one of the two values, true or false
Web Scripting with PHP V 1.0 C 2004 Aptech Limited Page i
Ef A T CI R D I E P E IO L WD
Giossary
Glossary
Break Statement Stops the iteration of the loop from the current loop execution
AP-5111h %MP
Class Contains variables and functions working with these variables. It is an object that can be inherited from a base class to a derived class. It has its own properties. Constants Identifiers that contain values that do not change as the program executes. It has a global scope of existence. Constructor Special function that is a member of the class. This function has the same name as that of its class name. Continue Statement Used for breaking the iteration of the loop from the current loop execution Cookies Enables Web site stores user information on the hard disk of client system
Database Used to store the data. A database is connected to establish the database properties to the Web sites. It is done with the help of a data source name. Database API Enables developers to write applications that are movable or easily accessible between the database products
Page ii
(APJr,EC,ff
Glossary
woRtowIae
y r a s o l G
Date and Time functions Enables us to find the date and time on the system. Decrement Operator Decrease the value of the operand by one
Else Statement Executes a block of code when the specified condition is false. It is used along with i f statement. Elseif Statement Optional clause that allows testing alternative conditions. It is executed before the else statement and is used along with if statement. Encapsulation Process of joining data and objects into another object. It hides the details of the data. Environment Variables System-defined variable. It gives information about the transactions held between the client and the server. Error handling functions Enables to define the error handling rules. Exit Statement Used to break the loop while the loop is in the execution process. ( a Floating-point Data type that stores floating-point numbers.
Glossary
E4 P E A O L WD 7 C TRD I ' E
Glossary
For Loop Executes a set of codes repetitively for a specified amount of time. In this, the counter variable is declared in the loop itself and is used for checking the specified condition. Form Provides an interface for the client and the server to interact with each other
43
GET Method Specifies the Web browser to send all the user information as part of the URL. Global Variables Retains its value throughout the lifetime of the web page.
a
Hidden Similar to the text field. The difference is that the user cannot view the hidden field and its contents. Hierarchical Inheritance
HTTP
I
HTTP is a Hyper-Text Transfer Protocol. This protocol is a network transmission protocol. HTTP protocol is used with the help of TCP/IP protocol. Hybrid Inheritance
multiple and multilevel inheritances. Ihriahn,eoeoigacsnud ut em niremenp rrsrchabeo ac bao ecnit t r o il ss i i mto n y n o I . a c b s e p i t l Uaolbac o tehn.lshnsr yli st f scc ir e oisnbTineen lam in ehi n o r ei e eacrce le i o s t hmnt s t smimi u h i t ae t af pf a e a p n ow
Page iv
(A"PirrCM
Glossary
W O R L D - W
Glossary
a
Identifiers
Names given to various elements of a program such as variables, constants, arrays, and classes in a program
If Statement Executes a block of code only when the specified condition is true
Increment Operator Increase the value of the operand by one Indexed Arrays An array where the index type is integer. Inheritance Process of creating a new class from an existing class. Integer Data type that stores numbers without decimal points. The value ranges from -2,147,483,648 to +2,147,483,647.
Local Variable Variable that is initialized and used inside a function. The lifetime of a local variable begins when the function is called and ends when the function is executed. Logical Operator Enables us to combine two or more test expression in a condition. They evaluate expressions and return a Boolean value.
Page v
Glossary
Glossary
Y.
Loop A loop is executed depending on the return value of the testing conditions by testing it- The return values are true and false.
Mathematical functions Mathematical functions operate on numerical data. Multidimensional Arrays Stores one array within another array Multiple Inheritances Contains more than one base class. The derived class inherits the properties of all the base classes.
Non-Persistent Cookie Cookies that are deleted from the Web browser as soon as the user exits the browser
Objects Used for any object reference. An object is an instance of a class. OOP A programming language model that is made up of objects and data. Objects can be manipulated as needed.
(A,pr,Ecjv
Goossary
\ WORLDWIDE
Glossary
Persistent Cookies Cookies that exist in the Web browser for a period specified at the time of its creation. PHP PHP stands for PHP - Hypertext Preprocessor. It is a scripting language used for developing dynamic Web pages. PHPEd Has an integrated development environment for PHP. This tool helps a developer in developing applications by supporting PHP scripts and its syntaxes Polymorphism Process of using a single function or an operator in different ways. The behavior of that function will depend on the type of the data used in it. POST Method Specifies the Web browser to send ail the user information through the body of the HTTP request
Relational Operator Compares two operands that determine the relationship between operands Rsort Function The rsort ( ) function sorts the element values in the descending alphabetical order.
Scope of Variables The scope of a variable is the portion in the script within which the variable is defined. It indicates the lifetime of a variable.
V 1.0 rD 2004 Aptech Limited Web Scripting with PHP Page vii
rAJ:PTECH
Glossary
ORLDWIDE
Glossary Session
Refers to the time the user accesses information on a particular Web site
setcookie Function
Generates the cookie header field that is sent along with the rest of the header information
Single Inheritance
Contains only one base class. The derived class inherits the properties of the base class
sort Function
Retains its value even after the function terminates. The static variable is used in the recursive function.
String
Data type that stores a set of characterAhose are enclosed within single quotes or double quotes
String Functions
Checks single variable against multiple values and executes a block of code based on the value it matches.
Page viii
Glossary
y r a s o l G
Ternary Operator Also known as conditional operator, simplifies complex conditions into one line statements Time Function 'Jeasures time in the number of seconds from ls' January 1970 00:00:00 GMT
0
UNIX Timestamp &gnifies the time and date that the time() function returns URL . URL is a Uniform Resource Locator. The URL locates the addresses of the resources on the Ddd Wide Web.
0
.P'#'hile Loop
::..`es loop statements depending on the return result of the testing condition after testing it. s loop is used for displaying the contents of the table of MySQL database.
th PHP