Вы находитесь на странице: 1из 152

Es:iciriErcAr

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.

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

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.

1.3 Introduction to PHP. tools and Setup.


PHP tools are used for developing and designing a Web page. These tools are the programming text editors. PHP tool contains all the supporting features for the fast development of Web sites. The tools that are used for developing dynamic Web pages under Linux environment are: PHPEd Uses Linux platform as well as in Windows platform. It is available with version 3.3. It has an integrated development environment for PHP. It is freely available to the users. This tool helps in developing applications by supporting PHP scripts and its syntax.

Page 3 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

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.

1.4 - Writino: a Simple

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.

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

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^

Web Scripting with PHP Page 4 of 274

5. b

Open the Mozilla Web

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

[T iDate is: Rin 22 2004 The 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.

Open the gedit text editor. Enter the following code:


<IITML> <BODY>

<?php echo "Hello Everybody";


</BODY> </HTML>

After entering the code, the text editor appears as shown in Figure 1.3.

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

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

. .... ..... .

Print

Undo Redo

Cut Copy Paste Find

untitled i * x

<HTML> <BODY> '<?php echo "Hello Everybody"; </BODY>

.. n .7, Col. 8 . ........ . .

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

File Edit View Go Bookmarks Tools Window Help Back


f

1-1

a Home Xf Bookmarks elled Hat Network (:,,~Support (:Shop 67 Products (]6`rraining


Hello Everybody

(32

Done

jk---

-- ---- ---

.................... . ........ ......... L

1-;D=,

Figure 1.4 : Displaying Text

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

Page 7 of 27^

(APrEciv

Sessi

In

~-R L!D W.1 D-E

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

406 R6d&4Cut Copy Paste Find

llntitledai4s,~~

<HTML> <BODY> <?php echo $ s t r ; </BODY> </HTML>

$ s t r = "My name i s Samson";

Ln 6, Col. 11

INS

Figure 1.5 : Using a Variable


In this example, the text is assigned to the variable named str. The second line provides the content of the variable str to the echo command. The echo command displays the contents of str variable.

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.

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

Page 8 of 27^

Sess~on I

."L A) LWAOlz

Introduction to PHP

Figure 1.6 : Displaying the Content

07"'N'7

to

Headers te HITV adors

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.

To use a simple header () function, the syntax is:


v o i d h e a d e r ( ' s t r i n g s t r i n g ' )

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

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');

I . . .. ....... ....... .. . ....... .

; 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

. ;

..- ah p . e m a n g ,& http:jAocalhost/st6n * S'h a e c R


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

1.5.1 replace Option


To use header () function with replace option, the syntax is: void header ('string string', boolean replace) Where, replace option replaces or adds header to the document.

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

2004 Aptech Limited

h o

Session 1

(APrEcff 0 R L D W : 1 0 Z

Option 1.5.2 http rcitponse, codeb

To use header() function with http_response_code option, the syntax is:

void header (httpresponse_code)


Where, httpresponsecode shows the response of the Web server on any request, such as the status or the location of the client. For example, to show the status of the client:

<?php header("HTTP/1.0 404 Not Found");

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:

<?php header("Location: http://www.msn.com"); exit;

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

Go Bookmarks Tools window . yelp

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

Careers & Jobs Dating & Personals Entertainment


g

Autos

Ccr sc: A
-d., WLd c uon ti[c . Owl be a g) mi-k

I
.....

cl G2

Done

Figure 1.7 : Displaying the client location


WcwP ergiP bt tH Sh p ii n Web Scripting with PHP V 1.0 @ 2004 Aptech Limited

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

V 1.0 2004 Aptech Limited

Session 1
Introduction to PHP

PHP works in _______ language and uses

tags within it.

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

xored PHP tool works on the ___________ platform. a. b.


C.

GNOME Linux Dreamweaver Eclipse

d.

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

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

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

Page 14 of 27^

Form Handling in PHP

2.2 Using Methods


The Method attribute enables us to specify how data must be sent to the URL. It enables us to control the process of data transfer to the Web server in the URL. There are two types of methods, GET and POST.

2.2.1 The GET Method


The GET method specifies the Web browser to send all the user information as part of the URL. In this method, a question mark is added at the end of the URL. This question mark indicates the ending of the URL and the beginning of the form information. This information on the form is transmitted in the structure of name/value pairs to the URL. The GET method passes the variables to the Web page by appending them at the end of the URL. Consider the following example: ?Name=john In the above example, Planets is the name of the field and earth is the value entered in the field. The question mark (?) symbol specifies to the browser that the element after it is a variable. For example, this value will .be specified to the URL as follows: http://www.lnformation.com/text.php?Name=john The browser automatically appends the information to the URL when the page request is send to the server. Multiple name/value pairs can be sent to the URL by separating each pair with the ampersand (&) sign. The name/value pairs are similar to variables. Once they are on the Web server for processing, PHP make them available as variables. The name/value pairs sent to the URL is a query string. Consider the following example: ?Name=john&age=18 In the above example, the name/value pairs are by the ampersand (&) sign. For example, this query string will be passed with the URL as follows: http://www. Information.com/text.php?Name=john&age=18 The GET method is used to transfer limited amount of information.

2.2.2 The POST Method.:


The POST method specifies the Web browser that all the user information is sent through the body of the HTTP request. This method has the capacity to transmit more information through the

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

Page 15 of 27^

Session 2

WORLDWIDE

Session 2

Form Handling in PHP


WORLDWIDE

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.

2.2.3 Difference in the GET and POST Method


The GET and POST methods work almost identically. The main difference is the way the information is conveyed to the server. The GET method sends information through the URL whereas the POST method sends information through the body of the HTTP request. In GET method, there is less security because all the users are able to view the transmitted information in the URL. In the POST method, the information is not visible to all the users. This helps to provide security. In the GET method, less amount of information is transmitted as compared to the POST method. The GET method retrieves the information whereas the POST method manipulates the information on the Web server.

2.3 Retrieving Data .Using the GET Method


PHP uses variables to pass multiple data to a script- The way data is retrieved changes, depending on the method used to send the form data to the Web server. The syntax to retrieve the data if we have used the GET method is:

$varname
Where,

$_GET['variable'];

varname - Specifies the name of the variable in which the data is to be stored

SGET['var fable' ]- Specifies the name of the input variable


For example, to retrieve the form data in the PHP script using the GET method: 1. Open the gedit text editor.

Page 16 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

(',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

Save Print Undo Redo Cut Copy Paste Find Replace

<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

Figure 2.1 : Creating the Personal Details Form


Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 17 of 27^

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.

Save Print Undo Redo Cut Copy . Paste Find

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

Figure 2.2 : Using the GET Method to Retrieve the Data

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

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 2

APIIECH A Ww'uo a
W 0'R L

1 . 0

C O A

Form Handling in PHP


Xr
File Edit View Go Bookmarks Tools Window Help

Back l Home

Forward

Ys Reload Stop

hit 1 3411ocalhost/PersonalDet;t

Search ]

Print

"Red Hat Network (:,jSupport g. Shop L~jProducts (ItTraining ' IdBookmarks

ENTER YOUR PERSONAL DETAILS FIRST NA.\.11-:: LAST NAME:

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

File Edit View Go Bookmarks Tools Window Help

\3

Back

FoiWard Home '4Bookmarks

1 http:/flocdvI 4 Reload Stop


-

15,

C: :1

L Search Print Red Hat Network (:, ,ftsupport aft-.Shop ( 2 ~


p

roducts

(S

iTrain

YOUR PERSONAL DETAILS FIRST NAME: John LAST NAME: Simons ADDRESS: 32, Park Street, New- Jet---&!v CONTACT NO.: 45450
Done

[7

Figure 2.4 : Displaying the Personal Details

Page 19 of 274

Session 2

('APrEcjv
WOR4D W4 D E

Form Handling in PHP

2.4;Retrieving: Data Using

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 .

Untide4,'I-(Modiried).-.'gedit,. fdIt Mew s ea r c h Tools


.. .. ...... .

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

Cut Copy Paste


.. . .. . . . . . .. . . .. . . . .. .

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

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 2

(APrircff ORLDWIDE
--1

Form Handling in PHP


echo echo echo echo "EMPID: $A <BR>"; "NA14E: $B <BR>"; "DEPARTMENT NAME: $C <BR>"; "EMAIL: $D <BR>";

After entering the code, the text editor appears as shown in Figure 2.6.
%I

File Edit View Search

Tools pocuments help

New Open

Save Print Undo Redo Cut Copy Paste Find Replace

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

Figure 2.6 : Using the POST Method to Retrieve the Data


6, 7. 8. Save the file as EMP_DETAILS.php under the /var/www/html directory. Open the Mozilla Web browser. Type http-.Hlocalhost/EMP_DETAILS.html in the address bar and press the Enter key. The form appears, as shown in Figure 2.7.
~t~yee Details =:MOZilla -'

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,-

Figure 2.7 : Form for Accepting Employee Details


W eb Scripting with PHP
V 1.0 Oc

2004 Aptech Limited

Page 21 of 274

EfEPTEC
ORL
W I U I

Session 2

9. 10. 11. 12. 13.

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

http:/AocaJhostfEMP- DETA11jBack Forward Reload Stop-

ai,Search Sh O P Eftl ` f O d u c ts EtT raining

Print

_IL H=e I *Bookmarks j*-Red Hat Netmrk C`y Sup p o r t (6,


YOUR PERSONAL DETAILS EMPLOYEE ID: A05 NAME: Peter Taylor DEPARTMENT NAME: IT EMAIL: peterA05@fiinfotecli.com

~-~65'jl

Figure 2.8 : Displaying the Employee Details

2.-S . - 'Using : :Hidden Fields'


Sometimes we pass the information from one Web page to another without any interaction from the user. A hidden form field enables to pass information to the Web server. Hidden field is similar to the text field- The difference is that the user cannot view the hidden field and its contents. To view whether the form contains the hidden field, the user needs to view the HTML source code of the form. The syntax to define the hidden filed is:

<INPUT TYPE=HIDDEN NAME=hiddenl VALUE="PHP MESSAGE">


Where,

INPUT TYPE - Specifies that the field is hidden


Specifies the name of,the hidden field

>

VALUE - Specifies the value as it appears on the form

In the above example, the form contains a hidden field containing the text, PHP MESSAGE.

Page 22 of 274

Form Handling in PHP

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>";

Figure 2.9 Creating a Form with Hidden Fields


3. Save the file as Continent.php under the /var/www/html directory.
V 1.0 C 200 Aptech Limited

Web Scripting with PHP

Session 2

WID R

APTHCH,

Form Handling in PHP


4. S. Open a new file in the gedit text editor. Enter the following code for retrieving the options selected by the user: <?php

$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

- -- - ----------_-

. .... ....

New Open Untitled 1*

Save Print Undo Redo Cut Copy, Paste Find Replace

<?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

V 1.0 Oc 2004 Aptech Limited

Web Scripting with PHP

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

Tools Wridaw Help . 0 , Search


Stop

http:j/l, v Forward Reload Print Home Red Hat Network [Support Specify the continend ASIA

Vj Book marks **-

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.

Form Handling in PHP


-M z1l1a.'.'..'

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

............. ....

Figure 2.12 : Displaying the Selected Continent

Web Scripting with PHP

V 1.0 2004 Aptech Limited

Page 25 of 274

(APrEcm

Session 2

~+L:DWID.N

Form Handling in PHP

,,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 &

Form Handling in PHP

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.

In the GET method, ___________ is added at the end of the URL. a. b.


C.
..............
V 1 . 0 O c 2 0 0 4 A p t e c h L i m i t e d

? /

Page 27 of 27zl

Web Scripting with PHP

(AOR LD, EW 10.0-EY

Session 2
Form Handling in PHP
method sends the information in the body of the HTTP request.

a. b.
C.

POST GET BODY None of the above

d.

Page 28 of 274

V 1.0 (D 2004 Aptech Limited

Web Scripting with PHP

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

Web Scripting with PHP

V 1.0 2004 Aptech Limited

Page 29 of 274

Session

WORLDWIDE

Using Variables and Expressions in PHP

3.2 Variables and Data Types.


A variable is an identifier whose value keeps changing. A variable has a name and a data type. The name refers to the value in the variable and the data type refers to the type of data the variable can store. We use variables to store user information, intermediate data such as calculated results, and values returned by the functions. Variables are used to store a data value in it. Variable data type means the type of data the variable can hold. Table 3.2 shows the data types of PHP:

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

Using Variables and Expressions in PHP

V 1.0 C 2004 Aptech Limited

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

Using Variables and Expressions in PHP


The syntax to assign a value to a variable using the reference of another variable is:

$new_varname =& $oldvarname


Where,

$new varname Specifies the new variable name


);> " $old_varname Specifies the old variable name For example, to assign a value of one variable to another:

<?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:

define(string_name, mixed value


Where,

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

define("NAME", "John Smith"); echo NAME; echo name;

Page 32 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

( 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.

t.4 Scope . of Variables


The scope of a variable is the portion in . the script within which the variable is defined. The scope of a variable indicates the lifetime of a variable- The lifetime of a variable is the duration from the time the variable is created to the time the execution of the scripts ends. In PHP, the following are the different scopes of variables: > > >
A

Local Global Static

MA Local 'Variables

Web Scripting with PHP

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.

0.4.2 Global Variables


When a variable retains its value throughout the lifetime of the web page, it is called the global variable. The global variable is declared with the help of the keyword global within the function.

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()

global $varl, $var2; Svar 2 = $ v a rl * $var2; echo $var2;

e c h o " T h e m u l t i p l i c a t i o n v al u e of 4 * 1.5 multiply();

Page 34 of 274

V 1.0 C 2004 Aptech Limited

Web

Scripting with PHP

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.

3.5 HTTP Environment Variables


Environment variables are system-defined variables that we can use in any PHP script. These variables provide information about the transactions held between the client and the server. They provide information about the HTTP request or the HTTP response. The environment variables are similar to the user-defined variables because they also begin with the dollar ($) sign.
Web Scripting withi PHP
V 1.0
(0)

2004 Aptech Limited

Page 35 of 274

Session 3
Using Variables and Expressions in PHP

Some of the environment variables are:

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

V 1.0 2004 Aptech Limited

Web Scripting with PHP

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;

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

Page 37 of 274

Session 3

DR-L.11 W I - D a

F.= CH

Using Variables and Expressions in PHP

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

Us ing V ar i ables and Ex press io ns in P HP

CHECK YOUR
1. An assignment operation is performed with the help of _________ sign.

a.

2-

A constant is declared using the _______________ function.

a. b.
C.

constant() define() string


_________ scope of existence.

3.

A constant has a. b. C. Local Static Global

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

Web Scripting with PHP

V 1.0 (6 2004 Aptech. Limited

Page 39 of 274

A1072FCIN

Session 3

W0.K--L,DW 'Or=

Using Variables and Expressions in PHP

6. a. b.
C.

The string integer floating-point boolean

data type stores true or false values.

d. 7.

The ________________ variable retains its value through out the lifetime of the program. a. b.
C.

local static global environment

d. 8.

The ______________ environment variables returns information about the uploaded files. a. b.
C.

SERVERPROTOCOL SERVERNAME POSTFILES

d. SERVERPORT

_ _ 40 of 274

V 1.0 @ 2004 Aptech Limited

Web Scripting with PHP

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:

4.1 Using the Assignment Operator


A variable is an identifier whose value keeps changing. A variable has a name and a data type. The name refers to the value in the variable and the data type refers to the type of data the variable can store. We use variables to store user information, intermediate data such as calculated results, and values returned by the functions_ Whenwe 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.
Open the gedit text editor. To assign a string value to a variable and display it, enter the following code:

<HTML> <HEAD> <TITLE>String Assignment Operation</TITLE> </HEAD> <BODY> <?php

Web Scripting with PHP

V 1.0 (P 2004 Aptech Limited

Page 41 of 27s'~'

(A"PrEcm
S e s s i o
n

W" WORLDWIDE

Using Variables and Expressions in PHP

ave,the,file as

r.php under the /y

directory. direct r .y

yp.6

ust :r

X4 i

-in the address barand:pressAhe,,Enter~' php

loc

i l lib e t l a gg g

Bookmarks Red
This is John Ci77el

Hat

Network

Figure 4.1 : Displaying a String

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:

<HTML> <HEAD> <TITLE>Integer Assignment Operation</TITLE>


</HEAD> <BODY>

Page 42 of 274

V 1.0 (-c,) 2004 Aptech Limited

Web Scripting with PHP

~P~`EaC'/Si

Session 4
Using Variables and Expressions in PHP

$ i n t -v a l u e l = 13; $ i n t value2 = 451 W i t valu462 ..'$int---valuel $int va


echo
$int-yal

d2y

$int~_value2; $iift_vdIde2,~

</BODY> </HTML> S -the file as.aftighlilt.ph


,

Open the Mozilla

aVd,

b%46Wi

Integer Assignment Operation - Mozilla

tl*
Back !,Home dBookmarks eRed Hat Network GAsupport rA~Shop L_jproducts L4Tralrflng
I
I

The product of 13 - 45 = 585

I L.'%,

L . 4,' 93 42 j

--------

Done

Figure 4.2 :
4

Displaying

the Value of an Expression

.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:

<HTbiL> <HEAD> <TITLE>Float Assignment Operation</TITLE> </HEAD>

Web Scripting with PHP

V 1.0 (L',, 2004 Aptech Limited

Session 4

W a IRI*Llo W.1 D.E.

Using Variables and Expressions in PHP

<BODY>

float--Yaluel. = 134.57;.; fleet vAlliez = 12.87; float value2, = $float_valuel :~ "The subtraction value of 4rjLoat vajue2;:

L6

The output appears, as shown in Figure 4.3.


` v LFf0atAA1gjrtt ............. . ..
3

iowe. or tlla . ......

11n i'X .. ...... Imm

File Edit View Go Jiookmatks Tools Window Help

http:/Aocalhost/assignflo L ' -j[;_; Search-4 Reload Slop Print B ,IH..cBookmarks eRed Hat Network dSupport EIShop GtProducts E jTraininq

Back

Fow;ard

The,uhtraction value of 134.57 - 12.0 =121.7

:2 fDone

Figure 4.3 Displaying the Value of a Subtraction

A2 -Using the toc al, ."Va Variables


::

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:

<HTML> <HEAD> <TITLE>Local Variables</TITLE> </HEAD> <BODY> <?php

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.

Web scripting with PHP

V 1.0 2004 Aptech Limited

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

Figure 4.4 : Using the Local Variables

4.3 Using the. Global Variables


When a variable retains its value throughout the lifetime of the Web page, it is called the global variable. The global variable is declared with the help of the keyword global within the function. As a result, it can be accessed from any part of the program. For example, to use global variables in the function that calculates quotient of two integers:
Open a. new. file in the text editor. Enter the following code to create the

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

V 1.0 2004 Aptech

Limited

Web Scripting with PHP .

Session 4

(APT'ECH
woa LDWIDF
11

Using Variables and Expressions in PHP

$int3 = $intl/$int2; echo "The quotient for $intl/$int2

4,14a,

y he. o u t p u t
"

I "' F1 t

fig""

Global Variables M ill Elie Edit WpjAocalh.Wabt-j1-j &Sw=hj


-

4Home 1.

Print
Tr gg

Id

Bookmarks

Red liat Ne
`

APP 4

19Prodixxts GA

j "..

The quotient for 68/50 = 1.36

411--'h

(D Done

Figure 4.5 : Using Global Variables

4.4 Using the Static Variables


A static variable is similar to a local variable. The only difference is that the static variable retains its valu e even after the fun ction terminates. When a function terminates, the values of the local v a r i ab l es o f t h a t f u n ct i o n l o o s e s i t s v a l u e s . T o r et a i n t h e v a l u e o f t h e v a r i a b l e t h ro u g h o u t t h e execution, use the STATIC keyword with the variable name.

I,

V 1.0 C(;,, 2004 Aptech Limited

Neb Scripting with PHP

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.

Open the Mozilla Web browser.


Type the http://localhost/staticdec.php key in the address bar and press

the Enter key. The output appears, as shown in Figure 4.6.

Page 48 of 274

V 1.0 @ 2004 Aptech Limited

Web Scripting with PHP

Session 4

W-OR'L 0 W I'D'

A P rECH

Using Variables and Expressions in PHP

'S

File

Edit

View

go Bookmarks

Tools

window

Help cvittp:
h

---------

: I } Home Nf Bookmarks JfRed Hat Network

........Ant - ............. 1Support (IlShop dProducts dTridning


-

The decrement value is 98

!'4. C , -e, 04 G9

Do n e

Figure 4.6: Decrementing a Value

Web Scripting with PHP

V 1.0 ng 2004 Aptech Limited

Page 49 of 274

EalT7rEcm
L
DWI

0,E

Using Variables and Expressions in PHP

r
t~

TRY: IT YOURSELF -- ____

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.

4 7 2 f o 0 5 e g a P V 1.0 2004 Aptech Limited

Web Scripting

Objectives
At the end of this session, you will be able to:
)>

Use Arithmetic operators Use Logical operators Use Relational operators

,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.

Web Scripting with PHP

V 1.0 Oc 2004 Aptech Limited

Page 51 of 274

AW01 p1t LYZEW

CAOME

Session 5
PHP Operators PHP provides with the arithmetic operators, as shown in Table 5.1: operator
+

Name Addition Subtraction Multiplication Division Modulus

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.

To display the remainder:


<?php $VAR1-15; $VAR2=4;

Page 52 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

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.

5.2 Relational Operators


A relational operator compares two operands. They determine the relationship between operands. Whenever we compare two values, it returns either true or false. PHP provides us with the relational operators, as shown in Table 5.2.
Operator
1=

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

Table 5.2 : Relational Operators

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.

5..3 'Logical Operators..


The Logical operators enable us to combine two or more test expression in a condition. They evaluate expressions and return a Boolean value. PHP provides us with the logical operators, as shown in Table 5.3. Operator AND true OR true XOR Expression2 are true or if both Expressionl and Expression2 are false and true otherwise. && II I Table 5.3 : Logical Operators Some of the examples of the logical operators are: To check if the student has percentage greater than 60 and year of passing is 2003: <?php $A=$GET('PERCENTAGE'j; $B=$GETl'PASSINGYEAR'1; if ($A>60 AND $B"2003") echo "ELIGIBLE FOR ADMISSION"; Note the percentage and passing year inputs are accepted from the user. We want both the inputs to satisfy certain condition. To use the OR operator:
<?php $A=$ GET['Va luc'1- if ($A=90 01t $A--95) echo "VALID INPUT";

true Expressionl II Expression2 Returns true if any one of the expression is

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

5.4 Bitwise Operators


The bitwise operators operate on the bits of an operand. They are similar to the logical operators. They work on small-scale binary representation of data. PHP provides us with the bitwise operators, as shown in Table 4.4.

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;

Note the above example will return 5.

Web Scripting with PHP

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
-

5.5 Assignment Operators',..


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 assign a value to a variable:

<?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.

5.6 Increment and Decrement Operators


The increment operators increase the value of the operand by one. The decrement operators decrease the value of the operand by one. These operators function more effectively within loops such as for, do while, and while. PHP provides us with the increment and decrement operators, as shown in Table 5.5-

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

Table 5.5 : Increment and Decrement Operators


Some of the examples of the increment and decrement operators are: To use the post-increment operator on a variable $A:

-1P . lip

$A=9;

echo "The value of A is: $A++ <BR>";


Page 56 of 274 V 1.0 2004 Aptech Limited Web Scripting with PHP

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_

5.7 String Opprators


The string operators operate on character data. PHP provide us with the string operators, as shown in Table 5.6.
Operator Name Description

Concatenation Concatenating assignment

Returns a concatenated string Appends the argument on the right side to the variable

Table 5.6 : String Operators

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

Scripting with PHP

V 1.0 @ 2004 Ar)tech Limited

Page 57 of 274

Session 5

WORLIDWIIIDIZ

'APFIEC

PHP Operators > To assign a value to a variable using the Concatenating assignment operator: <?php

$A=WELCOME; $A.= FRIENDS; echo" CONCATENATED STRING IS $A";


Note the above code will append the FRIENDS on the right side of $A containing the value WELCOME and return the string WELCOME FRIENDS.

5.8 :Precedence of Operators


We have seen the different operators in PHP. A complex expression may have several operators on it. In such cases, PHP will follow the order of precedence. Table 4.7 indicates the precedence of the operators. Precedence Highest Precedence Operators %

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

V 1.0 9) 2004 Aptech Limited

Web Scripting with PHP

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

V 1.0 0( 2004 Aptech Limited

operand by one.

Web Scripting with PHP

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

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 5

(.-4Pr,FC,ff WORLDWIDE
PHP Operators

ruff YOUR R PROGRESS U


1111 U 1% 1 a. b.
C.

LM

is the symbol used to perform the operation on a value. Operand Variable Operator

2.

The ________ arithmetic operator returns the remainder of a division operation. a. b.


C. $

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. ==

operator is the concatenating assignment operator.

Scripting with PHP

V 1.0 0c 2004 Aptech Limited

Session 5

WOR LVW I DE

APFIECH

PHP Operators

6. a. b.

The AND OR XOR

operator returns true only if all the expressions are true.

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

V 1.0 9 2004 Aptech Limited

Web Scripting with PHP

Objectives
At the end of this session, you will be able to:

Use Arithmetic operators Use Relational operators Use Assignment operators

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:

Using the .Arithmetic Operators


We use arithmetic operators to perform mathematical calculations. The arithmetic operators include operators such as addition, subtraction, multiplication, division, and modulus_ Forexample, to create a form that accepts two numbers and displays their product using the PHP script-. 1. 2. Open the gedit text editor. Enter the following code to create a form that accepts two numbers: <HTML> <BODY> <B>Multiplication of Two Numbers</B> <FORY1 METHOD=GET ACTION "Multiplication.php"> Enter the First Number: <INPUT TYPE="TEX'1'*" NAME="n1text"> <RR> Enter the Second Number: <INPUT TYPE="TEXT" NAME="r12text">

Web Scriptin with PHP

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

Bookmarks - R e d Hat Network (,]ftsupport ( : I S h o p (j_IProducts jElTraining

IN I till iplicatio 11 of "Fwo Numbers tillibel-S Fn wi t he First Number: Enter the Second Number: I MULTIPLY (92i Done

Figure 6.1 : Multiplication Form 9. Enter the first number as

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

APKECRI, WORLD 102


PHP Operators

Figure 6.2 : Viewing the Product

6.2 Using to Relational Operators Using Operator


relational operator compares two operands. They determine the relationship between operands. Whenever we compare two values, it returns either true or false. For example, to create a login form that accepts the username and password and authenticates the user using the PHP script: 1. 2. Open a new file in the text editor. Enter the following code to create the authentication form:

< 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

Edit View Go Bookmarks Tools Window Help

' 1 1 f,&, http:/Aocalhost/Multip

;A_Search

Session 6

w 0 ft:L 0 W 10.2

Air Eck

PHP Operators

5. Enter the following code to confirm the password,:


<HTML> <BODY> <?php $A=$--GET.['lDasstext'1 i f($A--"pass") echo "Valid User";

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

Figure 6.3 : Authentication Form 9. Enter John as the user name.

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

2004 Aptech Limited

Web Scripting with PHP

Session 6

W - Q , R - L ~ , D . W

1 1

PHP Operators

File

Edit

View

Bookmarks Stop

Tools

Window

Help Search Print w

http:/Aocalhost/Authel Reload Back Forward

!ill Home V4Bookmarks .t Red 'Hat Network Valid User

Support ( A S h o p

O'

Products CjTraining

LZ -,?,

-04 (2~2 Done

Figure 6.4 : Viewing the Confirmation

6 . 3 U s i n g t h L2 W-C Operatorss e. al Operator


The Logical operators enable us to combine two or more test expression in a condition. They evaluate expressions and return a Boolean value. For example, to create a form that accepts the percentage scored by the student and displays the grade depending upon it using the PHP script: 1. 2. Open a new file in the text editor. Enter the following code to create the form:

< 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.

*JVeb Scripting with PHP

V 1.0 Cc) 2 0 0 4

Aptech Limited

Page 67 of 274

( ___ PEif W R D I E A__ r cr0 O L WD

Session 6
PHP Operators

Enter the following code to assign grades:

$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

Shop (ItProducts LljTralning

- - - ------- --------- --04 eg 1' Done

. ........ .

Figure 6.5 : Grade Form

Page 68 of 274

Session 6

WORLDWIDE

A p r E c m

PHP Operators 8. 9. Enter 70 Click


f1v

I'

ENTEWiYOUR PERCENTAGE text box. A s o n G A . uo . ~ ep er,shn F ue.. hw R E t n g, pas s i i r6 b p a a ng 6 IFn Irk


V ,;.*,Search Print

GRADE

Filedif ' Back

View Go Bookmarks Tools Window Help


Forward Reload Stop _____
. i htt Itlocalhost/
V 4

!*Rome 1 IdBookmarks -AtRed Hat Network (;'Support dShop EftProducts (RTralnlng


Congrats'!! Grade I

lf@. G9. Done

K*V ,

1-

111

-;

-1

Figure 6.6 : Viewing the Grade

6.4 Using the Assignment

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>

Web Scripting with PHP

V 1.0 (D 2004 Aptech Limited

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

Enter the following code to calculate the..

simple

interest:,,

?php $P=$GET[ $R=$-" GET ['n2 text $N,:7,$_QET text


< ['n3

' n i t e x t ' j ; ']--

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.

Figure 0.7 : Simple Interest Form


8. Enter 30000 in the Principal Amount text box.

9.

Enter 3.5 in the Rate of Interest text box.

Page 70 of 274

V 1.0 @, 2004 Aptech Limited

Web Scripting with PHP

Session 6

CAPTEC
R K

O'LDWI-DE

PHP Operators

10. Enter 5' in the Rfirnber of Years text box. 11. Click
Mozillia

LATE button. A page appears, as shown in Figure 6.8. U.

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

T14E CALCULATED SIMPLE INTEREST IS 5250

LZ

't~

Q 09

1 Dom

Figure 6.8 : Viewing the Calculated Simple Interest

6.5 Using tie B&IM" e OMgWrs


The bitwise operators operate on the bits of an operand. They are similar to the logical operators_ Theywork on small-scale binary representation of data. For example, to use the OR operator on 32 and 5 using the PHP script: 1. 2. Open a new file in the text editor. Enter the following code: <?php echo "THE ANSWER OF 3215 IS: echo 3215;

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

Web Scripting with PHP

Sessocn 6
PHP Operators

Sv 44o Ila File Edit View Go Bookmarks Tools Back

ttp:/flocallio

LMndow Help .. . .. ........


I--

Fonvard

Reload Stop

-h Print

_____________________________________________________________________________________________________________________________________________________

B1 01

ijj Home i Xf Bookmarks #*Red Hat Network EtSupport

C,-~ Shop C jProduus EIT wining


,

THE ANSWER OF 3215 IS: 37

U~

. ..... . ....

Figure 6.9 : Viewing the Result of using Bitwise Operator

"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

Print

C.-D

t:42

Figure 6.10 : Appending Text to a String


Page 72 of 274 V 1.0 `Q 2004 Aptech Limited

Session 6

R L,11) W 1 0 E

ePYWCH
s o t a r e p O H P

6.7 Using the Increment and Decrement Operators


The increment operators increase the value of the operand by one. The decrement operators decrease the value of the operand by one. For example, to display the value of the variable before and after using the pre decrement operator: 1. 2. Open a new file in the text editor. Enter the following code:'

5. Type http://localliost/I)ecr *ement.pbp

in the. address 'bar and press

-the-Enter

key. A page appears, as shown in Figure 6.11.


V
1 File Edit View Go Bookmarks Tools Window Help Back F :.,- ; J

i
j w ., search
L i ______________________________

Reload

411tip:I/localhost/ cren R
S T

Print

I hc vain,: of A i s 1 (10 'I I ic x aluc ol'A is 99

'

fl

Home j Bookmarks#*-*Red Hat Network ;~f Support -'Shop d 2 i i j

c--2 i Done

t Figure 6.11 : Viewing the Result of Decrement

.'.eb Scripting with PHP

(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

V 1.0 C~,' 2004 Aptech Page 74 of 274 Limited

Range

nditional StOleaments J in P Hip


Obi ectives
At the end of this session, you will be able to:

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

executed. For example, to compare two variables and display a message:

o dy > <?PP $a=10;

Web Scripting with PHP

V 1.0 ( ) 2004 Aptech Limited

Page 75 of 27,11,

Sessi n

APTIECH WO R L D.W 1 0
Conditional Statements in PHP

$b=12; if ($a < $b) echo "a is less than b";

</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

$";

i t ( $ sal > 8500) f $bonus = Ssal * .1; echo "Bonus : 1"'

Page 76 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

(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

c -:'---ipting with PHP

(A-JMFECAr

Session 7

1-!~~

LOW71,0E

Conditional Statements in PHP

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

Conditional Statements in P HP $comm = $sal echo "Commission cno echo "<br>";


I

$$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:

Total Sales Commission

$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.

,'.Ieb Scripting with PHP

V 1.0 C0 2004 Aptech Limited

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 , ___________________________________________________________________________________________________________________________________________

Following code accepts the number of units consumed by the user:


<html> <body> <form action="elecBill.php" method="GET"> <table> <tr> <td>Number of Electricity units consumed <td><input type="text" name="units"></td> </tr> </table> <br> <input type="submit" value=-Submit"> </form> </body> </html>

</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

V 1.0 Q 2004 Aptech Limited

Web Scripting with PHP

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-

7.2 Switch Statement


A switch statement checks single variable against multiple values and executes a block of code based on the value it matches. The value can be any integer or string constant. The switch
statement is easier to read than multiple if statements. The syntax for the switch statement is:

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 variable does not matches any specified

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

Neb Scripting with PHP

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.

Scripting with PHP

V 1.0 .7 2004 Aptech Limited

Page 83 of 274

I WORLD PRLrD1 EW CID MAE

Session 7

( *

Conditional Statements in PHP

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

is greater than X";

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";

Web Scripting with PHP

The above code also displays, x is greater Lhan Y.


Page 84 of 274 V 1.0 2004 Aptech Limited

Session 7

(APrECH
DW10a

Conditional Statements in PHP

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.

Web Scripting with PHP

V 1,0 @ 2004 Aptech Limited

Ternary

Session 7

CA - p r , E r i v DE10 M.

Conditional Statements in PHP

1.

The a. b. C.

if

CHECK YOUR PROGRESS


keyword is followed by the _____________________ in parentheses.

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

2004 Aptech Limited

Web Scripting with PHP

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

6. a. b. C. d. If statement Switch statement Conditional statement Ternary operator

simplifies complex conditionals into one line statements.

'Aleb Scripting with PHP

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:

8.1 Using the if


The if statement executes a block of code only when the specified condition is true. If the condition is false, the program ignores the block of code in the if body and executes the statements following the if body. We will create a form that accepts name and phone number from the user. We will also add validation to the form to check if the fields in the form are left blank using if ... else statement.
To create the form:

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

Conditional Statements in PHP

</tr> <tr> <td>Age: </td> <td><input type="text" name= "myage"></td> </tr> </table> <br> <iput </FORM>

="submit" va;~e='~,.Submit">

nse le

ie aclfior0511 9! .7,T -at M


019

acute

Ah A' ID t%

is

MIRI

-Untitledl(-M odifie'd) - gedit

New Open Untitled 1 x


,

- Save ' Print ' Undo Redo ' Cut

Copy

Paste ' Find Replace

<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

Figure 8.1 : Attributes of Form Element


4. Save the file as info.html tinder the /var/www/html directory.

5.

Open a new file in the4ext editor.

Page 90 of 274

V 1.0 @ 2004 Aptech Limited

Web Scripting with PHP

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

ether, thdffl atni-q~


z. . 11 .

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

Save Print Undo Redo Cut Copy Paste

Find Replace

Untitled 1 x

<HTML> <HEAD> </HEAD> <BODY> <?php

<TITLE> User Information, </TITLE>

$nivnarne =$POST[ 'Mynarne'] S1r1yage=$_POST['rnyage'1;

echo "Please enter your name";

L11 18. Col.

!NS

Figure 8.2 : Validating the Name


l

ejeb Scripting with PHP

V 1.0 @ 2004 Aptech Limited

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

Home Y4 Bookmarks **-Red Hat Network

C,ft. Support (AShop C~~jtProclucts Training

Please enter the information Name: Ale:


Submit I

G2 T Done
Figure 8.3 : Personal Details Form

Page 92

Of 274

V 1.0 2004 Aptech Limited

Session 8

WOMILDWIDE

APr,ECM

Conditional Statements in PHP


13. Click the Submit button. A page appears prompting to enter the name, as shown in Figure 8.4.
atioSe ..Useffinf6im ' -6 "A File Edit .,36ew Go Bookmarks Tools Window Help .),;. oz
a,-,,

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

Figur Figure 8.4 : Message Displayed

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
-

Print

Home 4Bookmarks g*-Red Hat Network riSupport f .jShop "Products t:jTraining

John, you did not enter your af!c Rack aCk[)one

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.

Scripting with PHP

V 1.0 10c 2004 Aptech Limited

Page

93 of 274

Session 8
V . - -... ~1 ' r n -V
File Edit

W10MV-91WIV-1a

APIFIECH

Conditional Statements in PHP


f'. . f X , fl * Ij

View Go

-rma onz

Bookmarks Tools Window Help ,_,* Search

girl

I-.,

1-v-11-~"

C-: 1

! H o m e I VjBookmarks e R e d Hat Network Hi John. Your a e is 44 Back


y

Support EJShop ( y Products ejTralning

L Figure 8.6 : Personal Details Displayed

8.2 Using the switch Statement.


A switch statement checks single variable against multiple values and executes a block of code based on the value it matches. The value can be any integer or string constant. The switch statement is easier to read than multiple if statements. For example; an organization provides various facilities and perks to their employees depending on the grade assigned to them. Table 8.1 lists all the facilities available for the respective grades. Grade A Facilities 1. Increments are based on 30% of their basic salary 2. 3. 4. B 1. 2. 3. 4. C 1. 2. 3. 4. Bonus at the rate of 20% of their basic salary Traveling allowance worth $500 Medical allowance worth $500 Increments are based on 20% of their basic salary Bonus at the rate of 10% of their basic salary Traveling allowance worth $300 Medical allowance worth $300 Increments are based on 10% of their basic salary Bonus at the rate of 5% of their basic salary Traveling allowance worth $100 Medical allowance worth $100

W -- --W -

Table 8.1 : Facilities Based on Grades

Page 94 of 274

V 1.0 (D 2004 Aptech Limited

Web Scripting with PHP

Session 8

APMr,M
W 10 it L 0 WIM S

To display facilities according to the grades using the switch statement:

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

ra e, A TD>-;~'INPUT 'TYPE= "text" ~N' ;:~

gradEi"></TD>

.Veb Scripting with PHP

V 1.0 2004 Aptech Limited

6-4-~:ry-,Ecw WOR L D W VID it

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;

7 . Enter t he following cod e to c h ec k wh e the r th e N am e fi e ld is left blank: if($myname=="")

id-4, 6dified

Sessi n 8

WORLDWIDE

PrIECH

Conditional Statements in PHP

echo "Please enter your name"..;

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

lan ttply ac 044


Y,

ode

W111-;~W.;::-**17111

F~ l

File Edit View aearch Tools 2ocuments Help

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 "Increment = 30% of basic salary"; echo


"<BR>";

echo "Bonus = 20% of basic salary"; echo 1 . <BR> " ; echo "Travelling allowance = $SOO"; echo
"<BR>";

echo "Medical allowance = $500"; echo " <BR> break;

........

Ln 43, Col. 36

INS

Figure 8.8 : Case A

Scripting with PHP

AAVT,ECH-

Session 8

W,O R L D'W-1z0'.F

Conditional Statements in PHP

10. E rijfollowing code to display facilities for Grade B and Grade C:

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";

echo "<BR>"; echo "Medical allowance echo "<BR>"; break;

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:.

<BR><BR> <A HREF="perks.html"> Back </A> /BODY> </!-ITML>


13. Save the file as calcPerks.php under the /var/www/htmj- directory. 14. Open the Mozilla Web browser.

Page 98 of 274

V 1.0 @ 2004 Aptech Limited

Web Scripting with PHP

(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

Edit View Go Bookmarks Tools Window Forward Reload stop L44

Help

X,

----------

Back

http:/Aocalhost/pe 40 search

Print *Bookmarks , e Red t CITralnl ng CS

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

Figure 8.9 : Grade-Facilities Form

Grade Details.- Mozilla

1 file Edit View go -11ookmarks Tools Window Help Back


LI/Home I

BE

Forward

Reload Stop

http://localhost/ca ivA-Search ________ PrintMN

*Bookmarks 4*_Red Hat Network (1ISupport at Shop (:1'Products C:lTraining

Please enter your name Back

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

d id not enter your Grade..

Back ack
ap [ Done

Figure 8.11 : Message Prompting to Enter Grade


~-

Scripting with PHP

V 1.0 &:) 2004 Aptech Limited

Page 99 of 274

Session 8

W0,R-Lic&,WA0M

A P TIE CIA7

Conditional Statements in PHP

Click Back to return to the Information.html file.


20. Enter John in the Name field and enter A in the Grade field.

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

..

File. .. ... Edit View Go Bookmarks Tools


Back
- It

Window Help

.. ;* Search

-a

Forwa rd

Reload

Stop I

[, 4 http://localhost/calcP

Print Home j Xf Bookmarks . R e d Hat Network (ISupport C,,ftShop C Products a:jtTraining

Facilities for John (Grade A)


increment = 30% of basic salary Bonus = 20%. of basic salary Travelling allowance = $500 Medical allowance = $500

Figure 8.12: Facilities for Grade A

8.3 Using. the Ternary Operator


Ternary operator is also known as conditional operator. It simplifies complex conditions into one line statements. Ternary operator is considered as a shortcut for if ... else statement. We can modify the dispDet.php file to display the same messages using the ternary operator. To use the ternary operator.1. 2. Open the dispDet.php file in the text editor. Replace the PHP script in the code with the following script:. <?php $myname=$P0ST[.'myname'1; $myage=$_POST['myage'l; if ($myname=="") { echo "Please enter your name"; else $mOsg
Page 100 of 274

($myage=="") ?

$-.,rLyname, Please enter your age"


Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

Conditional Statements in PHP

" H i $ m y n a m e . Your age i s $ m ya ge "; echo $mesg; echo $mesg;

PHP enters the; else'block:vVhen':th'~d~,'uset-dntets


' . : " ' '

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

W Name-,field.--' li* If then.

user has entered the age, the


Save thq.,jOispDet.ph file ne
1W 1- -

messaoOHI-'$mynam-"e.~'You

4' ~ 4 -

age

trri" 9 :'Is didddl'

Va

" A

".M01,

Operu,thej.Mozilla,.',i dbTbfdWtdr-.
,

7. Click the Submit button.


V User, lnfarmadoit-Nozllll i

A. page appears, as shown in Figure 8.13.

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

Print

Bookmarks ** Red Hat Network (] jSupport

jShop t: jProducts

jTrainfnq

Figure 8.13 : Message to Enter Age

.','eb Scripting with PHP

AWPFIECf-111, ,
S e s s i o
n

O'R'L W UD.E

Conditional Statements in PHP

. I ;AIIWIC~ IV File Edit View Go Bookmarks Tools Window Help

in

"

I L v

Back

Forward

Reload Stop d k

httilocalhostidisp

Search _______________

Print

k k Hi John. Your age is 44


Back

91 G9 I Done Figure 8.14 : Personal Details Displayed

Page 102 of 274

(APTECH

Session 8

woRLowIoe

Conditional Statements in PHP

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.

Points in Hand Basic Member

Additional Points Privileged Member

Calculate and display the additional amount of points available and the total amount of points. Use if ... else statement.

-'.

_: Scripting with PHP

Page 103 of 274

Objectives
At the end of this session, you will be able to:

Use Loops Use Jump statements

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.

9.1 'Working with Loops


A loop executes a block of code repetitively. In loops, the specified condition is tested and the statements in the loop are executed repetitively if the condition is true. If the condition is false, the loop ends and the control is passed to the statement following the loop. The continuous execution of statements placed inside the loop is called iteration. PHP provides us with the following loop statements: Loop do-whi ie- Loop for Loop
-

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;

,eb Scripting with PHP

V 1.0 (e) 2004 Aptech Limited

Page 105 of 274

A 0 rEcm.

Session 9

W,O-WL:*WjWR

Flow Control in PHP


The while 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 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:

To display the first ten multiples of 5: <?php


$counter=l; $number=5; while($counter <= 10) $result:=$number*$counter; echo "<BR>$result<BR>"; $counter=$couiiter+1; }

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,

the statements in the loop body are not executed at all.


If we want to execute the loop body at least once, we must use the do vi h i le loop. The dowhl-lo loop works similar to the -while loop. The only difference between the while and do-while loop is that in the do-while loop, the condition is placed at the end of the loop.

Page 106 of 274

V 1.0 C 2004 Aptech Limited

Web Scripting with PHP

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.

Some of the examples of

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

c u r t - 1,7 P : o i . - -,B . : --r= Scot..coul-aL-ef< = < 3 RD- T h e v a 1.


T

ze-r'!
1- 1

e could not b e displayed";

i
f i e f S c r i p t n g w i t h P H P

V 1.0

' e )

2004 Aptech Lim ted

Page 107 of 274

Session 9

Z. L

Flow Control in PHP


The above code displays the even numbers using the do-while 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.
1'1`_11-1~1._ P O P .
v

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:

>

To display the output of the multiplication of a number by 2:


< ?PIMP

$num.ber=6; for ($counter=1.;

$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

"The odd numbers arc-, $i>=i;

Pa

ge 108 of 274

V 1.0 C-) 2004 Aptech Limited

Wet) Scripting with PHP

Session 9
Flow Control in PHP

$ nu abe_ r = $.;L.

echo $riumber; echo "Values could no


t

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

92.1 break Statement


The ',--)rea.k 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. This statement can be used with staternent, f o r loop, l o o p , a n d ( 3 o - w h i l e l o op . the i f statement, Some of the examples for the break statement are: To display the consecutive numbers from 1 to 10:
<?P11P

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.

_-'ping with PHP

V 1.0

200_ Aptech Limited

,l

Page 109 of 274

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

case echo break; default: =:i31 alphabet is a vowel

Page 110 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 9

WO K;L 0 . "OV

Flow Control in PHP


echo "<r--? BR>Tno alphabet is not a vowel.";

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.

- Scripting with PHP

V 1.0 ((~` 2004 Aptech Limited

Page 111 of 274

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.

Page 112 of 274

V 1.0 ((.: 2004 Aptech Limited

Web Scripting with PHP

A r- 2rEcm

Session 9

ORIL'O WI D F

Flow Control in PHP

>

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.

>

I scripting With PHP

V 1.0 t, 2004 Apte0i Limited

Page 113 of 274

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.

for while do-while


for-each

4.

The ___________ a. b. C. conditional jump loop

statements control the execution of the loop statements.

5.

The a.
C. C.

statement stops the execution of the loop. continue exitloop break

.... ... ...

Page 114 of 274

V 1.0 2004 Aptech Limited

Wet) Scripting with PHP

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>";

Save the file as fibo.php under the /var/www/html directory.

Scripting with PHP

V 1.0 C c.) 2004 Aptech Limited

Page 115 of 274

Session 10

Flow Control in PHP

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

The Fibonacci series : 1

5 13 e-9) Done

Figure 10.1 : Viewing the Fibonacci Series

10.2'.Ut sing The do-*hi3.e loop..,


The do-while loop works similar to the while loop. The only difference between the `,-chile and do--c~.71-iile loop is that in the loop, the condition is placed at the end of the loop. For example, to display the first ten odd numbers in the reverse order using the do-while loop:

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 )

I Save the file as odd.php under the /var/www/html directory


4.

Open the Mozilla Web browser.


V 1.0 (F-D 2004 Aptech Limited Web Scripting with PHP

Page 116 of 274

Session 10

I.T.

Aprr1r.Iff

Flow Control in PHP


5. Type http://localhoi3t/odd.php in the address bar and press the Enter key. The output appears, as shown in Figure 10.2.
V
6z

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

Figure 10.2 : Viewing Odd Numbers in Reverse Order

10.3 Using the-for Loop


A for

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-)

e c h o " T h e s q u a r e o f - f i r s t . t e n n u m b e r s a r e : < B R > < B R > " ; for

($i=1;$i.<=10;$-i-j-+)
r

I $ square= $ i * $.i. ;

e c h o " $ i X $ i = $ s q u a r e " ; echo "<BR>";

3.

Save the file as square.php under the /var/www/html directory. .

Open the Mozilla Web browser.

Web

Scripting with PHP

V 1.0

200-1 Aptech Limited

Page 117 of 27,11

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

..

http://localhost/sq Back J Home


-

F omard
,

' JBookmarks

.................... ... . .... ...... --- -- t

Reload

Stop

~k_ Search

Red Hat Network Support (!!shop _J

-'Products L-3

Pnnt 'Training
J

1 he square of first ten numbers

arc I X 1 1
2X2 A

;X; = 9 4x4-16 5 X 5 6 X 6 = 36 7X7=49

25

8X8=0-4 9X9=81 lox 10 100


C-43 < 2 2

Done

Figure 10.3 : Displaying the Square of the First Ten Numbers

p.04 MIA the.- JumpStatements . 2 PS e

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">

Enter number: <INPUT TYPE

"TEXT" NAME = "num"-

Page 118 of 274

V 1.0 @ 2004 Aptech Limited

Web

Scripting with PHF

Session 10

WORLDWIDE

Flow Control in PHP

<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;

echo "<BR><BR>Inverse of the number is 1/$number"; echo "<BR><BR><a href=break'-html>Go Back</a>";


Save the file as breakinv.php under the /var/www/htmi directory. Open the Mozilla Web browser. Type http: / / localhost /break. ht:ml in the address bar and press the Enter - key. The form appears, as shown in Figure 10.4.

6. 7. 8.

A41rW1W_0*9*WA_~AWj WIAM-9 File Edit View Go Bookmarks Tools Window Help

http:/jloc afhost.lbieak. fit nie r~h Reload


Red Hat Network ~Supf ort 'Shop -'Products j j
p -

Back
13

Print
j Training

Home j Bookmarks

I =mcr nu whet: i
INVERSE

Done

Figure 10.4 : Displaying the Form

e:, Scripting with PHP

V 1.0 2004 Aplech Limited

Page 119 of 274

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

Print

Nrr
r'
9

, J Hoe jBookmarks -0# Red Hat Network 'JSUPPOrt `j rn

Inverse. ofthe number is U-7


Go Back

-- 4 &

E5 \4' C7 <0 Done

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.

Page 120 of 274

V 1.0 ((,) 2004 Aptech 1-ignited

Web Scripting with PHP

Sess~oirll 10

(A'PF,EC,N WORLDWIDE
Flow Control in PHP

TRY IT YOURSELF
Part II - For the next half an hour:
1

1. Write a program to display cube of the first 10 numbers.


2rr tehenlyttae Wg c eudah s . ip owesatcggu er c hr bi e r to h treue e e amk t i p o. a ha nf h t

- : -'pting with PHP

(APywcw

Session 11

woe

L-D W IV E

Functions in PHP

11.2 Built-in PHP


PHP provides us with some built-in functions. We can categories these built-in functions into: Mathematical functions String functions Date and time functions Error handling functions Database functions Array functions Mail functions Built-in functions are placed in the PHP script.

11.2.1 Mathematical F ti
Mathematical functions operate on numerical data. Table 11.1 lists and describes some of the mathematical functions:

Table 11.1 : Mathematical Functions


Some of the examples for the mathematical functions are: To find the nearest integer of the number, 99.6:
<?~ ' 3110

echo "The nearest integer o--F 99.6 is: echo round(99.6);


I

11 ;

Note the above code will return 100 as the nearest integer.

Function Name Syntax

Description

Sessi

n 11

(APrECH
\ !!O~R LDWIDE

To find the largest of the arguments:

<?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:

<?php echo "The square root of 256 is: echo sqrt(256);

Note the above code will return 16.

11.2.2 String Functions


String functions string functions:

operate on character type of data. Table 11.2 lists and describes some of the

Table 11.2 String Functions

b Scripting with PHP

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);

Note the above code displays 41.

11.2.3 A NW I n 1.2.3 B d T! Im'eAnctions


The date and time functions enable us to find the date and time on the system. Table 11.3 lists and describes some of the date and time functions:

Table 11.3 : Date and Time Functions


Web Scripting with PHP

Page 126 of 274

V 1.0 2004 Aptech Limited

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;

Note the above code will return the current month.

11.2.4 Error Ha dam, Functions


Error handling is the process of dealing with errors as they arise during the run-time. PHP provides us with the error handling functions to define the error handling rules. Table 11.4 lists and describes some of the error handling functions:
F u n c t i o n

(error _msg

trigger erro trig seterr rhandi errorr porting

_ 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

Table 11.4 Error Handling Functions

Scripting with PHP

V 1.0 OL 2004 Aptech Li cited

Page 127 of 274

("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

describes some of the error constants:

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

11.3 User-d User

-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

To execute the function, we have to call the function.


Tine

syntax to call a function is:

-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.

11.4 Passing Arguments to Functions


Sometimes it is required that we have to accept inputs from the user. These inputs are processed for producing the desired output. For such cases, we can also design complex functions that accept inputs from user. These inputs that are passed to the functions are termed as arguments. A function can be designed to accept multiple arguments. The syntax to define a function with arguments: function fun_name(argl,arg2,...) code } Where, arg - Specifies the argument that is passed to the function There are three ways in which the arguments can be passed to the function. They are: >Passing arguments by value Passing arguments by reference Setting default value for arguments

11.4.1 Passing Arguments By


When the argument is passed by value, the value of the argument remains unchanged outside the function. The arguments are prefixed with the dollar ($) sign in the function definition to indicate that the argument will be passed by the value.

Page 130 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session I I
V 1.0 (q) 2004 Aptech Limited

rEcIff DWI'DE

Page 131 of 274

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.

11.4.2 Passing Argument By Reference


We can also pass the argument by-,reference. If we pass the value by reference, the value is modified even outside the function. When a function is defined, arguments must be prefixed with the ampersand (&) sign to indicate that the value is passed by reference.

-3b Scripting with PHP

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.

11.4.3 Setting Default Values


We can also assign default values to the arguments. We must assign a default value to the argument in the function definition. Now, even if the user tries to pass different arguments, the function would process only the default value.

Page 132 of 274

V 1.0 Oc 2004 Aptech Limited

Web Scripting with PHP

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

<?Php :unction TA($BASIC_SAL=10000). { STA=0.25*$BASIC_SAL; echo "The TA is: $TA"; } TAO;

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.

11.4.4 Returning. Values from Functions


A function can also return values. The return statement returns the value from the function. For example, to create a HRA ( ) function for calculating the house rent allowance: <?php
function HRA($Basic_Sal) $11RA=0.25*$Bas_Jc_Sa1;

return $HRA; SBasicSa1=20000;


SB=11RA echo $B;

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.

111. 4.5 Nesting of Functions


We may use several functions in a program. These functions may be dependent on few other functions defined in the program. As.a result, a function may require calling other functions. When one function calls another function, it is termed as nesting of functions.

V I LO Scripting with PHP

2004 Aptech Limited

Page 133 of 274

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.

Page 134 of 274

V 1.0 Q 2004 Aptech Limited

Web Scripting with P--

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

return $A*factorial($A-1); echo "The factorial is:. $B=factor-ial($A); echo $B;

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.

eb Scripting with PHP

V 1.0 C 2004 Aptech Limited

Page 135 of 274

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-

Page 136 of 274

V 1.0 (0 2004 Aptech Limited

Web Scripting with M'

c3ession

A p r E c m WORLDWIDE

Functions in PHP

CHECK YOUR PROGRESS


1. A function name can contain ___________
a. b.
C.

periods underscore

blank spaces reserved keywords

d.

The ___________ function returns the ASCII value of the first character of the string.
a. b.
C.

chr () bin2 hex

ord

3.

The time() function provides the time in number of a. b.


C.

hours minutes seconds

4.

The trigger_error () function _______________________ a. b.


C.

generates an user error generates the PHP back trace sets a user function to handle errors in script

5.

When we pass the arguments by value, the arguments value a. b.


C.

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

Scripting with PHP

V 1.0 (0 2004 Aptech Limited

Page 137 of 274

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

two functions calling the same function

Page 138 of 274

V 1.0 Oc 2004 Aptech Limited

Web Scripting with PHP

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>

a form that accepts a number:

<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.

,%eb Scripting witi, PHP

1 . 0

C c)

2004 Aptech Limited

Page 139 of 274

(APrECR
Session 12
INOR LOWIDE

7'g

:* 46 foilow'Wng code to find the square root of a number:


-

:',',GET n1text

p,,_square. root of
qrt ($A) ;

;A is:ff;

le -'. file ~, ef iivareroot-PbP under-4he /var/www/htmi; I directory


b3Mo'zllla,-,-Web browser. XY E 19 onn pai3liolist/iiqu , ppeqrp

Je;

hsNsbdWn I n t'' htaL im,'Jp o

nn':514

mozlula

4 http:/P(
.Wlklwl~x

Enter a Number: I SQUARE ROOT I

L75 "';' P-4) (3 I Done


g

V. O 1 c 0

2004 Aptech Limited

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.

(021 1'Done - ----- ----

....... . ... .

Figure 12.2 : Viewing the Square Root


Page 140 of 274

Session 12

APrEciv WORLDWIDE
Functions in PHP

12.2 Using the String -Functions


PHP provides string functions that operate on character data. For example, to obtain the ASCII equivalent of B using the PHP script:

1. Open a ri 3.
< ?php

ille,01he 46xt e4k

Enter the following cod&i:,'


71 A-~.,

40qWM
13

Figure 12.3 : Displaying Hexadecimal Equivalent

12.3 Using the' Date ' and Time, Functions


The date and time functions in PHP enable us to retrieve the date and time on the system.

Scripting with PHP

i f MOZ111a Edit 'Vi

V 1.0 2004 Aptech L i m i t e d

Page 141 of 274

'

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

-------- -. .............

Figure 12.4 : Displaying Time in Seconds

12:4 Crest .tjp the:


addition to the built-in functions, the user can also define their own functions to perform tasks. For example, to create a function that calculates the remainder: 1. 2. Open a new file in the text editor. Enter the following code: Functions in PHP
<?php

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

Florne y 6dokmarks The re mainder is 5

-04 (ER Done

. . . . . -. .-----------.....

Figure 12.5 : Displaying the Remainder

12.5 Passing Argument to a Fu.nct!Qh by. Value.


When we pass the argument to a function by value, the value of the variable is modified only inside the function. The change in the value of the variable is not reflected outside the function. For example, to accept two numbers and display their product using a function: 1. 2. Open a new file in the text editor. Enter the following code to create a form that accepts two numbers:
<HTML> <BODY>

~z Scripting with PHP

V 1.0 2004 Aptech Limited

Session 12
Functions in PHP

ENTER THE FIRST NUMBER: < INPUT TXPE= " TEXT" NAME= "numl text " > R-

5.

Save the file as

07M

Multipl

Pbpu W/htMl directory.,


rowser. show . in

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

ENTER THE FIRST NUMBER:I ENTER

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

Edit View Go Forward

Bookmarks Tools
Stop

\M ndcyw Help httip./flocalhis4 u0 * Search

------

Reload

Print

fjjHome

*Bookmarks **_. R e d Hat Network

1 4 shop (iftProducts EATralrdrK

I THE MULTIPLICATION OF 62 AND 66 IS: 4092

ii

!Wm

Figure 12.7 : Viewing the Result

126 Pang Argument to a. Function 'by, Reference


The second method of passing argument to a function is by passing the reference. When we pass the arguments by reference, the value of the variable is also modified outside the function. For example, to create a function that calculates the dearness allowance: Open a new file in the text editor. Enter the following code to create a form that accepts the basic salary:

<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

V 1 . 0 (c) 2004 Aptech Limited

Page 145 of 274

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

Edit View -Go Bookmarks Tools Reload Stop

Print

.,j Home 1

XfBookmarks e Red Hat Network @tsupport QShop CI Products QTM

ENTER YO UR BASIC SALARY:

DEARNESS ALLOWANCE

Done

Figure 12.8 : Dearness Allowance Form 9. ., E n t e r


:

20000: as the biiksadary.

10. Click the DEARNESS ALLOWANCE button. The output appears, as shown in Figure 12.9.

age 146 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

('A'Pr'EC'ff

Session 12

0 RLDWI WE

Functions in PHP

Figure 12.9 : Viewing the Dearness Allowance

12.7 Setting Defabult Values for an Argument


We can also assign default values to the arguments. We must assign a default value to the argument in the function definition. Now, even if the user tries to pass different arguments, the function would process only the default value
;:--or

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.

.-.

z: Scripting with PHP

V 1. 0 ( 0 2 004 Ap te ch L imit e d

Page 147 of 274 H l

1 Fil Edit Vi

G B k

k T l Wi d

Session 12

(APmcm
WORLDWIDE

Functions in PHP

Figure 12.10 : Displaying the Sum

12.8 Returning Vail

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.

Page 148 of 274

File

V 1.0 @ 2004 Aptech Limited

Web Scripting with PH,

Session 12

(APYWCH
~,W" LD-W-I 0 E

Functions in PHP

4. Enter the following code to calculate the cube of the number:


<?php

i4-

sz 0 W

Figure 12.11 : Cube Form


8. 9. Enter 10 in the Number text box. Click the CUBE,, qq:..The cube of the numbe appears,as shown in-Figure 12.12. re

11

Scripting with PHP

V 1.0 @ 2004 Aptech Limited

z4fi...

Page 149 of 274

1Session 12
WORLDWIDE

Functions in PHP

File Edit View Go Bookmarks Tools Window Help

31
! a H o m e 1

V$ '..

4k T';rks eRed Hat Network (,,Isupport Ljshop (4yroducts ffftTralnin

\3 ' ' L

4 http://localh

4* Search

G4 Print

The Cube of 10 is: 1000

G9 Done Figure 12.12 : Displaying the Cube

12.9 -Creatigg Recupive


A function can call itself. When a function calls itself several times, the process is termed as recursion. For example, to generate the Fibonacci series using the recursive function: 1. 2. Open a new file in the text editor. Enter the following code:

<?php $A=O; function fib($A) { if ($A<=1) { return $A; I else


f

return fib($A-1)+fib($A-2); } while($A!=10) { $B=fib($A); echo "$B<BR>" $A++ ;

Page 150 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

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.

File Edit View Go Bookmarks Tools Window Help

Back

Forward
I

4L httn://I(lv Seamh Reload Stop ___________________________________

41

!3
0

Home 4Bookmarks

eRed Hat Network C4-Support (AShop 8-Products al

Tr

Figure 12.13 : Displaying the Fibonacci Series

~/~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:

Page 152 of 274

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.

Defin;tng an.- Arra


variable can store only one value at a time. We can change the value of the variable as many times as we want in the program. However, we can store only one value in the variable. An array is a variable that can store a set of values of the same data type. Each value in an array is termed as an element. All the elements are referenced by a common name. Each element of an array can be referred by an array name and an index. An array index is used to access an element. An index can be a number or a string. If the index is a string, the array is an associative array. If the index is a number, the array is an indexed array. By default, the index value in an array starts at zero. As a result, the index number of the last element in an array is one less than the total number of elements- For example, if there is in an array of five elements, the index number of the last element will be four.
I

I--

Scripting with PHP

V 1.0 (c- 2004 Aptech Limited

Page 153 of 274

Session 13

(AiMI-EC'N \17-ort LOWIDE

Working with Arrays

PHP provides us with two ways of initializing an array:


array ( function Enables to assign value to all the elements of an array

array identifier Enables to assign value to a specific element of an array

13.2.1 The arrayffunction,


We can create an array and set the initial values of array elements using the array ( ) function. The arrayo function uses key value pairs separated by a comma to create an array. The number of key value pairs in the array() function determines the number of elements in an array. The syntax for creating an array using the array() function is: $array_name = array([key => ] value, [key => Where, );, >
array_name - Specifies the array name key - Specifies the index value of the array element. The key can be a string or an integer.

value)

value - Specifies the value of the element

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.

Page 154 of 274

(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

denartment = array("a" 'HR', "d" => 'Purchase')

'Finance', "b" => 'Sales',

In the above code snippet, the array index type is a string. Note the index value starts from a. The
index values are specified within double quotes. The department array contains .three values

Finance, Sales, and HR. To view the value of the third element, enter the following: echo $dcpartment["c"]; Note the result of the above code would be HR.

13.2.2 The Array Identifier


Using the array identifier, we can initialize value of a specific element in an array. The syntax for creating an array using the array identifier is: Sarray rl amo[key] Where, > arryname - Specifies the name of the array ke y - Specifies the index value of the array element. The key type can be a string or an integer. > element_value - Specifies the value assigned to the element of the array "element value";

?,.- -:

Scripting with PHP

V 1. 0 0 ) 2 004 Ap te ch L imit e d

Page 155 of 274