Web Scripting With PHP 1-12
Web Scripting With PHP 1-12
Table of Content
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. Introduction to PHP Form Handling in PHP Using Variables and Expressions in PHP Using Variables and Expressions in PHP PHP Operators PHP Operators Conditional Statements in PHP Conditional Statements in PHP Flow Control in PHP Flow Control in PHP Functions in PHP Functions in PHP Working with Arrays Working with Arrays Handling Databases with PHP Working with Cookies Working with Cookies Session Management in PHP Handling E-mail with PHP Handling E-mail with PHP OOP concepts OOP concepts Glossary 1 13 29 41 51 63 75 89 105 115 123 139 153 167 181 199 211 221 239 247 255 267
bjectives
At the end of this session, you will be able to: Discuss the history of PHP Identify the need for PHP Learn about PHP tools and setup Write a simple PHP script Learn about User 1/0 Use PHP to generate HTTP headers Pass variables via URL
JILITody,ction
PHP stands for PHP - Hypertext Preprocessor. It is a scripting language used for developing dynamic Web pages. It is embedded within HTML codes. It is an open source Web page scripting language. PHP code is executed on the server and as a result the client cannot view the code. In this session, we will learn about the history how to write a simple PHP script, how to generate HTTP headers using PHP and how to pass variables via URL.
1.114 61 Mo r Y.- of P
PHP is an advanced product of PHP/Fl. Rasmus Lerdorf created PHP/FI in the year 1995. PHP/ Fl stands for Personal Home Page/Forms Interpreter. Initially, it was a simple set of pert scripts, which was used for tracking accesses to his online resumes. These set of scripts were named as 'Personal Home Page Tools'. These scripts required more functionality. After writing larger C implementations, the scripts were able to work with the databases and the users were able to develop simple dynamic Web applications. In the year 1997, PHP/Fl got advanced to PHP/FI 2.0. Thousands of users had installed it in approximately 50,000 server domains. PHP/Fl 2.0 later got advanced to PHP 3.0. PHP 3.0 is the first version of recent PHP. Andi Gutmann and Zeev Surakshi created PHP 3.0 in the year 1997. It provides a concrete infrastructure for different databases, protocols, and APIs to the end users. In addition, PHP 3.0"also provides object oriented syntax support. In the year 1998, PHP 3.0 got advanced to PHP 4.0. PHP 4.0 includes supportive features for more Web servers, HTTP sessions, output buffering, and security while handling user inputs. This is the latest version of PHP.
Page 2 of 274
W 0-ft L'D W 1O E
AprEcAf
Introduction to PHP
PHP is used for server-side scripting. PHP is platform-independent. It can work on any operating system. The advantages of using PHP are: It is easy to learn, use, and implement It is free for access It can be executed on any platform PHP is a scripting language and a set of tools. These tools are used for performing various server-side functions. In addition, it can also be used to execute scripts from the command line and for developing client-side GUI applications that can operate on any platform. The following are some of the uses of PHP: Application control - PHP was initially used as an application control language. It was designed to control access logging for HTTP servers. Later on, it was started being used as scripting language in applications, such as Microsoft Word and Excel. Database Access - PHP is used with MySQL to access database. PHP can access any SQL or ODBC database. It can read and write data in the databases. Due to this feature, PHP is becoming famous for online business applications. As a. result, PHP has become a popular tool for e-commerce. File Access - PHP is used to work with files. It can read and write files. It uses the documents for editing remotely. PHP is also used for generating files in various formats, such as PDF and HTML formats. It is a popular tool for HTTP distribution. It generates emails by taking data from the documents and sends it through any standard mail protocol. It has an ability to work with many data files and provide answer to the queries. As a result, it is an ideal tool for creating search engines and message boards. Graphics - PHP can also manage graphical content. It can be used to create graphs and charts. It also generates image files such as GIF and PNG.
Page 3 of 274
Session I
EffPTECIff
ORLDWIDE
Introduction to PHP
PHPDebugger DBG Uses Linux as well as in Windows platform. Its current version is 2.11.23. This tool is freely available to all. This tool helps the PHP scripts to execute in steps. It enables us to trace the errors in scripts. ionCube Standalone PHP Encoder Enables quick execution of scripts. It is freely available for Linux platform. Its updated version is 3.1. Codelock Uses Linux platform for working with PHP scripts. It is freely available with 2.0 versions. PHing Works on Linux platform. The tool depends on the platform where the PHP is working. It is freely available for users. Its updated version is 1.0rc2. It performs various file system operations while processing a file. NuSphere PHPEd Uses 3.1.2 version on Linux platform. It is freely available to users. It is an Integrated Development Environment that includes all functionalities for developing dynamic Web sites. This tool supports more than one application developers. xored:WebStudio Uses the updated version of the tool. Its latest version is 0.2.2. It works on the Linux platform and is freely availability to the users. This tool is built on an eclipse platform. An eclipse platform is a tool platform for open source IDE. PHPmole Uses GNOME platform for working with PHP. GNOME platform is a desktop environment for Linux. The latest version of this tool is 1.3 and is freely available to the users. This tool is a combination of Dreamweaver software with Microsoft Visual studio software.
Simplewire PHP SMS Software Development kit Works on Linux platform. It is available in 2.3.0 version with freely available to users. This tools works with the wireless messaging network that enables us to send SMS to mobile phones. Quanta Plus Web Development Environment Uses 2.0 version of tool on Linux platform. It is freely available to the users. It is a Web development tool. K PHP Develop Works on Linux platform only. It is freely available with 0.1.6 version of the software. This tool supports MySQL as a database server. It has different modules, such as server, server setup, clients, and plug-ins. It is an integrated Web development tool. Gedit Works on Linux platform. It is a text editor that is used for writing PHP scripts. This tool does not have its own version because it comes by default when Linux is installed. It is a normal text editor that is similar to notepad of Windows.
Script
PHP file can include simple text, HTML codes, and PHP script. A PHP script starts with ?php tag and ends with the ?> tag. These scripts are embedded in the BODY tag of the HTML file- A PHP file is saved with a p',lip extension.
Page 4 of 27^
rAJy7'ECAF
Session 1
"-OR:L
IE
Introduction to PHP Some of the simple PHP scripts are: To display current date using the PHP script: 1. Open the gedit text editor. Enter the following code: < HTML > <BODY> The Date is: <?php echo gmdate("M d Y"); </BODY> < /HTML.> After entering the code, the text editor appears as shown in Figure
1.1.
Figure 1.1 Specifying Code Note the PHP script is placed within the BODY tag of the HTML code. The text enclosed within <?php and ?> tag is sent to the PHP script engine for processing. After processing of the PHP script, the contents are returned to the browser as a normal Web page. 3. Save the file with the name, date.php under the /var/www/html directory.
5.
Type http: / /localhost /date. php in the address bar and press the Enter key. The output appears, as shown in Figure 1.2.
V 1.0 @ 2004 Aptech Limited V 1.0 2004 Aptech Limited Page 5 of 27^
5. b
Session 1
WORLDWIDE
APYIECH
Introduction to PHP V
o 'Ila z ''X i
illn
F i l e E d i t Vi e w G o B o o k m a r k s T o o l s w i n d o w H e l p http:/Aocalhost/dat h c r a e S _ p E ___________ Reload Stop Print p (I~Products '!,1Home 1600kmark5 eRed Hat Network C, Support (,]I Back Forward
I
LS \Z, 0 (sR I Done Figure 1.2 : Displaying the Current Date In the PHP script, echo command is used. The echo command displays contents in the Web browser. The gmdateo is a PHP function enables us to display current date and time in the browser. The gm stands for Greenwich Mean Time. This function displays the current Greenwich Mean Time date and time. The letter, M, used in gradate () function displays the month of the current date. The letter, M, displays only first three letters of the month. The letter, d, displays the current date and Y displays the current year. The letter, Y, displays all the four digits of the year. To display simple text in the browser using the PHP script:
1. 2.
After entering the code, the text editor appears as shown in Figure 1.3.
Page 6 of 27^
Session 1
W 0 ft-LD W US.-E
AP&I-EcAr
Introduction to PHP
v Un
File Edit
Search
Tools
Documents
Help
View ,
__g r o .,
N O
Save
11
. .... ..... .
Undo Redo
untitled i * x
INS
Figure 1.3 : Codes fordisplaying Text Note the echo command is used to display the text. The text to be displayed is enclosed within double quotes. 3. 4. 5. Save the file with the name, stringdisp.php under the /var/www/html directory. Open a Mozilla Web browser. Type h t t p : / / l o c a l h o s t / s t r i n g d i s p . p h p in the address bar and press the Enter key. The output appears, as shown in Figure 1.4.
"V
7,
Forward http:lllocalhost/sti Reload Stop __________________
j*,Search
1-1
(32
Done
jk---
-- ---- ---
1-;D=,
Page 7 of 27^
(APrEciv
Sessi
In
Introduction to PHP To display text in the Web browser with the help of a variable: 1. 2. Open the gedit text editor. Enter the following code:
<IITML> <BODY> The string j S <?php $str = "My name is Samson"; echo $str; </BODY> </HTML> After entering the code, the text editor appears as shown in Figure 1.5.
%
' P
U n t i t l e d
~"YNew
Open
:.
54we
ht
llntitledai4s,~~
Ln 6, Col. 11
INS
4. 5. 3.
Open a Mozilla Web browser. Type htt-p://I-ocalhost/stringname.php in the address bar and press the Enter key. The output appears, as shown in Figure 1.6. Save the file with the name, stringname.php under the /var/www/htm] directory.
Page 8 of 27^
Sess~on I
."L A) LWAOlz
Introduction to PHP
07"'N'7
to
HyperText Transfer Protocol (HTTP) is a network transmission protocol that transfers hypertext files. It runs on top of TCP/IP suite, which is the foundation protocol suite for the Internet. HTTP protocol includes three parts, such as the request and response line, the HTTP header, and the body of the protocol. HTTP header sends information to the client or the server about the application that will be displayed on the browser. The information about the application depends on whether the application is on request line or on the response line. HTTP header includes categories, such as: General Includes information about the client and the server Entity Includes information about the transferred data either from the client to the server or from the server to the client Request or response Includes information about the configuration of the client and the server model. It also contains the information about the type of document the client is receiving from the server and the document that the client will be sending to the server_ InPHP, the header () function should be used to generate the HTTP headers. The header () function sends the HTTP commands to the server through HTTP protocols. The scripts written in the header affects only the main display page. After the execution of header function, it displays a blank line showing that the header information is complete.
Page 9 of 27^
(APrEcK
Session 1
OAUDMUD-E
Introduction to PHP Where, string - Includes authenticating or validating strings for the server. The whole string is enclosed in the single quotes.
77
For example, use an authenticating string in the header ( function. < ? p h p header('kNWVJ-Authenticate: Negotiate');
; f i x 7 k B o G w v d E ia F e t lr m W T s l e H w o d i p n .. .... . Z'
. :
4,
I
. ;
Back In the above example, WWW-Authenticate is a header that includes an authenticatingForward parameter Reload Stop for the request made to the Web server. Here, Negotiate is one of the authenticating parameters. Print
I -
Options such as replace and http_response_code can be used in a header () function } along with the authenticating parameter.
H
o m e
4 B o o k
The parameters of replace option shows whether the header needs to be replaced with a new m header or add a new header to the document. The header is normally replaced with a new header if there is no mention of any replace option. If the replace optiona is false then many new r headers will be added to the document.
k
For example, to add multiple headers to the document: < ? p h p false); header('M%M-Authenticate: NTLM',
R e d H
In the above example, false is the parameter of the replace option. NTLM is the authenticating a t parameter. N
e t w o t f [ k r S u p p o ( t r j 2 S
Page 10 of 274
V 1.0
h o
Session 1
(APrEcff 0 R L D W : 1 0 Z
The above example shows the header string as HTTP/. The data in the rest of the string is the status of the client that was requested by the user. For example, to show the location of the client:
The example shows the requested location on the browser. It also shows redirect status code if the redirect code is mentioned while displaying the status. In the above example, 404 is the status code used for displaying the status of the client. Figure 1.7 shows the output of the above codes:
V
E lle Edit View
4, L*O http://www.msn.com/ H &%Search L-4 .. Back Print .Forward Reload stop - -... . ........... Home 1 41 Bookmarks, t Red Hat Network (supportshop(dPfoducts (Training port
Netflix is your personal movie service. NO LATE FEES. Try FREE! Search the Web'
T d,, . Jo,?: Today On NNN
Autos
Ccr sc: A
-d., WLd c uon ti[c . Owl be a g) mi-k
I
.....
cl G2
Done
nu t H ItdcnPP oi r to o
Page 11 of 27^
Session 1
W 0 R L D W 1,0;5
APFECi,
Introduction to PHP
SUMMARY
PHP is a general purpose scripting language used for developing dynamic Web pages and is used with HTML coding scripts PHP 4.0 includes supportive features for more Web servers, HTTP sessions, output buffering, security while handling user inputs, and many more new constructions for languages PHP is developed from C-modules, therefore the scripts are also executed from the command line to make client-side GUI applications
PHP has become a popular tool for e-commerce because of its smooth accessibility to any SQL statements or any ODBC databases PHP is also used for generating files in various formats, such as PDF and HTML formats. It generates emails by taking data from the documents and sends it through any standard mail protocol PHP is also used for generating graphical images, such as GIF and PNG images
A PHP script starts with <?php tag and ends up only with the ?> tag. These scripts are embedded in the HTML tags A HTTP protocol is divided into three parts, such as the request and response line, the HTTP header, and the body of the protocol
PHP uses tools for developing and designing Web pages. These tools are the program text editors. Gedit is a popular text editor used for programming on Linux platform
Page 12 of 274
Session 1
Introduction to PHP
a. HTML, FORM b. HTML, PHP c. scripting, HTML d. C, user-friendly tool for making PHP is adirective a. HTTP distribution b S h i 3. " The texts are displayed on the browser with the help -of a. b. C. d. 4. echo GET display
PRINT
command.
The contents from the database of the _________ are stored in _______ a_ b.
C.
d. 5_ a. b.
C.
Fields, browser Database server, forms Web server, variables PHP, variables PHP tool executes the scripts in step-by-step manner. PHPEd PHPDebugger DBG Codelock Phing
d.
Page 13 of 27^
Objectives
At the end of this session, you will be able to: Use the GET method Use the POST method Retrieve data from forms using the Form methods Use the hidden fields
J;,i.,itroductiom
PHP supports the powerful feature of handling forms. In PHP, we can retrieve the form data using the form methods such as GET or POST. The way data is retrieved depends on the method used for retrieving the data. PHP also enables us to pass the data from the hidden fields. In this session, we will learn about the attributes of the form. We will also learn how to pass data from the form to the Web server using the GET and the POST method. In addition, we will learn how to retrieve data from the hidden fields in the form.
2.1 Forms:
A form provides a medium of interface for the client and the server to interact with each other. A form contains fields, where the user can enter information. This information is passed to the Web server for further processing. Forms are common on the Internet. A form appears on the display screen and the user fills in the information. This information is then passed to a form processing application that adds the information into a database. PHP provides us with the powerful feature of handling forms. PHP provides built-in support for collecting data from a HTML form, where HTML stands for Hypertext Markup Language. The user enters the information in the HTML form. On submission of the form, the information is sent to the Web server, which in turn passes the information to the PHP script engine. The script engine then processes this information, manipulates it, and sends the output back to the Web browser. A form consists of the following attributes: Action - Specifies the Uniform Resource Locator (URL) that will process the form data and send the feedback. The URL- can be the URL of simple HTML page, PHP page, or any server-side script. The PHP script engine receives the information for processing when we specify the URL of the PHP page in the action attribute. Method - Specifies the way the information is to be sent to the URL
Page 14 of 27^
Page 15 of 27^
Session 2
WORLDWIDE
Session 2
APY"C- C"
body of the HTTP request. This is possible because there is no physical limit on the amount of information passed through the body of the HTTP request_ Theinformation sent by the POST method is not encrypted. As a result, it is easily accessible to a hacker. In order to secure the information, it is necessary to establish a secure server connection. The POST method requests the server to accept the information in the body of the HTTP request. In the POST method, the variables are passed as they are passed in the GET method. The difference is that we cannot view the variables in the URL.
$varname
Where,
$_GET['variable'];
varname - Specifies the name of the variable in which the data is to be stored
Page 16 of 274
(',6Vr,ECAF
Session 2
~17 0 R L. 0 W,1,0.8
Form Handling in PHP 2. Enter the following code to create a form that accepts the first and phone number of the user: name, last name, address
<HTML> <BODY> <CENTER><BR><BR> <B>ENTER YOUR PERSONAL DETAILS</B> <FORM METHOD=GET ACTION="Detai1s.php"> FIRST NAME: <INPUT NAME="TEXT" TYPE="n1text"><BR><BR> LAST NAME: <INPUT NAME="TEXT" TYPE="n2text"><BR><BR> ADDRESS: <TEXTAREA NAME="n3text" ROWS=1, COLUMNS=1000></TEXTAREA><BR><BR> <BR> CONTACT NO.: <INPUT NAME="TEXT" TYPE="n4text"> <INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="SUBMIT"> <BR><CENTER> </BODY> </HTML> After entering 'the code, the text editor appears as shown in Figure 2.1. "n lrx,
File Edit View Search ..',.Tpds Documents Help
ul n New Open Untitled 1* x
<HTML>
<BODY> <CENTER><BR><BR> <B>ENTER YOUR PERSONAL DETAILS</B> <FORM METHOD=GET ACTION = 'Details.php'> <BR> FIRST NAME: <INPUT TYPE="TEXT" NAME="n1text"><BR><BR> LAST NAME: <INPUT TYPE="TEXT" NAME="n2text"><BR><BR> ADDRESS: <TEXTAREA NAME="n3text" ROWS=1 , COLUMNS=1000></TEXTAREA><BR><BR>I CONTACT NO.: <INPUT TYPE="TEXT" NAME="n4text"> <INPUT TYPE="SUBMIT" NAME "SUBMIT" VALUE="SUBMIT"> <BR></CENTER> </BODY> </HTML>
Ln 12, Col. 66 INS
Session 2
W 0 R L D W I'D E
AprEc"
Form Handling in PHP 3. 4, 5. Save the file as Details.html under the /var/www/html directory. Open a new file in the gedit text editor. Enter the following code for retrieving the personal details:
<?php
$A=$_GET['n1text]; $B=$GET['n2Lext1; $C=$_GET['n3text]; $D=$GET['n4text1; echo "YOUR PERSONAL DETAILS"; echo I/<BR><BR>"; echo "FIRST NAME: $A <BR>"; echo "LAST NAME: $B <BR>"; echo "ADDRESS: $C <BR>"; echo "CONTACT NO.: $D <BR>";
After entering the code, the text editor appears as shown in Figure 2.2.
gedit earchr",I.- T
A0
f--. Untitled 1* x
New Open
r,:-%
1.
I . ill
Replace
<?php $A=$_GET['nitext']; $B=$_GET['n2text']; $C=$_GET['n3text']; $D=$_GET['n4text']; echo "YOUR PERSONAL DETAILS"; echo "<BR><BR>"; echo "FIRST NAME: $A<BR>"; echo "LAST NAME: $B<BR>"; echo "ADDRESS: $C<BR>"; echo "CONTACT NO.: $D";
?>I
Ln 12, Col. 3 INS
6. 7. 8.
Save the file as Details. php,under the /var/www/html directory. Open the Mozilla Web browser. Type http-Hlocalhost/Details.htmi in the address bar and press the Enter key. The form to enter the personal details appears, as shown in Figure 2.3.
Page 18 of 274
Session 2
APIIECH A Ww'uo a
W 0'R L
1 . 0
C O A
Back l Home
Forward
Ys Reload Stop
hit 1 3411ocalhost/PersonalDet;t
Search ]
ADDRESS: I
co,N.-rAC'I- NO.:
I
SUBMIT
Figure 2.3 : Personal Details Form 9. * Enter John in the FIRST NAME text box. 10. 11. Enter Simons in the LAST NAME text box. Enter 32, Park Street, New Jersey in the ADDRESS text box.
12- Enter 45450 in the CONTACT NO. text box. 13. Click the SUBMIT button_ A page appears, as shown in Figure 2.4.
'IV
inn IFfn 1!-X
\3
Back
15,
C: :1
roducts
(S
iTrain
YOUR PERSONAL DETAILS FIRST NAME: John LAST NAME: Simons ADDRESS: 32, Park Street, New- Jet---&!v CONTACT NO.: 45450
Done
[7
Page 19 of 274
Session 2
('APrEcjv
WOR4D W4 D E
P O SMet!lod T
We can also use the POST method. The POST method sends data through the body of a HTTP request. The syntax to retrieve the data if we have used the GET method is:
$varname = $_POSII'['variable']; varname - Specifies the name of the variable in which the data is to be stored $POST[ 'variable' ] - Specifies the name of the input variable
For example, to retrieve the form data in the PHP script using the GET method: 1. 2. Open the gedit text editor. Enter the following code to create a form that accepts the employee details:
<HTML> <HEAD> <TITLE>Employee Details</TITLE> <FORM METHOD=GET ACTION="EMP_DETAILS.php" </HEAD> <BODY> <H4>Enter your details</H4> <FORM> <TABLE> <TR> <TD>Employee ID</TD> <TD><INPUT TYPE="text" NAME="empid"></TD> </TR> < T R > <TD>Name</TD> <TD><INPUT TYPE="text" NAME="name"></TD> </TR> < T R > <TD>Department</TD> <TD> <INPUT TYPE="radio" NAME--"dept" VALUE="Finance">Finance <INPUT TYPE="radio" NAYIE="dept" VALUE="Marketiiig">Marke+,.,ing <INPUT TYPE="radio" NAME="dent" VALUE="TP">IT < /TD> </TR> <TP> <TD>Einail</'1.'D>
Web Scripting with PHP V 1.0 2004 Aptech Limited
A, PVT IFCIN,
Session 2
Form Handling in PHP
<TD><INPIJ'T- TYPE="text" N.A11E="ernai 1 " >< /TD> </TR>. </TABLE> <BR> <TD><INPUT TYPE="submit" VALUE="SUBMIT"></TD> </FORM> </BODY> </11TML>
After entering the- code, the text editor appears as shown in Figure 2.5.
i
j F il e .
in X , L) oc ur n e n t s
Help
New O p e n
... L,,' Untitled
Save
Pdnt' Undo R e d o
Find R ep la c e
1 x
<HTML> <11EAD> <TITLE>Employee Details</TITLE> <FORM METHOD=GET ACTION="EMP_DETAILS.php"</HEAD><BODY> <H4>Enter your details</H4> <FORM><TABLE><TR> <TD>Employee ID</TD> <TD><INPUT TYPE="text" NAME="empid"></TD></TR><TR> <TD>Name</TD> <TD><INPUT TYPE="text" NAME="name"></TD></TR><TR> <TD>Departnient</TD><TD> <INPUT TYPE="radio" NAME="dept" VALUE="Finance">Finance <INPUT TYPE="radio" NAME="dept" VALUE="Marketing"Aarketing <INPUT TYPE="radio" NAME="dept" VALUE="IT">IT</TD></TR> <TR><TD>Email</TD> <TD><INPUT TYPE="text" NAME="email"></TD></TR> </TABLE><BR> <TD><INPUT TYPE="submit" VALUE="SUBMIT"></TD> 1 </F0RM></B0DY></HTN1L>1
Ln 19, Col. 22 INS
Figure 2.5 : Creating the Employee Details Form 3. 4. 5. Save the file as EMP_DETAILS.html under the /var/www/htmi directory. Open a new file in the gedit text editor. Enter the following code for accepting the values from the form:
<?php <?Php $A= $GET[ 'Crnpict' I
$B=$_G-ET[ 'nzlule'] ; $C=$_GETj'deoL']; S " D =. GET[ 'email']; echo "YOUR PERSONAL DETAILS"; e Ir I ci lo <BR><HR>";
Page 20 of 274
Session 2
(APrircff ORLDWIDE
--1
After entering the code, the text editor appears as shown in Figure 2.6.
%I
New Open
M -, Untitled 1* x <?php $A=$-GET['empid']; $B=$-GET['narne']; $C=$-GET['dept']; SD=$-GET['emaiI']; echo "YOUR PERSONAL DETAILS"; echo "<BR><BR>"; echo "EMPLOYEE ID: $A<BR>"; echo "NAME: $B<BR>"; echo "DEPARTMENT NAME: $C<BR>"; echo "EMAIL: $D";
AW
6'0,
xT
File Edit View go Bookmarks Tools Window Help t~ , hn,:Jji ih., DETA ;q Searchi Back Forward Reload Slop dBookmarks eRed Hat Network LAISUppott (:-!Shop (&roducts C6Traindrig I Home IP i t Enter your details Employee ID Name Dcpannmit Email Finwuc (- Marketing C IT
3)
4 Done
--------- --
................. ---------- __
I- *a'-.D' G-r,-
Page 21 of 274
EfEPTEC
ORL
W I U I
Session 2
Enter A05 in the Employee ID text box. Enter Peter Taylor in the Name text box. Select the department name as IT. Enter peterA05@fiinfotech.com in the Email text box. Click the SUBMIT button. -A page appears, as shown in Figure 2.8.
%0
Mortl[l1 q
Eile -~ *
LAewGo
Bookmarks
1
Tools
W n do w
L id P
~-~65'jl
>
In the above example, the form contains a hidden field containing the text, PHP MESSAGE.
Page 22 of 274
Session 2
WORLDWIDE
APTECK
For example, to use the hidden field and pass the name of the continents in the PHP script: 1. 2. Open the gedit text editor. Enter the following code to create a form that allows to select a continent:
<?php $var-l= "ASIA"; $var2 "AUSTRALIA"; $vaj--3= "EUROPE"; echo '<FORM METHOD='GET' ACTION='Display php'>; echo " Specify the continent?"; echo "<SELECT TYPE='LISTBOX'' NAME='continent'>; echo "<OPTION>$varl</OPTION>"; echo "<OPTION>$var2</OPTION>"; echo "<OPTION>$var3</OPTION>"; echo "</SELECT><BR><BR>"; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN1 VALUE='$var1'>; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN2 VALUE='$var2'>; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN3 VALUE='$var3'>; echo "<INPUT TYPE=SUBMIT>"; echo. "</FORM>";
After entering the code, the text editor appears as shown in Figure 2.9.
V
Un titl ed Llk , File
E d i t V i e w S e a r c h T o o l s L ) o c u r n e n t s H e l p .. . .........
40,
New Open Untitled 14 x
4 ID It n
S a v e P r i n t U n d o R e d o C u t C o py Pa s t e F in d R e p la ce
<?php Svarl="ASIA"; $var2="AUSTR4,IA"; $var3="EUROPE",echo "<FORM MFTHOD='G2T' ACTION= 'Display.plip'>"; echo " Specify the continent?"; echo "<SELECT TYPE='LISTBOX' NAME='continent'>"; echo "<OPTION>$var1</OPTION>"; echo "<OPTION>$var2</OPTION>"; echo "<OPTION>$var3</OPTION>"; echo "</SELECT><BR><BR>"; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN1 VALUE='$varl'>"; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN2 VALUE='Svar2 I > .1 ; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN3 VALUE='$var3'>"; echo "<INPUT TYPE=SUBMIT>"; echo "</FORM>";
Session 2
WID R
APTHCH,
$A=$_GET['HIDDEN1']; $B=$_GET['F1IDDEN2'11$C=$_GET['HIDDEN3'1; $name=$_GET['continent'1; echo ("Continents<BR>"); echo '<BR>"; echo $A; echo "<BR>"; echo $B; echo "<BR>"; echo "$C echo "<BR>"; echo "<BR>The continent you have selected is:<BR>; echo "$name";
After entering the code, the text editor appears as shown in Figure 2.10.
! j n l q d t 4 f l e o t9 e f I (%q4L ~iL I File Echt View Search Tools Qocumerds
- -- - ----------_-
. .... ....
<?php $A=$_GET['HIDDEN1'1; $B=S_GET['HIDDEN2'1; $C=$_GET['HIDDEN3'1; $name=$_GET[ 'continent') echo ("Continents<BR>"); echo " <BR> echo $A; echo " <BR> echo $B; echo "<BR>"; echo $C; echo "<BR>The continent you have selected is:<BR>"; echo "$name";
Ln 15, Col. 3
INS
Figure 2.10 : Retrieving the Data from Hidden Fields 6. 7. Save the file as Display.php under the /var/www/html directory. Open the Mozilla Web browser.
Page 24 of 274
E4lt_s_-72rECAIT
Session 2
L;V W 1'D E
8.
Type http://Iocalhost/Continent.php in the address bar and press the Enter key. The continents form appears, as shown in Figure 2.11.
File Edit: View
Back
Go' Bookmarks
http:j/l, v Forward Reload Print Home Red Hat Network [Support Specify the continend ASIA
A Products QftTr~
Submit Query
EM
c3`3
Figure 2.11 : Continents Form 9. 10. Select Europe from the Continent drop-down menu. Click the Submit Query button. The page appears, as shown in Figure 2.12.
File Edit View Go Bookmarks Tools Window Help L Back Forward Reload Stop Ltti~/'E . . ............... ............
~,j
n I* Search Print l E
Home Xf Bookmarks -**Red Hat Network LjSupport [Shop L-1 Products Ljtj,
Continents ASIA AUSTRALIA EUROPE The continent you have selected is: EUROPE
M 14
Bone
............. ....
Page 25 of 274
(APrEcm
Session 2
~+L:DWID.N
,,SUMMAR
);> A form provides a medium of interaction where users can fill in data. PHP has a built-in support for collecting data from a HTML form. The information from this form is automatically available to the script engine. The script engine then process the information. When the server accepts a form it recognizes the form as a collection of codes. The attributes of a form as are as follows:
Action: Specifies the Uniform Resource Locator (URL) that will process the form data and send the feedback Method: Specifies the way the information is to be sent to the URL The GET method specifies the browser to send the values the user placed on the form to the URL. The URL is the Uniform Resource Locator. The POST method informs the browser to send the values the user placed on the form to the PHP script engine in the body of the HTTP request. Hidden form fields enables form developers to pass information, from a form to a script, or from one form to another, before being passed to a script. Hidden form fields are not visible to users.
Page 26 of 274
(APTEC-V
Session 2
W O R L D W I D E &
1 a. b. C. 2.
provides an interaction between client and the server. Action attribute Methods Form
HTML stands for __________ a. b. C. Hyper Text Mode Language Hyper Text Markup Language Hyper Text Manual Language
3.
The ___________ specifies the Uniform Resource Locator (URL) that will process the form data and send the feedback. a. b. C. Method Form control Action attribute
4.
is an application program that performs the task of understanding the form, and interpreting it to the server. a. b. C. d. URL PHP HTTP None of the above
5.
? /
Page 27 of 27zl
Session 2
Form Handling in PHP
method sends the information in the body of the HTTP request.
a. b.
C.
d.
Page 28 of 274
0 bjectives
At the end of this session, you will be able to: Define Identifiers Lists the data types Use variables and constants Define the scope of variables Use the HTTP environment variables
4ntroduction
In programming, we use variables. A variable stores the data that keeps on changing. Different types of data can be stored in a variable. An expression consists of variables and operators. In this session, we will learn about the identifiers, data types, variables, constants, and expressions. In addition, we will learn about the scope of variables and HTTP environment variables.
3.1 identifiers.
Identifiers are names given to various elements of a program such as variables, constants, arrays, and classes in a program. We must keep some points in mind while naming an identifier. They are: An identifier must begin with a letter It must contain only letters(A to Z) or digits(0-9) We can use underscore() to add space in the identifier to make it more readable An identifier must not include any special characters including blank space
Some of the valid identifiers are firstnum, ]name, net sal, add8num, and NewNum. Some examples of the invalid identifiers are shown in the Table 3.1. Identifier
f irst.-num
lnum
Invalid Because Use othyphen not allowed First character cannot be a number Use of blank space not allowed Use of ampersand not allowed Table 3.1 : Invalid Identifiers
first
I.J.
num
r s t & num
Page 29 of 274
Session
WORLDWIDE
T abl e 3 .2 : D a t a Ty pes
In PHP, do not need to declare a variable. A variable is automatically declared at the time of initializing the variable. The variable is declared with the data type as that of the value stored in the variable. As the value of the variable keeps on changing, the data type of the variable also keeps on changing. A dollar ($) symbol must be placed before a variable name. This symbol helps to differentiate a variable from other statements in the code. Variables are case sensitive. For example, a variable name, $varname-, is different from a variable name, $VarName. If a variable is created without any value assigned to it, its takes the value as NULL. The data type of such variable will automatically change during the execution time. The syntax to initialize a variable is:
$variable_name = value;
Page 30 of 274
Session 3
Where, $variable name - Specifies the name of the variable value - Specifies the value the variable will store
4PTIECII
RLDWIDE
When we assign a value to a variable, we are performing an assignment operation- An assignment operation is performed with the help of an equal to (=) sign that is placed between the variable and the value. The equal to (=) sign is called the assignment operator. The left side of the assignment operator has the name of the variable and the right side of the assignment operator has the value for the variable. The name on the left side of the assignment operator can be the name of a constant or a variable. A value of an expression can also be assigned to a variable. An expression consists of variables and operators. Some of the examples for the variables are: To store the integer in the variable:
$Salary = 5000;
Note the $Salary variable will be declared as the numeric variable because the value
assigned to it is of the integer data type. T o s t o r e s t r i n g i n t h e v a r i a b l e : $message
= "HELLO! How are you?" Note the $message variable will be declared as the string variable because the value assigned to it is of the string data type. The string is enclosed within the double quotes. To store the value of an expression in the variable:
<?php
Web Scripting with PHP
(APrEc'--f
Session 3
1\!_oe
L D WA Z:e
<?php $Fname = "John"; $Lname = "Smith"; $name =& $Fname; echo $name; echo $Lname;
Note the variables, $Fname and $Lname are string variables. The reference of the $Fname variable is given to the $name variable with the help of an equal to and ampersand symbols.
3.3 Constants
Constants are identifiers that contain values that do not change as the program executes. Like variables, constants are also case-sensitive. Once a constant is defined, it cannot be changed. A constant is declared using the define ( ) function. A constant has a global scope of existence. It can be accessed from anywhere in the script regardless of its position in the script. The syntax to declare a constant using the define () function is:
string_name Specifies the variable name for the constant mixed value Specifies a numeric or string value that is to be made constant
For example, to declare the constant, NAME, containing a string value: <?php
Page 32 of 274
( A
S e s s i o n 3
:0~
k0
0 R L D-WTD-E
T, ECH
Using V a r i ables and Ex press io ns in P HP In the above code snippet, a constant is declared. On executing the statement, echo NAME, the string value stored in the constant will be displayed. But, on executing the statement, echo name, an error message will be displayed. This is because constants are case-sensitive. We can also declare constants that are not case-sensitive using the defineo function. The syntax to create constant that case-insensitive: define(string_name, mixed value, case insensitive Where, case insensitive specifies a Boolean value, TRUE or FALSE. If the value specified is TRUE, the constant name will be case insensitive
different cases represent : different in
. values .
Two constants with the same 'name For example, to declare a constant that is case insensitive: <?php define("NAME", "Michael Graff", TRUE); echo NAME; echo name;
Note the TRUE value in the defineo function indicates that the constant to be declared must be case-insensitive. Now on executing both the statements, echo NA M E and echo name, the string value stored in the constant will be displayed.
MA Local 'Variables
variable
initialized
A P TEC' F"r,
Sess6on 3
W-0,91L.W.W.VDa
Using Variables and Expressions in PHP For example, to display product of two numbers-.
<?php echo "a'he multiplication value of 14 function multiply() $num1=14; $num2=15; $num2=$numl echo $num2; multiply();
15
$num2;
In the above code snippet, the variables, numl and num2 are declared inside the function as the local variables of the function. They are initialized and used inside the multiply ( ) function. The product of two variables, numl and num2 is calculated in the multiply() function. This function executes when the PHP script calls the function using the function name.
As a result, it can be accessed from any part of the program. The syntax to declare a global variable in a program is:
global $var_name;
Where, $var_name specifies the variable name that needs to be made global. For example, to perform multiplication of two numbers using the global variables:
<?ph-o $varl = 4; $var2 = 15; function multiply()
Page 34 of 274
Web
Session 3
W-O.R L D W I D E
~A_PiEclff
Using Variables and Expressions in PHP In the above code snippet, the variables, varl and var2 are declared as the global variables. They are initialized outside the function and declared as global within the multiply ( ) function. The product of two variables, varl and var2 is calculated in the multiply() function. This function executes when the PHP script calls the function using the function name.
3A.3 Static V i bl
A static variable is similar to a local variable. The only difference is that the static variable retains its value even after the function terminates. When a function terminates, the values of the local variables of that function looses its values. To retain the value of the variable throughout the execution, use the STATic keyword with the variable name. The static variable is used in the recursive function. A recursive function calls itself recursively within a function. The syntax to declare a static variable is:
static $var_na me = va lue;
Where, );,. var_name Specifies the variable name value Specifies the value of the variable For example, to use the static variable in a function: <?php
function sum() static $varl = 9; $varl=$varl + 12; echo $varl; e c h o " T h e a d d i t i o n v a l u e o f 9 + 1 2 sum
In the above code snippet, the varl is declared as the static variable. It is declared inside the sum ( ) function. The variable varl is local to the sum( ) function but it retains its value throughout the program.
Page 35 of 274
Session 3
Using Variables and Expressions in PHP
SERVER_ -SOFTWARE Returns the name and the version of the server software. To view the server software and its version, enter the following PHP script:
<?PHP echo $HTTP_SERVERSOFTWARE;
SERVER NAME Returns the server hostname. The hostname can be the IP address or
the DNS name of the server. To view the server name, enter the following PHP script:
<?php
echo $HTTP_SERVER NAME; SERVER PROTOCOL Returns the name and version number of the protocol that called the script. To view the server protocol, enter the following PHP script: <?php echo $HTTP_SERVER_PROTOCOL; SERVER PORT Returns the port number for the script. To view the server port, enter the following PHP script: <?php echo $HTTPSERVERPORT; COOKIE_ - DATA Returns the content of the recently used cookie. A cookie stores user information sent to the browser by the Web server. A cookie is saved as a text file. A cookie is sent back to the server when the browser requests to display a page. To view the cookie data, enter the following PHP script: <?php echo $HTTP_C00K1E_DATA;
POST FILES Returns information about the uploaded files. To view the uploaded files, enter the following PHP script: <?php echo $11TT11POSTFILES;
Page 36 of 274
Session 3
W 0 R L'D;WI 0,6
AprEcAel
Using Variables and Expressions in PHP MTPUSER AGENT Returns the name of the browser the client is using. To view the type of the browser, enter the following PHP script: <?php echo $HTTP_USER_AGENT;
HTTPACCEPT Returns a list of media types the client will accept. To view the list of media types, enter the following PHP script: <?php echo $IITTP_ACCEP,r;
HTTP_FROM Returns the e-mail address of the users those who have made any request to the server. To view the email addresses of the users, enter the following PHP script: <?php echo $HTTPFROM;
Page 37 of 274
Session 3
DR-L.11 W I - D a
F.= CH
SUMMARY
Identifiers are names given to various elements of a program such as variables, constants, arrays, and classes in a program A variable is an identifier whose value keeps changing. Variables are used to store a data value in it A dollar ($) symbol must be placed before a variable name Constants are identifiers that contain values that do not change as the program executes
A constant is declared using the define() function The scope of a variable is the portion in the script within which the variable is defined. The different scopes of variables are local, global, and static A variable initialized and used inside a function is called a local variable When a variable retains its value throughout the lifetime of the web page, it is called the global variable. It is declared with the help of the keyword global within the function The static variable retains its value even after the function terminates- It is declared with the help of the keyword static with the variable name Environment variables are system-defined variables that we can use in any PHP script Environment variables provide information about the HTTP request or the HTTP response A COOKIEDATA environment variable returns the content of the recently used cookie )> The environment variables are similar to the user-defined variables because they also begin with the dollar ($) sign
Page 38 of 274
Session 3
WOM-LDWIDE
A P MCM
CHECK YOUR
1. An assignment operation is performed with the help of _________ sign.
a.
2-
a. b.
C.
3.
4.
The a. b. C.
_________ environment variable returns the content of the recently used cookie. SERVERSOFTWARE SERVER_PORT COOKIE__DATA
d. HTTP_ACCEPT 5. protocol. a. b. SERVERPROTOCOL SERVER_PORT The __________ environment variable returns the name and version number of the
C . H T T P _ P O S T d. HTTP_FROM
11
Page 39 of 274
A1072FCIN
Session 3
W0.K--L,DW 'Or=
6. a. b.
C.
d. 7.
The ________________ variable retains its value through out the lifetime of the program. a. b.
C.
d. 8.
The ______________ environment variables returns information about the uploaded files. a. b.
C.
d. SERVERPORT
_ _ 40 of 274
Objectives
At the end of this session, you will be able to:
Use the assignment operator Use local variables Use global variables Use static variables 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:
Page 41 of 27s'~'
(A"PrEcm
S e s s i o
n
W" WORLDWIDE
ave,the,file as
directory. direct r .y
yp.6
ust :r
X4 i
loc
i l lib e t l a gg g
Bookmarks Red
This is John Ci77el
Hat
Network
Open a new file in the text editor. To calculate the product of two numbers and assign it to a variable, enter the
following
code:
Page 42 of 274
~P~`EaC'/Si
Session 4
Using Variables and Expressions in PHP
d2y
$int~_value2; $iift_vdIde2,~
aVd,
b%46Wi
tl*
Back !,Home dBookmarks eRed Hat Network GAsupport rA~Shop L_jproducts L4Tralrflng
I
I
I L.'%,
L . 4,' 93 42 j
--------
Done
Figure 4.2 :
4
Displaying
.11. Open a new file in thd~ltext editor. 12. To subtract a decimal number from another and assign its value to a variable, enter the following code:
Session 4
<BODY>
float--Yaluel. = 134.57;.; fleet vAlliez = 12.87; float value2, = $float_valuel :~ "The subtraction value of 4rjLoat vajue2;:
L6
http:/Aocalhost/assignflo L ' -j[;_; Search-4 Reload Slop Print B ,IH..cBookmarks eRed Hat Network dSupport EIShop GtProducts E jTraininq
Back
Fow;ard
:2 fDone
A variable initialized and used inside a function is called a local variable. The declaration of local variable and normal variable is similar. The lifeti me of a local variable begins when the function is called and ends when the function is executed. A local variable is declared inside a function and the value assigned is ret ained until the function execut es.
Page 44 of 274 V 1.0 0 2004 Aptech Limited Web Scripting with PHP
Session 4
W - 0 R L W.W."310',E
APKC-CH
Using Variables and Expressions in PHP For example, to use local variables in the function that calculates sum of two variables: 1. Open a new file in the text editor. Enter the following code to create the sumo function:
In the above code, the variables, $intl and $int2 are declared inside the sum () function as the local variables of the function. They are initialized and used inside the function. The sum of two variables, $inti and $int2 is calculated in the sum() function. This function executes when the PHP script calls the function using the function name.
Save the file as localvar.php under the.: Open the Mozilla Web browser.
directory.
Type http://localhost/localvar.php in` the address bar and press"the Enter key.
Page 45 of 274
Session 4
WORLDIWI-019
A P FEC117
U s i n g V a r ia b l e s a n d E x p r e ss i o n s i n P HP
Local.varlables - Maz Ili File Edit View Go Bookmarks Tools Window Help ; Back Forward Reload Stop
-7
14 http:/Poca1host/localvar.lF,
12 S ea rc h
C-4
Print
1 -1 Home I *Bookmarks *#Red Hat Network (dSupport UAShop EtProducts ,C;ATrajnlnq The sum of 43.4 + 13 = 56.4
division()
function:
<HTML> <HEAD> <TIITLE>Glbb al Variables</TITLE> </HEAD> <BODY> <?php $intl = 68; $int2 = 50; function division() global $intl, $int2;
Page 46 of 274
Limited
Session 4
(APT'ECH
woa LDWIDF
11
4,14a,
y he. o u t p u t
"
I "' F1 t
fig""
4Home 1.
Print
Tr gg
Id
Bookmarks
Red liat Ne
`
APP 4
19Prodixxts GA
j "..
411--'h
(D Done
I,
Sessio 4
Using Variables and Expressions in PHP 1. Open a new file in the text editor. 2. Enter the following code to create the decrement() function:
<HTML>
< H E A D >
W 0 A LD;WI:0,2
APF,'c_f'CN
<TITLE>Static
</IIEAD>
In the above code, the static_intl variable is declared as the static variable. It is declared inside the decrement() function. The variable, stati-c inti is local to the decrement() function but it retains its value throughout the program.
3. Save the file, as staticdec.php under the /var/www/htmi directory.
4.
Page 48 of 274
Session 4
W-OR'L 0 W I'D'
A P rECH
'S
File
Edit
View
go Bookmarks
Tools
window
Help cvittp:
h
---------
!'4. C , -e, 04 G9
Do n e
Page 49 of 274
EalT7rEcm
L
DWI
0,E
r
t~
Part II - For the next half an hour: 1. 2. Store the string, I am learning PHP 4, in a variable and display it on the Web browser. Create a form that accepts two numbers and displays its sum using the PHP script.
Web Scripting
Objectives
At the end of this session, you will be able to:
)>
,I>
Use Bitwise operators Use Assignment operators Use String operators Use Increment and Decrement operators
>
Introduction
All programming languages use operators. Operators are pre-defined symbols that allow performing specific actions. An expression contains operators and operands. The operators are assigned precedence values. This precedence value indicates the order in which the operators are evaluated in an expression. In this session, we will learn about different types of operators such as arithmetic, logical, relational, bitwise, assignment, string, increment, and decrement- In addition, we will learn the operator precedence order.
5-16~rlttmiatio. Operators I ~E L
We use arithmetic operators to perform mathematical calculations. We follow certain rules while performing mathematical calculations. Similarly, PHP also follows certain rules. It is necessary to follow these rules so that different people get the same answer for an expression. Consider the example below: $Varl =21-4*4; In the above expre-,sion, if we follow the order in which the operand appears, we get the answer as 68. Now if we follow the BODMAS rule of mathematics, the answer will be 5. PHP follows the similar BODMAS rules for calculation.
Page 51 of 274
CAOME
Session 5
PHP Operators PHP provides with the arithmetic operators, as shown in Table 5.1: operator
+
Description Adds the operands Subtracts the second operand from the first operand Multiplies operands with each other Divides the first operand by the second operand Returns the remainder when the first operand is divided by the second operand Table 5.1 : Arithmetic Operators
Some of the examples of the arithmetic operators are: To display the sum of two variables, VAR1 and VAR2:
.<?php $VAR1=5; $VAR2=10; $SUM=$VAR1+$VAR2; e c h o " T H E S U M O F 5 A N D 1 0 I S : echo "$SUM";
Note the $Sum variable will store the sum of two variables, $VAR1 and $VAR2. To display the product of three variables, $VAR1, $VAR2, and $VAR3-.
< ? -P h p $VAR1 =2; $VZ%R2=1_0; $VAR3 = 10; $PROI)UC7'=$V"'R1*$VAR2*$VAI'3; echo "THE PRODUCT OF 2, 10, AND 10 IS: echo "$PRODUCT";
Note the $PRODUCT variable will store the product of three variables, $VAR1, $VAR2, and
$VAR3.
Page 52 of 274
Session 5
141prAFCH
WG*RIL D W I D
PHP Operators
$REMAINDER=$VAR1%$VAR2; e c h o " T H E R E M A I N D E R O F 1 5 D I V I E D E D B Y 4 I S : " ; echo "$REMAINDER";
Note the $REMAINDER variable will store the remainder of two variables $VAR1 and $VAR2.
Name
Description
Equal to Not equal to Less than Less than or equal to Greater than Greater than or equal to
Returns true if both the operands are equal Returns true if the first operand is not equal to the second operand Returns true if the first operand is less than the second operand Returns true if the first operand is less than or equal to the second operand Returns true if the first operand is greater than the second operand Returns true if the first operand is greater than or equal to the second operand
For example, to compare two variables, enter the following code: < Php $A=74;
if ($A>$B) echo "$A IS GREATER THAN $B"; else echo "$A IS LESSER THI\d,4 $B";
The it statement executes a block of code only when the specified condition is true. Note the it keyword is followed by the condition. This condition compares two variables, A and B. If the variable A contains value greater than B, the code following the it statement will be executed.
Web Scripting with PHP V 1.0 nc 2004 Aptech Limited Page 53 of 27A
: APFECM
Session 5
0~
WORLDWIDE
PHP Operators Otherwise, the code following the else statement will be executed. The result of the above code will be A is greater then B.
Note the input value is accepted from the user. If the input satisfies the condition, the if body is executed.
Page 54 of 274 V 1.0 2004 Aptech Limited Web Scripting with PHP
EtSRI-ECM
Session 5
OR LDWIDE
PHP Operators
Table 5.4 : Bitwise Operators Some of the examples of the bitwise operators are: To use the & operator on 15 and 5: <?php echo 15&5;
Note the above code will return 5. To use the A operator on 10 and 15: <?php echo 101,15;
1 . 0
O c
2 0 0 4
A p t e c h
L i m i t e d
Page 55 of 274
Operator Name
General Form
Description
APYLU'CH
Session 5
W,',0,1UL'0W1VD-Z
PHP Operators
-
<?php $var1=52; $var2=10; $A =$var*$var2+8; echo "The value of A is:" echo "$A";
Note the above code will assign the value 528 to the variable $A.
Operand
++$a $a++ $a $a
Operator Name
Pre-increment Post-increment Pre- decrement Post decrement
Description
Increments the operand value by one and then returns this new value to the variable Returns the value to the variable and then increments the operand by one Decrements the operand by one and then returns this new value to the variable Returns the value to the variable and then decrements the operand by one
-1P . lip
$A=9;
AprEcAf
Session 5
PHP Operators echo "The value of A is: $A";
Note the above code will return the value of $A as 9. It will then increment it to 10 and return this new value. To use the pre-decrement operator on a variable $A:
<?php $A=1.0; e c h o ' T h e v a l u e o f A i s : $ A < B R > " ; $A; echo "The value of A is: $A";
Note the above code will return the value of $A as 10. It will then decrement it to 9 and return this new value_
Returns a concatenated string Appends the argument on the right side to the variable
Some of the examples of the string operators are: To concatenate the strings WELCOME and FRIENDS using the Concatenation operator: <?php
$A=WELCOME; $B= FRIENDS; $C="$A.$B" echo" CONCATENATED STRING IS $C-;
Note the above code will concatenate the strings and store it in a variable $C. The above code returns the string WELCOME FRIENDS.
Web
Page 57 of 274
Session 5
WORLIDWIIIDIZ
'APFIEC
PHP Operators > To assign a value to a variable using the Concatenating assignment operator: <?php
AND XOR Lowest Precedence OR Table 5.7 : Precedence of Operators The operators listed on the same row have the same precedence. For example, consider the expression below:
$A>60 OR $B==20
Now, in the expression above first the variables $A and $B are checked, whether they satisfy the required condition. Then the OR operator is used.
I
Page 58 of 274
Session 5
(A'P7-,FCH OR L D W I WE
PHP Operators
Operator is any symbol that performs an operation on an operand. An operator enables us to work on variables, strings, and numbers. > Operators enable to control the program flow.
In a complex expression, operator precedence indicates the order in which the operands
must be evaluated. PHP evaluates operators with high precedence before operators with precedence. The types of operators are: > Arithmetic operators Logical operators Relational operators Bitwise operators Assignment operators String operators Incremental and Decremental operators
low
The arithmetic operators work with numbers. They are used to perform mathematical operations. We follow the rule of BODMAS for operator precedence. The relational operators compare two operands. They determine the relationship between operands.
i i
>
The logical operators handle multiple conditions. They combine two or more test expression in a condition- They return a Boolean value. The Bitwise operators enable comparison and manipulation of operands. They operate on the bits of an operand. The assignment operator allows assigning a value to a variable. It enables us to set the operand on the letf side to the value on the right side The increment and decrement operators. allows to increase or decrease value of an
operand by one.
Page 59 of 274
Session 5
WORLDWJDE
APYIECH
PHP Operators
>
The concatenation operator joins two or more strings into a single string. The string operators used in PHP are: 0 Concatenation operator ('.'): Returns the concatenation of its right and left arguments Concatenating assignment operator side to the argument on. the left side Appends the argument on the right
Page 60 of 274
Session 5
(.-4Pr,FC,ff WORLDWIDE
PHP Operators
LM
is the symbol used to perform the operation on a value. Operand Variable Operator
2.
d. 3. a. b.
C.
None of the above operators compare operands and determine relationship between operands. Relational Arithmetic Assignment Bitwise
d.
5 a. b_ c. e. ==
Session 5
WOR LVW I DE
APFIECH
PHP Operators
6. a. b.
C. 7.
The << operator ______________ a. b. C. d. Shifts the bits of Operand2, Operand-I times to the right Shifts the bits of Operandl, Operand2 times to the left Shifts the bits of Operandl, Operand2 times to the right. Shifts the bits of Operand2, Operandl times to the left
Page 62 of 274
Objectives
At the end of this session, you will be able to:
Use Logical operators Use Bitwise operators Use String operators Use Increment and Decrement operator
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:
1 . 0
2 0 0 4
A p t e c h
L i m i t e d
Page 63 of 274
Session
CAP"0 R L D FW CI O N-F
PHP Operators
<INPUT TYPE="SUBMIT" VALUE="MULTIPLY" <BR> </BODY> </HTML> Save the file as multiply.htmi under the /var www/html 'directory. Open a new file in the text editor. Enter the following code to multiply the numbers:. <?php $A=$_GET['.n1text'j; $B=$__QET['n2text'l; $C=$A*$B; echo "The multiplication-of-
two.-
numbers is $C";
th ht41-:-, direct()
a
V,, : W'D
t ,1bd--tft"Wnd
e
d" 0111-
rowt er
zi
File
Edit
View Go
Bookmarks Tools
-i S
window
Help
!.,--Search Print
4 - Forward Back
!t Home
It
1 ()
Reload
p1 , 4 httl:i:/AocaIhostjMuItip -_ -
AN
IN I till iplicatio 11 of "Fwo Numbers tillibel-S Fn wi t he First Number: Enter the Second Number: I MULTIPLY (92i Done
A.
10. Enter the second number as 59. 11. Click the MULTIPLY button. The output appears, as shown in Figure 6.2.
Page 64 of 274 V 1.0 * 2004 Aptech Limited Web Scripting with PHP
Session 6
< H T M L > < B O D Y > <B>Authentication</B> <FORM METHOD=GET ACTION "Authentication.php"> ENTER USER NAME: <INPUT TYPE="TEXT" VALUE="NAME"> ENTER YOUR PASSWORD: <INPUT TYPE="TEXT" VALUE="Passtext"> <BR> <INPUT TYPE="SUBMIT" NAME "CONFIRM" VALUE="CONFIRM'> <BR> </BODY> </HTML>
3. 4. Save the file as AUthentication.html under the /var/www/htmi directory. Open a new file in the text editor.
V 1.0 (c) 2004 Aptech Limited Web Scripting with PHP
V,Mozilla,
Page 65 of 274
;A_Search
Session 6
w 0 ft:L 0 W 10.2
Air Eck
PHP Operators
4 N I
1K on'*'- P]
6 ~.bro er
v
%#
~-tn jrx
File Edit View Go Bookmarks Tools Window Help http:/Aocalhost/ Search Print Back Forward Reload S t o p I fa Home I Xf Bookmarks e Red Hat Network (El supportShop (El Products (SITrajninq
I :
Authentication
E N T E R E N T E R U S E R Y O U R N A M E P A S S W O R D :
C O N F I R M
X~
Z1
-F-C = Z 3 ( F 9 1 1
10. Enter pass as the password. 11. Click the CONFIRM button. A page appears, as shown in Figure 6.4.
Page 66 of 274
V 1.0
Session 6
W - Q , R - L ~ , D . W
1 1
PHP Operators
File
Edit
View
Bookmarks Stop
Tools
Window
Support ( A S h o p
O'
Products CjTraining
LZ -,?,
< H T M L > < B O D Y > <B>Grades</B> <FORM METHOD=GET ACTION "Grade.php"> ENTER YOUR PERCENTAGE: <INPUT TYPE="TEXT" VALUE="n1text"> <BR> <INPUT TYPE="SUBMIT" NAME=;"GRADE" VALUE="GRADE"> <BR> </BODY> </HTML>
3. Save the file as Grade .html under the /var/www/htmi directory.
V 1.0 Cc) 2 0 0 4
Aptech Limited
Page 67 of 274
Session 6
PHP Operators
$A,$_BT['nitext'];
if 60
h,
. . . .
-,v
Save the file as Grade. php','. under-, the tvar/mm/html directory.,,,,. Open the Mozilla Web browser. Type http://loc.alhost/Grade..html in the address bar and press the Enter key. A page appears 'prompting to enter the percentage, as shown in Figure 6.5.
ozilla
File Edit View Go Bookmarks Tools Window Help -a Search Pant
'X
Forwar
Back
Reload
Stop
httnAocalhost/Grade h fv]
i ___ I U
UU.'.
Home VI Bookmarks t R e d Hat Network (2ftSupport Grades ENTER YOUR PERCENTAGE GRADE
. ........ .
Page 68 of 274
Session 6
WORLDWIDE
A p r E c m
I'
GRADE
K*V ,
1-
111
-;
-1
Operator,
The assignment operator enables us to set the operand on the left side to the value of the expression on the right side. The '=' sign is the assignment operator. It is different from the equal to '= 'sign used as the relational operator. For example, to create a form that accepts the principal amount, interest rate, and no. of years and calculates the simple interest using the PHP script: 1. 2. Open a new file in the-text editor. Enter the following code to create a form: <HTML> <BODY> <B>Simple Interest</B> <FORM METHOD=GET ACTION "Simpleinterest.php"> ENTER THE PRINCIPLE AMOUNT: <INPUT TYPE="TEXT" NAME=" n1text" > <BR> ENTER THE RATE OF INTEREST: <INPUT TYPE="TEXT" NAME="n2text"> <BR>
Page 69 of 274
Session 6
Eaii:FECH L
,0W1,0-E
PHP Operators ENTER THE NUMBER OF YEARS: <INPUT TYPE="TEXT" NAME="n3text"> <BR> "CALCULATE" VALUE="CALCULATE"> <1 NPUT <BR> </BODY> </HTML>
di Save the file as situp14inter'68t html .. under the /var/
,'
rector
simple
interest:,,
ci l r~L P $ R-' ($
'y
'1; V
0
7. Type http://localhost/Simpleillterest.htmi in the address bar 'and press the Enter key. The form appears, as shown in Figure 6.7.
9.
Page 70 of 274
Session 6
CAPTEC
R K
O'LDWI-DE
PHP Operators
10. Enter 5' in the Rfirnber of Years text box. 11. Click
Mozillia
File Edit View Go Bookmarks Tools Window Help . ................. ... . ..... L4 http:/Aocalhost/Si.phllvl ______ ( 4 Back Forward Reload - ch Print ....... .......... . - Sear Home Vj Bookmarks je Red Hat Network (:rjsupport Shop Products 6jTralnlng
f o l I
LZ
't~
Q 09
1 Dom
3. 4. 5.
Save the file as bitwise.php under the /var/www/ht-ml directory. Open the Mozilla Web browser. Type http://localhost/bitwise.php in the address bar and press the Enter key. A output appears, as shown in Figure 6.9.
V 1 . 0 6, c ) 2004 Aptech Limited
Page 71 of 274
Sessocn 6
PHP Operators
ttp:/flocallio
Fonvard
Reload Stop
-h Print
_____________________________________________________________________________________________________________________________________________________
B1 01
U~
. ..... . ....
"6.6 Using' ..the .String OperatorsThe string operators operate on character data. PHP provides two string operators to concatenate two or more strings. For example, to append text to the existing string:
,
W ,
IneW 11
ext"'.1
2. El-60"rIfiii
following
code:
<?php $String = "HELLO"; $String.= " FRIENDS"; echo "$String ......... 3. 4. 5. Save the file as string.php under the /var/www/htm1/ directory. Open the Mozilla Web browser. Type http.- / / localhost /String. php in the address bar and press the Enter key. A page appears, as shown in Figure 6.10.
File Fdit View Go Bookmarks Tools Window Help
7
Back Forward Reload S t o p o /,JHonie )dBookmarks *Red Hat Network 6Support [ j Shop L-'Products 'Training I I I'LL0 FRIENDS ... ""'
3-
hap:1pocalhost/Strin
Search C
C.-D
t:42
Session 6
R L,11) W 1 0 E
ePYWCH
s o t a r e p O H P
-the-Enter
i
j w ., search
L i ______________________________
Reload
411tip:I/localhost/ cren R
S T
'
fl
c--2 i Done
(1AJi7T'ECM
Session 6
WORLD WIDE
PHP Operators
Part II - For the next half an hour: 1. Create a form that accepts the first name, last name, and the basic salary of the employee. 2- Write a PHP script to display the full name and basic salary of the employee. 3. Also, calculate and display Dearness Allowance (DA), HRA, and TAX. The Dearness Allowance is calculated at 2% of the basic salary, while HRA is calculated at 5% of the basic salary. The tax is deducted from the salary based on the range of the basic salary.
4. In addition, calculate the net salary of.the employee using the following formula. Net Salary = Basic Salary + DA+ HRA - TAX
Range
Use the If statement Use the Switch statement Use the Ternary (?) operator
rdd;"
In a programming language, flow refers to the order in which the statements in a program execute. In a program, the statements execute in a sequence, from the first to the last statement. We can use conditional statements to change the order of flow in a program. The conditional statements execute a set of statements only when a specified condition is satisfied. Conditional statements are also known as control statements as they control the flow of the program. In this session, we will learn how to use the different types of conditional statements, such as if and switch statement. In addition, we will also learn to use ternary operator in PHP.
7.1 if St lt
The if statement executes a block of code only when the specified condition is true. If the condition is false, the block of code is ignored. For example, a registration form gets accepted only if a user specifies the full name and email address_ Thesyntax for if statement is:
if (condition) Code execuLes if the condition is true;
The if keyword is followed by the condition in parentheses. The condition is the test expression
consisting of variables and operators- If the condition is satisfied, the code in the if body
i8
Page 75 of 27,11,
Sessi n
APTIECH WO R L D.W 1 0
Conditional Statements in PHP
</body> </html> If more than one statement is to be executed when the condition is true, we must enclose the statements within the curly brackets. For example, to find and display the bonus at the rate of 10% and total salary when the salary of the employee is greater than 8500: <html> <body> <form action="salBonus.php" method="GET"> <table) <tr> <td>Salary </td> <td><input type="text" name="sal"></td> </tr> </table> <br> < input type="submit" value="Submdt"> < / f orL rr> </bodv> </html> Save the above code as SalBonus.html. To process the salary, use the following PHP code: <?php $sal=$_GET['sa].']; echo "Salary before bonus echo ssal; echo "<br>";
10
$";
Page 76 of 274
(APFECH
Session 7
WORLDWID E
Conditional Statements in PHP echo "<br>"; $sal = $sal + $bonus; echo "Total Salary : $$sal";
Note if the salary of the employee is less than 8500, the statements within the curly brackets are not executed. The statement that follows the closing curly bracket (1) will be executed. We can execute a block of code when the specified condition is false. This can be done using the else statement. The else statement is used along with the if statement. The syntax for if...else statement is:
-if (condition),, Code executes if the condition is true else Code executes if the condition is false
For example, to calculate the commission at the rate of 10% when the sale is greater than 20000 and at the rate of 5% when the sale is lesser than 20000. The following code calculates the commission:
if'($sales > 20000) $comni = $sales * .1; echo "Cormision $$coaun" else($sales < 20000) $comm = $sales echo "Cormision .05; $$conun";
In the above code snippet, the $sales variable stores the sales amount and the $comm stores the amount of commission. When the sales amount exceeds 20000, the program executes the -- f statement and calculates commission at the rate of 10%. When the sales amount is less than 20000, the program executes the else statement.
V 1.0 2 0 0 4 Aptech Limited
Page 77 of 274
(A-JMFECAr
Session 7
1-!~~
LOW71,0E
We can also use elseif clause along with if statement. The elseif clause is an optional clause that allows testing alternative conditions- It is executed before the else statement. For example, to calculate the commission based on the rates specified in Table 7.1-.
Table 7.1 : Commission Rate based on Sales The following code accepts the sales amount from the user: <html> <body> <form action="SaleComm.php" method="GET"> <table> <tr> <td>Total Sales </td> <td><input type="text" name="sal"></td> </tr> </table> <br> <input </forni > </body> < /h L Save the above code as SaleComm - htm]. To process the sales amount and calculate the commission, use the following PHP code: <?php $sal=$GET['sa1.']; echo "Total Sales echo $sal; echo "<br>"; if
($Sal >
="submit" value="Submit'>
50000)
Sales
Commission Rate
Session 7
WORLDWIDE
APTIECIf
$$comm";
elseif ($sal > 20000 and $sal <= 50000) $comm = $sal * .07; echo "Commission echo "<br>";
$$comm";
else ($sal < 20000) $comm = $sal * .05; echo "Commission echo -<br>";
I
$$comm";
In the above code, commission is calculated according to the sales amount that the user enters. For example, if the user enters 55000, PHP displays the following message:
$55000 $5500
We can also specify if statement within if statement or else statement. These are known as nested it statements. For example, to calculate the electricity charges based on the units specified in Table 7.2: Units Above 1000 Greater than 500 but less than equal to 1000 Lesser than 500 Rate($) 3 2 1.5 Table 7.2 : Electricity Charges based on Units Also, add service charges at the rate of 10% on the electricity charges paid when the amount exceeds 2000.
Page 79 of 274
W O R L D W I D E
Sessuon 7
14PTECH
Conditional Statements in PHP
I I I I I I I I I I I I I I N W , ___________________________________________________________________________________________________________________________________________
</td>
Save the file as elecBill.html. To find the total electricity bill, use the following code:
<?php $units=$_GET['units'1; e c h o "Number of Units con s u me d echo $units; echo "<br>"; if ($units > 1000) $rate = $units * 3; $service = $rate echo "Service Charge added for units above 1000 echo "<br>"; $totalbill = $rate A- $service; echo "Total Electrici t y B i l l : $$ t o ta l bi l l " ; } else if ($units > 500 and $units <= 1000) $rate = $units * 2; echo "Total. Electricity Bill else
I;
$$service";
$$rate";
Page 80 of 274
Session 7
Conditional Statements in PHP $rate = $units * 1.5; echo "Total Electricity Bill
$$rate";
Save the above code as elecBill.php. In the above code, if the user enters 1500, PHP first calculates the rate and stores the value in $rate variable. To calculate the service charge charged on the electricity bill, PHP calculates the service charge at the rate of 10% and store the value in $service. It then stores the total amount in the $totalbill variable. If the user enters number of units as 400, the total electricity bill would be calculated at the rate of 1.5. The output would be, Total Electricity Bill $600-
switch(variable) case valuel: Code executes if condition equals valuel break; case value2: Code executes if condition equals value2 break; default: Code executes value
The switch statement is followed by the variable in parenthesis. The case keyword is followed by a case constant. The case constant can be an integer or string constant. The data type of the case constant must match the data type of the switch variable. Before entering the switch statement, program must assign value to the switch variable. The switch statement implements the code statement by statement. The switch statement executes the code only when the value of the case statement matches the value of the switch variable. PHP continues to execute the statements until the end of the switch statement or until a break statement.
Page 81 of 27,1
1 . 0
O c
2 0 0 4
A p t e c h
L i m i t e d
APT,ECH
WORLOWIVE
Conditional Statements in P H P
The break statement is used to move the control to the statements following the switch statement. If the break statement is not used, PHP executes all the statements including the statements of the following cases in the switch statement. The default is the special case. It is used when none of the case statements matches the value of the switch variable. We must place the default case after all the case statements in the switch statement. For example, in the following code there are no break statements:
<?php $day = $GET['day'l; switch ($day) case 1: echo "It's Sunday"; case 2: echo "It's Monday"; case 3: echo "It's Tuesday"; case 4: echo "It's Wednesday"; case 5: echo "It's Thursday"; case 6: echo "It's Friday"; case 7: echo "It's Saturday"; default: echo "There are Seven Days in a Week";
In the above code, if the user enters 4 as the week day, PHP first matches the case value that the user enters. If the user enters 4 as the week day, PHP displays the message related to case 4. It also displays all the messages related to the subsequent cases till it reaches the end of the switch statement. The break statement instructs PHP to stop its action and come out of the switch statement. The statements following the switch statements will be executed. The above code with a break statement:
<?php $day
$-GET[ 'day'] ;
V 1.0 Cc., 2004 Aptech Limited Web Scripting with PHP
Pag
e 82 of 274
Session 7
WO R-L DWI D E
ARY'ECH
Conditional Statements in PHP switch ($day) { case 1: echo "It's Sunday"; break; case 2: echo "It's Monday"; break; case 3: echo "It's Tuesday"; break; case 4: echo "It's Wednesday"; break; case 5: echo "It's Thursday"; break; case 6: echo "It's Friday"; break; case 7: echo "It's Saturday"; break; default: echo "There are Seven Days in a Week"; break;
In the above code, if the user enters 4 as the week day, PHP displays only the message related to case 4- If the user enters any other value apart from numbers between 1 to 7, PHP displays There are Seven Days in a Week.
7 . 3 T e r n a r y ( ?) O pe r a l h b r - ' : '
Ternary operator is also known as conditional operator. It simplifies complex conditions into one line statements. The syntax for the ternary operator is: Terml ? Term2 : Term-3; . Ternary operator requires three operands. It evaluates the condition specified in -Ter.mi and returns '1,erm2 if the condition is true and Term3 if the condition is false.
Page 83 of 274
Session 7
( *
For example, consider the following code snippet with the ternary operator:
(7 == 7) ? "Yes"
"No"_
In the above code snippet, Term1 includes an expression where number 7 is compared to 7. The value of Term2 and Term3 is, Yes and No. Ternary operator is considered as a shortcut for if. ... else statement. Note the following code where the two variables are compared and the greater number is displayed using if .. . els e statement:
<?php $x = 100; $y = 50; if ($X > $Y) echo "X is greater than Y"; else echo
I
When the above code is executed, x is greater than Y is displayed. We can display the same output using the ternary operator. To use ternary operator instead of using if ... else statement:
<?php $x = 100; $y = 50; $disp = ($x > $y) ? "X is greater than Y" echo $diso; "Y is greater than X";
Session 7
(APrECH
DW10a
Conditional statements change the order of flow in a program. Conditional statements. execute a set of statements only when a specified condition is satisfied. I The i f statement executes a block of code only when the specified condition is true. ),- In a Nested if statement, we specify,if statement within if statement or else statement. A switch statement checks single variable against multiple values and executes a block of code based on the value it matches. The break statement is used to move the control to the statements following the switch statement. The default statement is used when none of the case statements matches the value of the switch variable.
Ternary
Session 7
CA - p r , E r i v DE10 M.
1.
The a. b. C.
if
condition operator variable declaration executes a set of code only when a condition is true.
U.
2. a. b. C. d. 3. a. b. C. d.
4.
If statement Switch statement Conditional statement Ternary operator are used when there are many conditions with discrete values. If statements Switch statements Conditional statements Ternary operators
is used when none of the case statements matches the value of
the switch variable. a. b. C. Ternary operator Switch statement Break statement Default statement
I
5.
d.
PHP continues to execute the statements in a switch statement until the end of the switch block or until it encounters the ____________ statement. a. b. C. If Default Continue Break
d.
Page 86 of 274
V 1.0
Session 7
V 1.0 @ 2004 Aptech Limited
WR W E OL I DD
AF C PE H
C n io a ttm ns P P o d nl ae e t i H t S n
Page 87 of 274
Objectives
At the end of this session, you will be able to:
Use the -if statement Use the switch statement Use the Ternary (?) operator
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:
1. 2.
Open the gedit text editor. Enter the following code to create a form consisting of two fields, Name and Age:
<HTML> <HEAD>
<TITLE>Personal Details</TITLE> </HEAD> <BODY> <1-14>Please enter the information</H4> <FORM> <table> <tr> <td>N,aaie: </td> <td><input type="texL" name="myname"> </td>
Web Scripting with PHP
V 1.0 (0, 2004 Aptech Limited
Page 89 of 274
Session 8
W 0 R L:D'W. UWE
</tr> <tr> <td>Age: </td> <td><input type="text" name= "myage"></td> </tr> </table> <br> <iput </FORM>
="submit" va;~e='~,.Submit">
nse le
acute
Ah A' ID t%
is
MIRI
Copy
<HTML> <HEAD> <TITLE>Personal Details</TITLE> </HEAD> <BODY> <H4> Please enter the information </H4> <FORM ACTION="dispDet.php" METHOD="POST$ <TABLE> - <TR> <TD>Name:</TD> <TD><INPUT TYPE="text" NAME="myname"</TD> </TR>
Ln 8, Col. 41 INS
5.
Page 90 of 274
A R r A E c If
Session 8
Conditional Statements in PHP 6. Enter the following code to retrieve the information from the form and store them in variables:
ec
41
After adding the code, the file appears as shown in Figure 8.2.
V _ U n f i d ' d . I f t o A l f i a Z - j edit, File Edit View Search Tools Documents Help
Nn . X
New Open
J, info.html
Find Replace
Untitled 1 x
!NS
Page 91 of 274
AkEPYHCH
W-Oft
L:D WTV4E
S e s s i o n
8 _________________
Conditional Statements in
PHP
41
8. E ntWihe following code immediately after the if body to check whether the Age field is not left blank:
10.'. Save the file a . ,4: dispDet.php under the /var/www/htmI--': directory. 11. Open the Mozilla Web browser.
1.
12. Type hittp://localhost/info.html in the address bar and press the Enter The Personal. Details form appears, as shown in Figure 8.3. V
File Edit View Go Bookmarks Tools Window Help 4
13
- 3
.1
4' h
ttp:jjocalho51Anfo.J` _ I
;.*Search C-4
G2 T Done
Figure 8.3 : Personal Details Form
Page 92
Of 274
Session 8
WOMILDWIDE
APr,ECM
Print - 1 Home i *4Bookmarks " R e d Hat Network -CTjSupport(!-~,Shop d'Products (:ITraining Please enter your name
Back
3 Back
Forward
Reload Stop
h"p://localhost/dispEl
_,&
C-4
L L .,e- 0 ( S 9 [ D o n e
It
i User Information M ill File Edit View Go Bookmarks Tools Window Help I Back
~.)
--'s O
Forward
Reload Stop
http:ffiocalhostidisr[-j exSearchi
-
Figure 8.5 : Message to Enter Age Details 16. Click the Back hyperlink to return to the form. 17. Enter John in the Name text box and 44 in the Age text box. 18. Click the Submit button. A page appears, as shown in Figure 8.6.
Page
93 of 274
Session 8
V . - -... ~1 ' r n -V
File Edit
W10MV-91WIV-1a
APIFIECH
View Go
-rma onz
girl
I-.,
1-v-11-~"
C-: 1
W -- --W -
Page 94 of 274
Session 8
APMr,M
W 10 it L 0 WIM S
Open the gedit text editor. Enter the, following HTML* code to create a form that accepts the name and grade Of an employee:
<HEAD> <TITLE> Grade Details <iTITLE>. < /HEAD> <BODY>
<H4>. Please enter the information </H4>
<FORM>
<TABLE>
W *k W
.
T R
gt~
S.
V , 4; 0
Y34aMep
xg
(1010
gradEi"></TD>
Session 8
Conditional Statements in PHP
Figure 8.7 : Form Element Attributes Sai(6'the file as 0erks.html under thejvar/www/htmi w--,/btzn3 "directory." Open a new file in the text editor. Enter the following code that retrieves values entered by the user in the PHP variables: <HTML> <HEAD> <TITLE> Grade Details</TITLE> </HEAD> <BODY> <?php $myn.ame=$GET['myname']; $myg-rade=$GET['mygrade'1;
id-4, 6dified
Sessi n 8
WORLDWIDE
PrIECH
Enter the following code after the if block to check whether th"rade field Is left bidblank:
else switch ($mygrade) cas
echo. $inyname;
echo. * break"-,--
you
id .
n,
6.1
ode
W111-;~W.;::-**17111
F~ l
E 3
New Open Save Print Undo Redo Cut Copy -Paste Find Replace perks.htmlOx !.~. __ . .1 untitled 1* x I
case echo Smyname; echo ", you did not enter your Grade"; break; case A: echo "Facilities for $myname (Grade A)"; echo
"<BR><BR>";
echo "Bonus = 20% of basic salary"; echo 1 . <BR> " ; echo "Travelling allowance = $SOO"; echo
"<BR>";
........
Ln 43, Col. 36
INS
AAVT,ECH-
Session 8
W,O R L D'W-1z0'.F
case B: echo "Facilities for $myname (Grade B)"; echo "!5.BR><BR>"; echo "Increment = 20% of basic salary"; echo "<BR>"; echo "Bonus 10% of basic salary"; echo "<BR>"; echo "Travelling allowance = $300"; echo "<BR>"; echo "Medical allowance $300"; echo "<BR>"; -1 break; case:,
echo;, ,I-B ~ < R . ~5 Facilities U. R;B. ..
, .~~-AMMem
v-..
e C ~
ecWM-T
"n r X14 e t 1, n
N
Off.
g allowance $100";
11. Enter the following code to check for any other values that a user enters in the Grade field:
default: echo "$myname, Please enter the correct Grade (A, B, or C)"; break;
12. Enter the following code after completion of the PHP code to create a link that returns the user back to the main form:.
Page 98 of 274
(APrEcff
Session 8
WORLDWID E
Conditional Statements in PHP key in the address bar and press the Enter key. The form appears, as shown in Figure 8.9.
15. Type http://localhost/perke.html.
I'n
File
1
Help
X,
----------
Back
http:/Aocalhost/pe 40 search
C 4
i : , j Home Hat Network C j Support tElShop C , Pro d cs Please enter the information
Name: Enter your Grade (A/I3/C): Submit
CI
L.a'
Lai
ga
(0
BE
Forward
Reload Stop
Done
Figure 8.10 : Message Prompting to Enter the Name
17. Enter John in the Name field.
18. Click the Submit button. The page appears, as shown in Figure 8.11.
ili
File Edit View Go Bookmarks Tools Window Help Back Forward 11 [.47ocalhos Reload Stop http://l t/calc E Search Print
:~15 Home 4 Bookmarks l#-Red Hat Network (:ISupport CtShop j:tProducts CI-Training
John, you
Back ack
ap [ Done
Page 99 of 274
Session 8
W0,R-Lic&,WA0M
A P TIE CIA7
21. Click-Ahe Submit button. The facilities available for Grade A are displayed,asshown in. Figure #A
VG raiil
e','Detal
~ c~zififia-,~---'~~, lsz, M
..
Window Help
.. ;* Search
-a
Forwa rd
Reload
Stop I
[, 4 http://localhost/calcP
($myage=="") ?
Age field AiNleft blank.11ag AhL If the user has not entered the age ,.-:the'-text- after`the ? symbol is
It checks whether. the
.
Ing,
code, - ($1fi
messaoOHI-'$mynam-"e.~'You
4' ~ 4 -
age
Va
" A
".M01,
Operu,thej.Mozilla,.',i dbTbfdWtdr-.
,
File Edit View Go Bookmarks Tools Window Help Back !;} Home John. lieuk LZ G2 Done Forward Reload http://Iocalhost/dispC
s t o p
Search
ED
jShop t: jProducts
jTrainfnq
AWPFIECf-111, ,
S e s s i o
n
O'R'L W UD.E
in
"
I L v
Back
Forward
Reload Stop d k
httilocalhostidisp
Search _______________
(APTECH
Session 8
woRLowIoe
TRY IT YOURSELF
Part II - For the next half an hour: 1. Create a form for an online shopping mall that accepts details such as the customer name, the membership no., the type of membership, and the amount of points in hand. The two types of membership are Basic and Privileged. Create a Job Application form for an organization that accepts the first name, last name, address, phone no., qualifications, and experience of the candidate. It must also display different department such as IT, Finance, and Sales for which the candidate wants to apply. Depending on the department selected, different posts that are available under that department must be displayed on the form. Use the switch statementV 1.0 2004 Aptech Limited
3.
Calculate and display the additional amount of points available and the total amount of points. Use if ... else statement.
-'.
Objectives
At the end of this session, you will be able to:
Introduction
The loop statements control the flow of the statement execution. A loop executes a block of code repetitively- PHP provides us with the loop statements such as while loop, do-while loop, and for loop. The jump statements control the execution of the loop- The different types of jump statements are break, continue, and exi t. In this chapter, we will learn how to use the various types of loop and jump statements.
while
9.1.1,while Loop
A while loop executes the statements in the loop body as long as the condition is true. The syntax for a while loop is:
while(condition) Code executes if the cond.i.U'.orl is L.rue; Code executes if the condition is false;
A 0 rEcm.
Session 9
W,O-WL:*WjWR
expression consisting of variables and operators. If the condition is satisfied, the code in the loop body is executed. If the condition is false, the loop stops and the control move to the statement following the loop.
Some examples of the while loop are:
In the above code, the result is displayed until the counter reaches 10. The loop stops once the counter exceeds 10. To display the odd numbers between 1 and 10: <?php
$number=j_; echo "The odd numbers ar-e:<BR><BR>"; wh_ilc($ni_2inber <= 10) echo "<BR>$number<BR>"; $numbeY-=$nu1--,nbe)_-- 12;
In the above code, the number is always incremented by 2 until the number reaches 10.
9.1.2.-do-whilo.
In a while loop, the condition is evaluated at the beginning of the loop. If the condition is false,
Session 9
Flow Control in PHP
The syntax for a do-while loop is:
do
Code executes if the condition is true; } whil.e(cond-ition); Code executes if': the condition is false; In do while loop, the loop body follows the do keyword. The loop body is executed at least once. The loop body is followed by the while keyword and the condition in the parenthesis. If the condition returns true value, the loop executes. If the condition returns false value, the loop ends p and the statements following the w-hi -- e keyword are executed.
do
loop are:
To display the odd numbers between 1 and 10: <?php $number=l; e c h o " T h e o d d n u m b e r s a re :<B R >< B R >"; do echo "<3R>$numbci--<BR->"; $num1Der=$number+2; 10) echo "<BR>Th(-- value cool-d not- be dis-piayed";
The above code displays the odd numbers between 1 and 10 using the do - w hi l e loop. Before the iteration of the loop starts, the value is displayed once. Then the execution starts. The value keeps displaying until the counter reaches 10. The loop stops once the condition is satisfied. To print the even numbers up to 10: <. P--1P $cc)ljj-ltej,--O; echo "The even numbers ar'e: <BR><BR>" do echo
"
'c
o " 1 I
1I
ze-r'!
1- 1
i
f i e f S c r i p t n g w i t h P H P
V 1.0
' e )
Session 9
Z. L
A for loop enables us to execute a block of code repetitively for a fixed number of times. The loop executing statements keeps executing until the testing condition gets satisfied. Once the condition gets satisfied, the loop stops executing.
The syntax for the tor loop is:
f or (in iti. a l iz at". on; condition; re-initializaL.-ion)
Code executes If the condition is true; } Code executes if the condition is false;
The for loop consists of initialization expression, text expression and re-initialization expression. The condition expression specifies the test expression. The initialization expression initializes the value of the counter. The re-initialization expression increments or decrements the counter. The code inside the loop is executed only when the condition returns true value. The re-initialization expression helps in the iteration of the loop. Some of the examples for the for loop are:
>
$coijnt.-.or <=
6;
$count.er++-) R
i
echo < B R > $ n - n i b e r <113R, u $numbe .r = -: riUmbe r * 2
,
e c h o " V a l u e s c o u l d n o t be ca lc ul a t ed ." ;
In the above code, the f o r loop is used to display the double of the number. The loop executes until the counter value reaches to 6. Once the counter value reaches 6, the loop stops executing. To display the first five odd numbers in the reverse order:
< ?,,.-)hp
echo for
Pa
ge 108 of 274
Session 9
Flow Control in PHP
$ nu abe_ r = $.;L.
be cai-c-ulat-ed.";
In the above code, note the for loop contains the counter, which is initialized at 5. The re-initialization expression decrements the counter every time the for loop is executed.
atement
jump statements control the execution of the loop statements. PHP provides the following jump statements: > > > break statement cont.inue statement exit statement
if ($i.>10)
b r e a k; I ecYio
In the above code. the statement is used with the v o r loop. The condition is specified in the t statement. The statement controls the loop. If the ' O r r a k statement is not used, then the loop will go in continuous state.
V 1.0
,l
Session 9
To check whether the alphabet is a vowel using s-vji.t.-.ch statement: ?php
$a.ioI1aj_-,eL='u' ; switch ($alphabet) case 'a': e c h o " < b R > < B R > The al ph a be t i s a v o we l. break; case 'A': e c h o " < B R > < B R > The al ph a be t i s a v o we l. break;
A PV cars
Flow Control in PHP
case e c h o " < B R > < B R > The al ph a be t i s a v o we l. break; case 'E': e c h o " < B R > < B R > The al ph a be t i s a v o we l. "; break;
case echo '<BR><BR>Thc alphabet is a vowel.."; break; case 'I': e c h o " < B R > < B R > T h e a lp ha b e t is a vo w el . bf c. ak; , (-), : echo "<BR><BR,>The al , :)habet, IS a vowel. break; '0'. echo "<BR><BR>The alphabet is a vowel. break; u'. echo "<BR><BR>The- alphabet is a vowel. break;
case
case
case
Session 9
WO K;L 0 . "OV
In the above code, the break statement is used in the switch statement. The break statement moves the control to the statements following the st^.- , Itch statement. If the break statement is not used, PHP executes all the statements including the statements of the following cases in the switch statement. 9.2.2 continue
Statement
The co ntinue statement is used with the loop statements. It skips the code following the continue statement in the loop body and forcibly executes the next iteration of the loop. This statement is normally used in the nested loops. The continue statement can be used with the if statement, for loop, chile loop, and do-while loop. For example, to display the consecutive numbers from 1 to 10 using the while loop: <?php
$counter = 0; while($counter<10) f $counter++; 4 'L($counter==5) f ec ho "Continues t h e l o op" continue; I echo "$counter<BR><BR>"; e c h o " T h e l o o p e n d s h e r e" ;
In the above code, the continue statement is used in the it statement. Here, the counter is initialized to 0. The loop continues until the counter reaches 5. As the counter increments to 5, the loop skips the if body and executes the next iteration of the loop. The loop continues until the condition becomes false. 9.2.3 exit Statement. The exit statement ends the loop and the control is passed to the statement following the loop body.
Session 9
Flow Control in PHP For example, to calculate the HRA:
<?P11P ssalary=8000;
if($salary<6000) echo "Basic : $salary,--BR><BR>"; echo "Erti p lovees having salary below , 6000 are not entitled to receive HRA. exit; } else echo "Basic $ sa la ry---BR><Da>" 0.2; $hra=$salar y echo "HRA $hra"; }
In the above code, HRA is calculated based on the basic salary. If the basic salary is less than 6000, the if statement exits. If the basic salary is greater than or equal to 6000, HRA is calculated.
A r- 2rEcm
Session 9
ORIL'O WI D F
>
A loop executes a block of code repetitively. A while loop executes the statements in the loop body as long as the condition is true.
>
The do-whil I e loop works similar to the while loop. The only difference between the while and loop is that in the do-while loop, the condition is placed at the end of the loop. A for loop enables us to execute a block of code repetitively for a fixed number of times. The jump statements control the execution of the loop statements.
.1 , 10
The break statement stops the execution of the loop. The control is then passed either to the beginning of the next loop or to the statement following the loop. The continue statement skips the code following the continue statement in the loop body and forcibly executes the next iteration of the loop. The exiL statement ends the loop and the control is passed to the statement following the loop body.
>
Session 9
Flow Control in PHP
1.
The ___________ statement executes a set of code only when a condition is true. a. b.
C. d.
If Switch Conditional while _____________ loop, the condition is placed at the end of the loop. while do-while for
2.
In the a. b. C.
3.
A ______________ loop enables us to execute a block of code repetitively for a fixed number of times. a. b.
c. d.
4.
5.
The a.
C. C.
Objectives
At the end of this session, you will be able to: Use the rah j 1 e loop Use the do-w1211r loop Use the for loop Use the'u.%
.
7 4) statement
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:
30 10.1 Using the while Loap-I
A while loop executes the statements in the loop body as long as the condition is true. We will generate the Fibonacci series using the while loop.
1. 2. Open the gedit text editor. Enter the following code for displaying the Fibonacci series:
<?php $fibl=0; $fib2=1; echo "The fibonacci series echo "$fibl<BR>"; while($sum<15) { echo "$fib2<BR>"; $sum=$fibI+$fib2; $fibl=$fib2; $fib2=$sum; echo "<BR>"; return 0;
3.
<BR><BR>";
Session 10
rECAI
4. 5.
Open the Mozilla Web browser. Type http: / /Iocalhost/fibo.php in the address bar and press the Enter key. The Fibonacci series appears, as shown in Figure 10.1.
n rX
File Edit View Go Bookmarks Tools, Window Help 3 .?,t litip:[Aocalhostj [_____ search! For Reload E
P -
iwt
j
/,IHome 'Bookmarks .4- Red Hat Network C 'Supporl 'sliop 'Products -'Training
i j
5 13 e-9) Done
1. 2.
Open the gedit text editor. Enter the following code to display the first ten odd numbers in the reverse order:
<?php e c h o " O d d n u m b e r s i n r eve r se o r de r :< BR >"; $i=10; do $num=$i*2-1; echo "<BR>$num"; }while (S J >=I )
Session 10
I.T.
Aprr1r.Iff
File Edit View Go Bookmarks Tools Window Help 3 Search 1 crop IDS d Fl~ 1,e,, Back Reload s opi I . at - p:lfioc . alh ---Print ;i Home 'Bookmarks -**-Red Hat Ner"rk ,-j'Support t:Shop -'Products "Training j "Training
Odd
M111111CI-I in rr r r
wder:
19 17 15 Il 97 53
iZ
\ZI Q G
Don
loop enables us to execute a block of code repetitively for a fixed number of times. The
for loop consist of the initialization expression, test expression, and the re-initialization expression.
For example, to display the square of the first ten numbers using the for loop'.
1. 2. Open the gedit text editor. Enter the following code:
< ?phT-)
($i=1;$i.<=10;$-i-j-+)
r
I $ square= $ i * $.i. ;
3.
Web
V 1.0
pa-
Session 10
Flow Control in PHP
5. Type http://localhost/square.php in the address bar and press the Enter key. The output appears, as shown in Figure 10.3.
175: X
File
Edit
View
Go
Bookmarks
.. . .........
Tools
Window
Help
..
F omard
,
' JBookmarks
Reload
Stop
~k_ Search
-'Products L-3
Pnnt 'Training
J
arc I X 1 1
2X2 A
25
Done
The jump statements control the execution of the loop statements. The various jump statements are break statement, continue statement, and exit statement. The break statement stops the execution of the current loop and the control moves to the next loop. The con . tinue statement skips the code following the continue statement in the loop body and forcibly executes the next iteration of the loop. The exit statement ends the loop and the control is passed to the statement following the loop body. These statements are used in the if statement, for loop, while loop, and do-while loop. To display the inverse of a number:
1. 2. Open the gedit text editor. Enter the following code to create a form for accepting a number: <HTML>
I
<BODY>
<FORM METHOD "GET" ACTION
"breakinv.php">
Web
Session 10
WORLDWIDE
<BR><BR> <INPUT TYPE = "SUBMIT" NAME = "submit" VALUE = "INVERSE"> </FORM> <BD>BD> /OY OY </HTML>
3. 4. 5. Save the file as break.html under the Open a new file in the text editor. Enter the following code to display the inverse of the number:
< ? p h p
/var/www/html
directory.
$number=$_GET['num'1; if($number==0) f
exit;
6. 7. 8.
Back
13
Print
j Training
Home j Bookmarks
I =mcr nu whet: i
INVERSE
Done
Session 10
Flow Control in PHP 9. Enter the number as -7.
10. Click the INVERSE button. The page appears, as shown in Figure 10.5.
M6
X
Window Help
File Edit View Go Bookmarks . . ... 7--.7 . .. .... Tools ---------........ ............ Back For ard Reload
4 http:/Pocalhos Li
H
reakinv.r
_;A-.
Search
Nrr
r'
9
-- 4 &
Figure 10.5 : Displaying the Inverse Number 12. Click the 13.
Go Back hyperlink.
Enter 0 in the text box and click INVERSE. Note a blank screen is displayed.
Sess~oirll 10
(A'PF,EC,N WORLDWIDE
Flow Control in PHP
TRY IT YOURSELF
Part II - For the next half an hour:
1
(APywcw
Session 11
woe
L-D W IV E
Functions in PHP
11.2.1 Mathematical F ti
Mathematical functions operate on numerical data. Table 11.1 lists and describes some of the mathematical functions:
11 ;
Note the above code will return 100 as the nearest integer.
Description
Sessi
n 11
(APrECH
\ !!O~R LDWIDE
<?php echo "The largest number from 99.9, 9.9999, and 99.99 is: echo max(99.9,9.9999,99.99);
Note the above code will return 99.99 as the largest value. To find the square root of the number, 256:
operate on character type of data. Table 11.2 lists and describes some of the
V 1.0 U 2 0 0
Aptech Limited
Functions in PHP
(A_PY',ECAf
Session 11
WORLD W1-DE
Functions in PHP Some of the examples for the string functions are: To find the length of the string, HELLO:
< ? p h p
echo "The length of the str i ng HELLO . is:" echo strlen(HELLO); Note the above code will return 5. To convert a string to the lower case: <?php echo strtolower(PHP); Note the above code will display PHP in the lower case. To find the ASCII equivalent of the letter, A: <?php echo bin2hex(A);
Fun ctio
(APYWCH
Sessin 11
= L-OW I De
Functions in PHP Some of the examples of using the date and time functions are: `r To obtain the day: <?php echo date("l"); Note in the above code the "I" is the argument string, which corresponds to the textual representation of the day of the week. Above function will return the dayTo display the current month: <?php $A=getdateo; $month=$A['month']; echo $month;
(error _msg
_ r g o e e Constant) PHP provides many levels of errors_ We can use this function to set a level d ring the r n time of the script
("aFran
Sess~on I I
!oR. L D W I-WE
Functions in PHP
The e r r o r_ r e po r t i ng o function requires constants as arguments. Table 11.5 lists and
Table 11.5 : Error Constants Some of the examples for the error handling functions are: To report only the simple errors that are running: <?ph-,)
$A=errorreporing(EERRORIEWARNINGIE_P,ARSE); echo $A;
Note the above code displays the errors depending on the constants used as arguments. To generate a user-defined error: <?php
$num1=0; if(num1==0) tr igger e rror("Cannot divide by zero", E_USLR_ERR0R); else $B=100/rIUMI;
Note in the above code the value of $nurnl variable is tested. Since the value of snuini is
equal to zero the code in the if body is executed. Constant Name Description
(.-4PT,ECJV
Session 11
WORLDWIDE
Functions in PHP
-dined Functions Fu
A user can also define a function. A function has to be defined before it is used. The function definition contains the code for the function. The syntax to define a function is:
f_nction code
Z _ .~
fun name(
The function keyword is followed by the function name. In the above syntax,
> >
funname - Specifies the name of the function code Specifies the body of the function
-nnameo;
Where fun nameis the name of the function Some of the examples for creating a function are: > To create a function that calculate the sum of two variables, enter the following code:
<?php function addition() $A=100; $3=200; $C=$A+$B; echo "The sum of 100 and 200 is. $C"; addition(};
Note in the above code the addition( ) function adds the variables $A and $B and stores the value in $c.
Page 129 of 274 ~~-ipting with PHP V 1.0 2004 Aptech Limited
CA1 T C O - 0 E H RLDWIDE
Session 11
Functions in PHP To create a function that displays the text, enter the following code: <?php function Display() echo "LEARNING PHP IS FUN"; Display(); Note in the above code when the Display() function is called, the sentence is displayed.
Session I I
V 1.0 (q) 2004 Aptech Limited
rEcIff DWI'DE
Some of examples of passing the argument by value are: To create a function for calculating the square of a number, enter the following code: <?php function Square($A) $A=$A*$A; echo $A; } $A=5; echo "The square of $A is: Square($A);
Note in the above code, we have passed the argument by value_ The variable $A is passed to the Square ( ) function, which multiplies $A with $A and stores the resultant in the same variable. The output displayed is 25. Now when we display the value of $A outside the function,5 is displayed instead of 25. This is because the execution of function does not affect the value of the variable outside the function. To create a function that subtracts one variable from another, enter the following code: <?PhP function subtraction($A,$B) $C=$A-.$B; echo " The difference of $A and s u b t rac
t
L-
B is: $C";
i on (9 0, 4 5)
Note in the above code, we pass two arguments to the function subtraction() -The subtraction ( ) function subtracts the variable $B from $A and stores the value in $c.
ARTECIff
Session
WO R LOW4 0--E
Functions in PHP Some of examples of passing the arguments by reference are: To create a function for calculating the square of a number, enter the following code:
<?php function Square(&$A) $A-.$A*$A; echo $A; $A=5; echo "The square of $A is: Square($A);
Note in the above code, we have passed the argument by reference. The variable $A is passed to the square ( ) function, it multiplies $A with $A and stores the resultant in I the same variable. The output displayed is 25. Now when we display the value of $A outside the function, the output will be 25. This is because the execution of function changes the value of the variable even outside the function. To create a function that calculates the product of two variables, enter the following code:
<?php function multinlication(&$A,&$B) $C=$A*$B; echo "The multiplication of $A and $B is. $C"; } $A=25; $B=30; multiplication(SA,$B);
Note in the above code, we pass two arguments to the function multiplication H.The mul ti-ol. ication function calculates the product of two variable $A and $B and stores the value in sc.
Session 11
AAPFECH 0 R L D. W I -DAr
.
Functions in PHP For example, to create a TA salary: function for calculating the traveling allowance based on the basic
Note in the above code, the TA ( ) function calculates and displays the traveling allowance. It calculates the traveling allowance at the rate of 25% on the basic salary.
Note in the above code, the HRA ) function returns the house rent allowance, calculated at the rate of 25% of basic salary. The return $HF-A statement returns the HRA. The above code returns 5000.
Session 11
WfOAMMM48M.
Functions in PHP
For example, we will define a function named NetSalary (), which in turn calls functions, such as HRA () , TAX() , and DA(). . <?php $Ba.sicSa.1=20000,function HRA($Basic_Sal) $HRA=0.3*$Basic_Sal; return $HRA; function TA($Basic_Sal) $TA=0.25*$Basic_Sal; return $TA; function TAX($Basic_Sal) .$HRA=0.1*$Basic_Sal; return $TAX; function Net_Salary($Basic_Sal) $A=HRA($Basic_Sal); $B=TA($BasicSal); $C=TAX($Ba.sic_Sal); SNetSal=$Basic_Sal+$Ai-$B-$C; echo "Your Net Salary is: echo $-NetSal; Net_Salary($Basic_Sal);
Note in the above code the Net_ TAX ( ) . The NetSalary three functions_
O function calls three functions, HR.=. () , T ( ) , anc function calculates the net salary using the values returned by the
Recursio
Wehave seen that one function can call another function. Also a function can call itself. Whea function calls itself several times, the process is termed as recursion. When a function calls itself the same code is repeated. For example, we can use recursive functions in programs tc calculate the factorial and Fibonacci series.
Session 11
Ei
-Pr'ECITOARLDM10
R
Functions in PHP
For example, to use a recursive function for calculating the factorial of a number:
< ? nho $A=4function factorial($A)
return 1; I else
In the above code, the factorial() function returns 1 if the input is 0 or 1. Otherwise the factorial () function will call itself to calculate the factorial. Above function will return 24.
We can also use non recursive function instead of recursive function in the above factorial example. In a non recursive function we have to use a loop instead of recursion. There are instances where a recursive function is simpler to code than a non recursive function. The code written by using the recursive function is easier to understand. The recursive functions also have the disadvantage that they sometimes require more time to execute as against the non recursive function.
Session 11
WO R-LO W 10 E
A 0 FIECH
Functions in PHP
Functions are used to avoid rewriting the codes again and again.
We have built-in functions in PHP. The built-in functions can be categorized as: I
Mathematical Functions String Functions Date and Time Functions Error Handling Functions Database functions Array functions Mail functions
Mathematical functions operate on numerical data. String functions operate on character type of data. Date and time functions enable us to find the date and time on the system.
I
Error handling functions enables to define the error handling rules We can also define a function. We can pass arguments to a function. We can pass arguments to a function by value, reference, or even pass default values to a function. Recursive functions calls it self. - )~Recursive functions are simpler to code-
c3ession
A p r E c m WORLDWIDE
Functions in PHP
periods underscore
d.
The ___________ function returns the ASCII value of the first character of the string.
a. b.
C.
ord
3.
4.
generates an user error generates the PHP back trace sets a user function to handle errors in script
5.
remains unchanged outside the function changes outside the function remains constant inside the function sign to pass the arguments by reference to the
6.
We use the
a.--ec
Session 11
WOIM'D-,WI'DIE
A P.MCK
Functions in PHP
Recursion is a. b.
C.
one function calling another function several times a function calling itself number of times
Objectives
At the end of this session, you will be able to: Use the built- in functions
>
Create the user- defined function Pass arguments to a function Return values from a function
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:
n ' 1 2 . 1 U P s~r n ,g - A d M a f l f f l e % a tW - 0 I F U n a t o n s
PHP provides built-in mathematical functions that operate on numerical data. For example, to accept a number and dis lay the square root of the number using the PHP script:
p
1. 2.
Open the gedit text editor. Enter the following code to create
<HTML> <BODY>
<FORM M E T H O D = G E T ACTION "Squareroot.php"> Enter a Number: <INPUT TYPE="TEXT" NAME="n1text"> <BR> <BR> <INPUT TYPE="SUBMIT" NAME = "SQUARE ROOT" VALUE=". - $QUARE ROOT"> </BODY> </HTML>
3. 4. ..Save the file as Squareroot.htmi under the /var/www/htmi directory. Open a new file in the text editor.
1 . 0
C c)
(APrECR
Session 12
INOR LOWIDE
7'g
:',',GET n1text
p,,_square. root of
qrt ($A) ;
;A is:ff;
Je;
nn':514
mozlula
4 http:/P(
.Wlklwl~x
V. O 1 c 0
Figure 12.1 : Square Root Form 9. Enter 64 in the Number text box.
in I'X File Edit Viewookmarks Tools Window Help 9jo P .1 L ~ ~n~.JflocalhosV.J~j & * S . r c h l . 2 Back Fon%ard Reload Stop Print Home o V4Bookmarks 4#- Red Hat Network 2tiSupport L-'jShop Products EjTrainnq The square row of 64 is:
8
10. Click the SQUARE ROOT button. The output appears, as shown in Figure 12.2.
....... . ... .
Session 12
APrEciv WORLDWIDE
Functions in PHP
1. Open a ri 3.
< ?php
40qWM
13
'
k i
Sessi n 12
For example, to display the current time in seconds using PHP script: code
(A-PrEav WORLDWIDE
TOW 1087570279
Mao, 4 0
Done
-------- -. .............
function?
V 1.0 2004 Aptech Limited Page 142 of 274 Web Scripting with PHP
A p r E C H
S.ession 12
RLDWIDE 0O~
Functions in PHP
nio a
~eoutputappears !a
4 http./fiocalh
. . . . . -. .-----------.....
Session 12
Functions in PHP
ENTER THE FIRST NUMBER: < INPUT TXPE= " TEXT" NAME= "numl text " > R-
5.
07M
Multipl
Flle Edit View Go 'Alookmarks Tools Back Forward Reload Stop ____________
aa Search Print
.1 Home Y4Bookmarks ,Red Hat Network EtSupport (i Shop EjProducts CATraininj, THE SECOND NUMl3EJZ:F_
MULTIPL
64PTECIf
Session 12
ORLDWIDE
Functions in PHP
..`,'_-.Enter 62 as the first number. Enter 66 as the second number. 10. ,Click the MULTIPLY Ibutton_ N 7............... ..
s i
File Back
Bookmarks Tools
Stop
------
Reload
fjjHome
ii
!Wm
<HTML> <BODY>: <B>Using function to .-.,I)A< B> <FORM METHOD= ET ACTION "Dearnessallowance.php"> ENTER YOUR BASIC SALARY: <INPUT TYPE="TEXT". NAME="num1text"> <BR><BR> <INPUT TYPE="SUBMIT" NAME "DEARNESS ALLOWANCE" VALUE=" DEARNESS ALLOWANCE"> <BR> </BODY> </IiTML>
--
Scripting
with PHP
S e s s i o n
1 2
WORLDWIDE
A P21Y clif
Functions in PHP
o calculate
ess,,,A1U
MN IRA
r.ce-.
A
.w.
V-NA~
r.0
-e
M1
............................................................... --,.; - - - - - - - - - -
X7
Window Help
~%,,Search
.File
Back
\3 ttp:j/l(j' Forward
h
e
.,j Home 1
DEARNESS ALLOWANCE
Done
10. Click the DEARNESS ALLOWANCE button. The output appears, as shown in Figure 12.9.
('A'Pr'EC'ff
Session 12
0 RLDWI WE
Functions in PHP
example, to create a function that has default values for its arguments: Open a new file in the text editor. Enter the following code to calculate the sum of 50 and 100: <?php
1. 2.
function addition($A=50, $B=100) { $C=$A+$B; .echo " The addition of $A and $B is: $C"; } addition();
3. 4. 5. Say.e the file as Additi6n:.php under the /var/www/html. Open the Mozilla Web browser. Type http: / / localhost /Addition. php in the address bar and press the Enter key. The output appears, as shown in Figure 12.10.
.-.
V 1. 0 ( 0 2 004 Ap te ch L imit e d
1 Fil Edit Vi
G B k
k T l Wi d
Session 12
(APmcm
WORLDWIDE
Functions in PHP
ues from
A function can return values. The return statement returns the value from the function. For example, to return the cube of a number from the function: 1. 2. Open a new file in the text editor. Enter the following code to create a form that.accepts a number: <HTML> <BODY> <FORM METHOD=GET ACTION "Cube.php"> ENTER -THE NUMBER:_ <INPUT TYPE="TEXT" NAME="n1text"> <BR> <BR>,: <INPUT. TYPE=,'ISUBMIT" NAME "CUBE" VALUE="CUBE"> <BR> </BODY>. 11 </HTML> 3. Save the file as cube.htmi under the /var/www/htmi directory.
File
Session 12
(APYWCH
~,W" LD-W-I 0 E
Functions in PHP
i4-
sz 0 W
11
z4fi...
1Session 12
WORLDWIDE
Functions in PHP
31
! a H o m e 1
V$ '..
\3 ' ' L
4 http://localh
4* Search
G4 Print
Session 12
a with PHP V 1.0 2004 Aptech Limited
~~rEe~ LDWIDE
H P s o i t c n u F
Page 151 of 274
3. 4. 5.
Save the file as - Fibonacci.php under the c' Open the Mozilla Web browser.
htmi directory.
Type http://localhoet/Fibonacci.html in the address bar and press the EntW key. The output appears, as shown,in; Figure .12.13.
Back
Forward
I
41
!3
0
Home 4Bookmarks
Tr
~/~YrCHWOR W LD I
Session 12
Functions in PHP
TRY IT YOURSELF
Part II - For the next half an hour: 1. Find and display the minimum number from the following: 55.5, 5555.5, 5.55555555, and 555.55555 2. 3. Find and display the length of the string, WECLCOME. Create a form that accepts the principal amount. Create a user-defined function to calculate the compound interest.
V 1.0 (c) 2004 Aptech Limited Web Scripting with PH:
Objectives
At the end of this session, you will be able to:
Define an array Create and use arrays Merge arrays Use single and multidimensional arrays Use array- related functions
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.
I--
Session 13
value)
Using the array() function, we can initialize both indexed and associative arrays. Indexed Arrays An indexed array is an array where the index type is integer. By default, PHP creates an indexed array, if the index type is not specified at the time of creating an array. The index value can start with any integer, such as 1, 20, or 123. To create an indexed array named department: $department = array (1 => 'Purchase') 'Finance', 2 => 'Sales', 3 `HR/ , 4
In the above code snippet, the array Index type is an integer. Note the index value starts from 1. The department array contains three values, Finance, Sales, and HR.
(APrECM
Se
Working
with Arrays To view the value of the first element, enter the following: echo $departmenr-[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:
s
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 $dcpartment["c"]; Note the result of the above code would be HR.
?,.- -:
V 1. 0 0 ) 2 004 Ap te ch L imit e d