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

Web and Internet Technologies

(As per the Syllabus of JNTUA, JNTUH, and JNTUK)

Sreedhar Jinka | Praveen Kumar Donta | BaijNath Kaushik


2
3

About Authors
Dr. Sreedhar JinkaCurrently working as a Associate Professor in the Department of Computer Sci-
ence and Engineering in a premier Institute named as B.V.Raju Institute of Technology-Autonomous,
Vishnupur Narsapur, Medak, Telangana, India. He is having 14 years of teaching experience and he
has been awarded with PhD in Computer Science and Engineering in Jawaharlal Nehru Technologi-
cal University Kakinada which is a largest technical university in India. Worked as Principal, Vice
Principal, HoD, Professor, Associate Professor, Assistant Professor in various premier institutions.
He completed Master of Technology in Andhra University College of Engineering Vizag, Andhra
Pradesh, India. He is a member of Computer Society of India, IAENG and GSRD. He is a Convener
for National Conference and Workshops and Organizer for International Conferences. He has
attended good number of workshops on Internet of Things, Big Dat Analytical Tools, Machine
Learning Techniques, Python and so on and also he has organized good number of workshops on
Big Data with Hadoop and R Programming, Linux Programming and so on. Apart from teaching
he was involved in Research and Development activities and as part of this he has published more
than 20 research articles in National and International Conferences and Journals. He also published
"Cracking The C Interviews" in LAP-LAMBERT Publishing from Germany. Interested subjects are
Programming in C, C++, JAVA, Python, PHP & R, Operating Systems, Compiler Design, Formal
Languages and Automata Theory, Algorithms, Storage Area Networks and Big Data. Research
areas are Big Data Analytics.

Praveen Kumar Donta, Currently Ph. D Research scholar (Full-Time) in Indian Institute
of Technology(Insian School of Mines), Dhanbad from the Department of Computer Science
& Engineering. He is Former Assistant professor at Bapatla Engineering College, Bapatla, AP
, Sree Venkateswara College of Engineering, Nellore, AP and Sri Venkatesa Perumal College
of Engineering and Technology, Puttur, AP. He received Master in Technology and Bachelor in
Technology JNTUA Ananthapuramu. He had certificates like PGDCA from Ministry of HRD
recognized institute, Technical Teacher Training from NITTTR, Chennai , Basics of Computer
from NIIT, Big Data Analytics With Hadoop and RHadoop. He Published International journal and
International conference proceedings in IEEE, ACM and Springer. He also published "Cracking
The C Interviews" in LAP-LAMBERT Publishing from Germany. Given FDP and seminars on
Big data analytics in various colleges in AP. He also given placement oriented training in various
engineering colleges in AP. He is a member of SWIDC, CSTA, UACEE, IAENG and Swecha.
Interested subjects are Programming in C, C++, JAVA, Python, PHP & R, Operating Systems,
Algorithms, Storage Area Networks and Big Data. Research areas are Big Data Analytics.

Dr. BaijNath Kaushik have completed Ph.D. in CSE from Indian Institute of Technology
(Indian School of Mines, Dhnabad), March, 2016. He have done Master of Technology (Information
Technology) from Guru Gobind Singh Indraprastha University, New Delhi, 2009. He have done
B.E. in CSE from Nagpur University, 1997. He proven track record in teaching (19 Years), research
(2 Science Citation Index, 6 Scopus and overall, 2 SCI under review, total 32+ publications),
sound theoretical and extensive research back ground makes me excellent match for the academic
environment. Also, the role excites me because he love to learn new technology and skills to
impart knowledge to the students. He know that the students will take benefits from knowledge and
wisdom for their successful orientation towards their goal achievements.
Contents

1 Introduction to Web Technologies ...................................................... 13


Working of Internet 13
Client-Server ........................................................................................................................13
World Wide Web(WWW) 14
Hyper Text Markup Language .........................................................................................15
Uniform Resource Locator ................................................................................................15
Hyper Text Transfer Protocol .............................................................................................15
Web Servers 17
Apache Web Server ..........................................................................................................18
Internet Information Server (IIS) .......................................................................................18
XAMPP (Bundle Server) .....................................................................................................19
WAMP (Bundle Server) ......................................................................................................20
Installation of Web Servers 20
Installing Apache and PHP on Windows .......................................................................20
Installing Apache for Linux ...............................................................................................28
Installing IIS and PHP on Windows ...................................................................................29
Installing a XAMPP on Linux ..............................................................................................30
Installing XAMPP on Windows .......................................................................................... 31
Installing WAMP ..............................................................................................................................34
Apache Tomcat.............................................................................................................................39
Install Tomcat 7 ...................................................................................................................40
Hypertext Markup Language 42
HTML5 47
HTML5 Advantages for End User ..................................................................................... 47
New Elements included in HTML5 ................................................................................... 47
New Form Elements in HTML5 ..........................................................................................49
New Input Types introduced in HTML5 ...........................................................................50
XHTML 50
CSS 51
1.9 CSS3 55
1.9.1 New Features in CSS3 ........................................................................................................56
1.10 Exercise 56

2 Java Script ............................................................................................. 57


JavaScript Datatypes 58
JavaScript Variables 58
JavaScript Variable Names..............................................................................................59
JavaScript - Functions 60
Function Definition .............................................................................................................60
Function Parameters ......................................................................................................... 61
The return Statement......................................................................................................... 61
JavaScript - Event Handling 62
onclick Event Type ........................................................................................................................62
onsubmit Event type..........................................................................................................63
onmouseover and onmouseout .....................................................................................63
JavaScript - Document Object Model or DOM 64
DOM compatibility ............................................................................................................ 64
JavaScript Date Object 65
The Date object .................................................................................................................65
The Most Common Date Methods .................................................................................66
Examples of Date Object .................................................................................................66
JavaScript Regular Expression 69
Categories of Pattern Matching Characters ...............................................................70
Examples..............................................................................................................................72
JavaScript - Form Validation 72
Basic Form Validation...................................................................................................................73
Data Format Validation...............................................................................................................74
DHTML with JavaScript 75
Exercise 75

3 Servlets................................................................................................... 77
Common Gateway Interface 78
Servlet Tasks 78
Servlets - Life Cycle 79
Architecture 80
Servlet API 80
Reading Servlet Parameters 82
Reading Initialization Parameters 84
HTTP Request 86
Methods to read HTTP Header ........................................................................................ 87

HTTP Header Request Example .......................................................................................88


HTTP Response 89
Methods to Set HTTP Response Header .........................................................................90
Servlets - Cookies Handling 92
The Anatomy of a Cookie ................................................................................................92
Servlet Cookies Methods ..................................................................................................92
Setting Cookies with Servlet .............................................................................................93
Servlets - Session Tracking 95
Accessing a Database using Servlet 97
Exercise 98

4 Java Server Page-JSP ......................................................................... 101


JSP - Architecture 101
JSP Processing 102
JSP Declarations 103
JSP Expression 103
JSP Comments 104
A Test of Comments.........................................................................................................104
JSP - Directives 104
JSP - The page Directive .................................................................................................105
Accessing JavaBeans 106
Accessing JavaBeans Properties ..................................................................................106
JSP - Cookies Handling 107
The Anatomy of a Cookie ..............................................................................................107
Reading Cookies with JSP ..............................................................................................109
Delete Cookies with JSP..................................................................................................110
JSP - Session 111
Maintaining Session Between Web Client And Server ..............................................111
The session Object ...........................................................................................................111
Session Tracking Example ...............................................................................................112
Deleting Session Data .....................................................................................................114
JSP Database Connection 114
Create Table ................................................................................................................................ 114
Select..................................................................................................................................116
Insert ...................................................................................................................................117
Delete.................................................................................................................................117
Update ...............................................................................................................................118
compare JSP and servlet 119
Exercise 120

5 Introduction to PHP ............................................................................. 121


Server Side Programming 121
Introduction to PHP 123
Difference between HTML & PHP..................................................................................124
Features of PHP.................................................................................................................124
The anatomy of a PHP Page 125
Embedding PHP Code in Your Web Pages .................................................................125
Commenting Your Code ................................................................................................127
Outputting Data to the Browser ....................................................................................128
Identifiers 130
Variables 130
Variable scope .................................................................................................................131
Variable variables ............................................................................................................132
Constants 133
Data Types 134
Scalar Data Types ............................................................................................................134
Compound Data Types ..................................................................................................135
Expressions 135
Operators 136
Arithmetic Operators.......................................................................................................136
Assignment Operators ....................................................................................................136
Bitwise Operators .............................................................................................................137
Comparison Operators ...................................................................................................138
Error Control Operators ...................................................................................................138
Execution Operators........................................................................................................138
Incrementing/Decrementing Operators .....................................................................139
String Operators................................................................................................................139
Logical Operators ............................................................................................................139
Array Operators ................................................................................................................139
Operator Precedence ....................................................................................................140
Operator Associativity .....................................................................................................140
Statements 141
Conditional Statements ..................................................................................................141
Looping Statements ........................................................................................................143
return ..................................................................................................................................148
require ................................................................................................................................148
include ...............................................................................................................................148
Arrays 149
Creating Arrays.................................................................................................................149
Accessing Array Elements ..............................................................................................150
Outputting an Array ........................................................................................................151
Adding and Removing Array Elements .......................................................................151
Searching an Array ..........................................................................................................152
Sorting an Array ................................................................................................................153
Reversing Array Element Order .....................................................................................153
Strings 153
Single-Quoted Strings ......................................................................................................154
Double-Quoted Strings ...................................................................................................154
Here Documents (heredocs) .........................................................................................154
String Manipulation Functions........................................................................................155
Regular Expressions 156
Character Classes............................................................................................................156
Functions 157
Pre-define Functions ........................................................................................................157
User-Defined Functions ...................................................................................................157
Programming Exercise 160
Using Cookies 162
Setting Cookies.................................................................................................................162
Reading Cookies..............................................................................................................163
Deleting Cookies ..............................................................................................................163
Using HTTP Headers 164
Redirecting to a Different Location ..............................................................................164
Sending Content Types Other Than HTML ...................................................................166
Forcing File “Save As” Downloads ................................................................................166
Using Sessions 167
Setting Sessions .................................................................................................................167
Reading Sessions ..............................................................................................................168
Deleting Sessions ..............................................................................................................168
Storing Simple Data Types in Sessions...........................................................................168
Storing Complex Data Types in Sessions ......................................................................169
Authenticating Your Users 170
Using Environment and Configuration Variables 171
Reading Environment Variables....................................................................................171
Reading Configuration Variables .................................................................................171
Setting Environment Variables.......................................................................................171
Setting Configuration Variables ....................................................................................172
Working with Date and Time 172
5.21.1 time() ..................................................................................................................................172
5.21.2 date() .................................................................................................................................172
checkdate()......................................................................................................................173
mktime().............................................................................................................................173
strtotime() ..........................................................................................................................174
getdate() ...........................................................................................................................174
strptime()............................................................................................................................174
Programming Exercise 175
Exercise 175

6 XML- eXternal Markup Language..................................................... 177


XML Syntax 178
XML Declaration ...............................................................................................................178
Tags and Elements ...........................................................................................................179
Syntax Rules for Tags and Elements ..............................................................................179
Element Syntax: ................................................................................................................179
Nesting of elements: ........................................................................................................179
Attributes 180
Syntax Rules for XML Attributes 180
Attribute Types ..................................................................................................................181
XML Document Type Declaration 181
Internal DTD .......................................................................................................................182
External DTD ......................................................................................................................183
XML-Schemas 184
Definition Types.................................................................................................................185
Document Object Model 186
XML - Parsers 187
Extensible Stylesheet Language (XSL) 188
XSL Transformations..........................................................................................................189
News Feed 190
RSS-(Really Simple Syndication) ....................................................................................191
ATOM .............................................................................................................................................. 191
RSS vs ATOM.................................................................................................................................. 192
Exercise 193

7 Creating and Using Forms.................................................................. 195


Understanding Common Form Issues 195
GET vs. POST ......................................................................................................................197
Validating form input .......................................................................................................199
Working with multiple forms ...........................................................................................202
Redisplaying Forms with Preserved Information and Error Messages ....................206
Global & Superglobal variables 208
Preventing Multiple Submissions of a Form 209
Preventing Multiple Submissions on the Server Side ..................................................209
Preventing Multiple Submissions on the Client Side...................................................210
Handling Special Characters 211
File Uploads 212
Basic Database Concepts 212
Connecting to a MySQL Database..............................................................................212
Querying the Database..................................................................................................213
Retrieving and Displaying Results..................................................................................216
Deleting Data ...................................................................................................................219
Modifying Data ................................................................................................................220
MySQL Functions in php 222
mysql_connect() ..............................................................................................................222
mysql_close() ....................................................................................................................223
mysql_select_db() ............................................................................................................223
mysql_query() ...................................................................................................................223
mysql_fetch_array() .........................................................................................................224
mysql_fetch_row() ...........................................................................................................224
mysql_fetch_assoc() ........................................................................................................225
More MySQL functions ....................................................................................................225
Model View Controller(MVC) Architecture 225
Exercise 226
8 AJAX-Asynchronous JavaScript And XML . . . . . . . . . . . . . . . . . . . . . 229
8.1 How to make an HTTP request 229
8.2 Handling the server response 231
8.3 Working with the XML response 231
8.4 AJAX-Call Back 232
8.5 Exercise 233

9 Web services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235


9.1 Web service Architecture 235
9.2 Types of Web services 237
9.3 Java Web Services 237
9.3.1 Example: Hello World JAX-WS Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
9.4 WSDL – Web services description language 238
9.4.1 WSDL Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
9.5 SOAP Introduction 239
9.6 Exercise 239

A Sample Source Codes for Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241


A.1 Sample Source Codes 241
A.1.1 Config.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
A.1.2 login.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
A.1.3 logout.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242

B Interview Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247


1. Introduction to Web Technologies

Introduction to Web Technologies: Introduction to Web servers like Apache 1.1,IIS XAMPP(Bundle
Server), WAMP(Bundle Server),Handling HTTP Request and Response ,installations of above
servers,HTML and CSS: HTML 5.0 , XHTML, CSS 3.

*********************

Working of Internet
Although the physical network connections, the hardware communication devices and the software
communication protocols are required for communication across the Internet, the application
software provide useful functionality.
In a network application, two application programs participate in any communication: one
application initiates communication and the other accepts it. This is known as the Client-Server
interaction. This is the methodology used for internet communication.

Client-Server
Client and Server are two applications involved in communication. These components work
together over a network. It involves the client requesting serve from the server. The Server provides
the requested service.
The typical features of the Client are:
• It is front-end of an application. It
• manages user-interface portion.
• It validates data entered by the user.
• It dispatches requests to server program.
The typical features of the Server are:
• Performs a back-end task.
• Receives requests from clients.
• Executes database retrievals and updates.
• Manages data integrity.
14 Chapter 1. Introduction to Web Technologies

• Dispatches response to clients.


Web Browsers
A Web browser is a software program that is used to access the World Wide Web(WWW). It allows
users to view Web pages and navigate between them.
Examples of Web Browsers are : Mozilla, Microsoft Internet Explorer, Opera, Crome, Netscape
etc,.
Web Browsers are known as Universal Clients because they act as the common Client for all
Web-based applications. They are the Web Clients that request services from a Web Server, Which
is located some where on the Internet or Intranet.

Server Program & Server System


Genrally, the term ‘Server’ refers to a program that waits for a request and provides service.
However, a Computer that runs many such Server programs is also known as a Server.
Computers that have fast CPUs, large memories and powerful operating systems are also called
Server Machines(or Server Systems or Server Computers).
“A Server is the program that provides Service to a client”.

Working of Server
A server offers one or more Services to clients. By default, it does not do any processing until a
client sends in a request. It waits for a client to make a request. This is known as ‘listening’ mode
of the server.
A typical client server interaction happens as follows:
1. The client sends a request for a server.
2. On receiving a request, the service assigns one of the threads in the pool to process the task
and continues to wait for further request.
3. The thread executes the code for the requested service.
4. After execution, it sends the response back to the client.
5. It then returns to the thread pool.

Figure 1.1: Working of Server

World Wide Web(WWW)


The World Wide Web(WWW) is an information sharing model that allows accessing information
over the medium of the Internet. It is the collection of electronic documents that are linked together.
These electronic documents are known as ‘Web Pages’. A collection of related Web Pages is known
as a ‘Web Site’.
1.2 World Wide Web(WWW) 15

A Web Site is resides on Server computers that are located in around the world. Information on
the WWW is always accessible, from anywhere in the world.
The basic architecture is characterized by a Web Browser that displays information content and a
Web Server that transfer’s information to the client.
This architecture depends on three key standards for creating, publishing and finding Web
documents on the Web:
HTML: Hyper Text Markup Language For creating and editing document content.
URL: Uniform Resource Locator For locating resource on the Internet.
HTTP: Hyper Text Transfer Protocol For transfer the data.

HTML: Hyper Text Markup Language


HTML is the authoring language used to create documents on the WWW. HTML makes documents
readable across variety of computing platforms. More refer section1.5

URL: Uniform Resource Locator


URL is the unique address that identifies each web page or a resource on the Internet. It indicates
where the web pages is stored on the Internet. URL is the standard way of addressing resources on
the Internet that are part of WWW.
It supplies the Internet Address of a resource on the WWW, alone with protocol by which the
resource is accessed. URLs are used by Web Browsers to connect to a specific server and to get a
specific document or page on the Web.
The URL looks like

HTTP: Hyper Text Transfer Protocol


Web browsers and Web Servers communicate with each other using the HTTP. It is a simple
protocol, which standardizes the way requests are sent and processed. This allows different Clients
to communicate with any vendor’s server without compatibility problems.
HTTP is an application level protocol of the TCP/IP suite, which is used to deliver virtually all
files and other data on WWW.
It is used to transmit resources that are identified by URL. The most common kinds of a
resources can be a file, but it can also be dynamically generated content, which is the result of
execution of a script or an application on the server.
Features of the HTTP protocol:
• Simple request-response model based protocol.
• Application layer protocol built on TCP/IP.
• Plain-text protocol(Non-Secure)
16 Chapter 1. Introduction to Web Technologies

• Stateless protocol
• Does not define how network connection is initiated or managed
• Standardized.

HTTP Request-Response
HTTP is a simple Request-Response protocol. A HTTP Client, such as a Web Browser initiates a
request by establishing a TCP/IP connection to a particular port on a remote host. A HTTP Server
listening on that port waits for the Client to send a request, upon receiving the request, the server
send back a response.

Figure 1.2: HTTP Request-Response

1. A HTTP Client initiates a connection to the Web Server.


2. Once the connection is established, it sends a Request message to the Server.
3. To this message, the server returns a response.

HTTP Request
The HTTP Request has the following message format for transferring entities: A request line,
Zero or more header lines, A blank line which separates the headers from the message body. The
request line of the HTTP request includes:
• The method to be applied on the resource.
• The identifier of the resource.
• The Protocol version in use.
The method filled in request line of HTTP indicates the method to be performed on the object
identified by the URL. Some methods are: GET, POST and HEAD.
GET The GET method is most frequently used method. It is used by default to GET static content.
The method can also be used to submit data from a HTML Web Page to the Server. In GET
method, the data submitted will be sent as a part of the URL. Hence, in GET method:
• Parameters are encoded and passed along with the URL.
• Usually, parameters are passed as name-value pair.
• There is a physical restriction on the size of it being sent.
POST A POST method is used to send data as a part of the HTTP message body. In Certain cases
the Client may need to send megabytes of information. In these situations POST method is
the right choice.
Web Servers 17

A POST request passes all its data of unlimited length, directly as a part of its HTTP request
body. The exchange is invisible to client. The URL does not contain the data submitted.
Consequently, POST requests cannot be book marked or emailed or in some cases, even
reloaded.
Hence, confidential information sent to the Server, such as the credit card number, should be
sent via post method.
HEAD The HEAD method is similar to GET method, except that it asks the server to return
only the Response headers and not the content. This method is useful for client to check
the characteristics of the resource without actually downloading it, thus saving bandwidth.
HTTP Clients usually use the HEAD method when they do not need the files contents. When
HEAD used:
• To determine the document’s size.
• To know the document’s modification time.
• To know general availability of a Web Page.
HTTP Response
In response to a HTTP Request sent by a HTTP Client, the server sends a HTTP Response. The
HTTP Response to requests is usually a program output and not a static file. The first line of a
Response message is a status line. It consists of
• The protocol version
• Numeric status code
• Description of the status code
HTTP status code The response status line contains the status of processing of the HTTP request.
In case of success, it will contain the status code 200 and description “OK”. The status line
in this case will be: In case of error, the server sends an appropriate error code back to the

HTTP/1.0 200 OK

Client. The HTTP error codes are standardized. Some of the commonly found error codes:
The error or success code of the HTTP response are standardized in the following manner:

HTTP/1.0 404 Page Not Found


HTTP/1.0 500 Internal Server Error

1XX Indicates informational message only.


2XX Indicates success of some kinds.
3XX Redirects the Client to another URL.
4XX Indicates an error on Client’s port.
5XX Indicates an error on Server’s port

HTTP Response Headers The Response nust contain header line describing the following.
• MIME-type of the data being sent in response.
• Date and Time stamp.
• Content size etc.
The HTTP Response message body contains the required data.

Web Servers
A Web Server is a server program running on a computer whose purpose is to serve Web Pages to
other computer when required. Every computer on the Internet that contains a Web site will have a
18 Chapter 1. Introduction to Web Technologies

Web Server program.


Examples of Web Servers:
1. Apache Web Server
2. Microsoft Internet Information Server (IIS)
3. XAMPP (Bundle server)
4. WAMP (Bundle server)

Apache HTTP Server


The Apache HTTP Server, commonly referred to as Apache, is a web server program notable
for playing a key role in the initial growth of the World Wide Web (WWW). It became the first
web server software to exceed the 100 million web site mile stone. Typically Apache is run on a
Unix-like Operating system, and was developed for use on Linux.
Apache is developed and maintained by an Open community of developers under the support
and approval of the Apache Software Foundation (ASF). The application is available for wide variety
of operating system, including Unix, Free BDS, Solaris, Linux, Novel Netware, OSX, Microsoft
Windows, OS/2 etc., Released under the Apache license, Apache is open-source software.
The main design goal of Apache is not to be the fastest Web server, Apache does have
performance similar to other “high-performance” Web Servers. Instead of implementing a single
architecture Apache provide a variety of Multi Processing Modules (MPMs) which allow Apache
to run process-based, where compromises in performance need to be made, the design of Apache is to
reduce latency and increase throughput, relative to simply handling more requests, thus ensuring
consistent and reliable processing or requests within reasonable time frames.

Features of Apache
• It implemented as compiled modules which extend the core functionality, thus the range from
server-side programming support to authentication scheme.
• Password-protected pages for a multitude of users(It supports password authentication and
digital certificate authentication).
• Customized error pages.
• Display of code in numerous levels of HTML, and the capability to determine at what level
the browser can accept the content.
• Virtual hosting allows one Apache installation to serve many different actual Websites.
• Usage and error logs in multiple and customizable formats
• DirectoryIndex directives to multiple files.
• URL aliasing or rewriting with no fixed limit

Microsoft Internet Information Server (IIS)


It is the second most popular Web Server software. It consists of Services including File Transfer
Protocol (FTP), Hyper Text Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP)
and others that enable a Windows machine to manage Websites. The latest version (IIS 7.6) also
includes various modules for security, logging compression and diagnostics.
Because of IIS is provided for Windows systems only, the choice to use IIS necessitates the
choice of a Windows Server and therefore increases running costs. Windows is also prone to more
malware attacks, and has a reputation as a less secure server option.
But this presents a problem if you’d like to develop and even deploy your PHP-driven web
site on a Windows server running Microsoft’s IIS web server. In recent years, Microsoft, in
collaboration with Zend Technologies Ltd., has made great strides towards boosting both the
stability and performance of PHP running on both Windows and IIS.
1.3 Web Servers 19

Features:

IIS has a modular architecture. Modules, also called extensions, can be added or removed individu-
ally so that only modules required for specific functionality have to be installed.
• Security Module: Used to perform many tasks related to security in the requesting-processing
pipeline (Authentication Scheme, URL authentication)
• Content Module: Used to perform tasks related to content in the requesting-processing
pipeline (Such as processing requests for static pages, returning default page etc.,)
• Compression Module: Used to perform tasks related to compression in the requesting-
processing pipeline (Such as compression responses, performing pre-compression of static
content.)
• Caching Module: Used to perform tasks related to caching in the requesting-processing
pipeline (Such as storing processed information in the memory on the server and using
cached content in subsequent request for the same resource.)
• Logging and Diagnostics Module: Used to perform tasks related to Logging and Diagnostics
in the requesting-processing pipeline (Such as passing information and processing status to
HTTP.sys for logging, reporting events, and tracking requests currently executing in worker
processes.)
• IIS 7.5 includes additional security features: Client-certificate mapping, IP security, Request
filtering, URL authentication.

XAMPP (Bundle Server)

XAMPP is a free and open-source cross platform Web Server Solution stack package, consisting
mainly of Apache HTTP Server, MySQL database, and interpreter for scripts written in the PHP
and Perl programming languages.
X: Cross-Platform
A: Apache
M: MySQL
P: PHP
P: Perl
Officially, XAMPP’s designers intended it for use only as a development tool, to allow Web
site designers and programmers to test their work on their own computer without any access to the
Internet. To make this as easy as possible many important security features are disabled by default.
XAMPP sometimes used to actually Server Web Pages on the World Wide Web.
Note: XAMPP is also provided support for creating and manipulating databases in MySQL
and SQL Lite among others.

Benifits

• Self contained, multiple instances of XAMPP can exist on a single computer, and any given
instance can be copied from one computer to another.
• It automatically starts at system logon.
• You can start and stop Web Server and database stack with one command.
• Run in back ground.
• XAMPP is portable so you can carry it around on a thumb drive.
• The security settings are strict by default, nobody but you will be able to access the Web
Server.
• PHP error reporting is enabled by default, which helps when debugging scripts.
20 Chapter 1. Introduction to Web Technologies

WAMP (Bundle Server)


WAMP is the bundle of Apache, MySQL and PHP for Windows. These are the things you need to
run a dynamic web sites on your computer in Windows. i.e equal to XAMPP.
Some of the bundle servers are:
LAMP: Linux, Apache, Mysql, PHP.
SAMP: Solaris, Apache, Mysql, PHP.
MAMP: Mac OS, Apache, Mysql, PHP.

Installation of Web Servers


Installing Apache and PHP on Windows
Apache needs to be installed and operational before PHP and MySQL
1. Download the Apache 2.x Win32 MSI installer binary. It’s downloadable from http://httpd.apache.org/.
Select the “Download froma mirror” link on the left side of the page and download the best
available version. A mirror is a download location. The file that you save to your desktop
will be named similarly to apache2.2.4-win32-x86-nossl.msi (the exact version number will
vary).
2. Install Apache using the Installation Wizard. Double-click the MSI installer file on your
desktop, and you see the installer shown in Figure 1-3

Figure 1.3: The Installation Wizard prompts you for basic configuration

3. Accept the license terms by clicking the radio button shown in Figure 1-4. Click Next.
4. You’ll see a Read This First box, as shown in Figure 1-5. Additionally, this window offers a
number of excellent resources related to the web server. Click Next.
5. In the dialog shown in Figure 1-6, enter all pertinent network information. Click Next.
6. In the next screen, shown in Figure 1-7, select the setup type. The Typical install will work
for your purposes. Click Next.
7. Accept the default installation directory, as shown in Figure 1-8. Click Next.
8. As Figure 1-9 shows, it’s time to begin the installation. Click Install. The installer installs a
variety of modules, and you will see some DOS windows appear and disappear.
9. Click Finish when the installer is done.
10. Test your installation by entering http://localhost/ in your browser’s location field. Remember,
localhost is just the name that translates to the IP address 127.0.0.1, which is always the
address of the local computer.
1.4 Installation of Web Servers 21

Figure 1.4: Apache license terms and conditions for use

Figure 1.5: Apache HTTP Server information


22 Chapter 1. Introduction to Web Technologies

Figure 1.6: Server Network Information dialog

Figure 1.7: Selecting a setup type


1.4 Installation of Web Servers 23

Figure 1.8: Destination Folder dialog for the Apache installation files

Figure 1.9: “Ready to Install” dialog


24 Chapter 1. Introduction to Web Technologies

11. After entering the URL in your browser, the default Apache page displays, which is similar
to the one shown in Figure 1-10. The installation was successful if you see the text “It works!”
This page may be different depending on which version of Apache you install. Generally, if
you see text that doesn’t mention an error, the installation was successful.

Figure 1.10: Apache’s default index page after installation

Installing PHP
Go to http://www.php.net/downloads.php to download the latest version of PHP; both binaries
and source code can be found on this web site.
1. The file that you save to your desktop will be named similarly to php-5.2.1-win32-installer.msi
(the exact version number will vary).
2. Install PHP using the Installation Wizard. Double-click the MSI installer file on your desktop,
and you’ll see the installer shown in Figure 1-11.

Figure 1.11: The PHP MSI installer

3. Click Next. The License Terms dialog appears as shown in Figure 1-12.
1.4 Installation of Web Servers 25

Figure 1.12: The License Terms dial

4. Click the checkbox to accept the licensing terms. Click Next.


5. The Destination Folder dialog appears (see Figure 1-13). Select the destination folder. You
may use the default of C:\ Program Files\PHP or C:\PHP (examples in this book that modify
the PHP configuration files assume C:\PHP). Click Next

Figure 1.13: The installation directory for PHP

6. The Web Server Setup dialog appears as shown in Figure 1-14. Select “Apache 2.2.x Module”
and click Next. Naturally, if you were using a different web server, such as IIS, you could
select that option here.
7. The Apache Configuration Directory dialog specifies where you installed Apache so that
the installer can set up the Apache configuration to use PHP for you. It should be similar to
C: \Program Files Apache
\ \
Software Foundation Apache2.2 , as \shown in Figure 1-15.
8. Figure 1-16 shows the “Choose Items to Install” dialog. The defaults on this dialog are all
OK. If you changed the base install directory, you may also need to change it here. Click
Next.
26 Chapter 1. Introduction to Web Technologies

Figure 1.14: The Web Server Setup dialog

Figure 1.15: Selecting the Apache install path


1.4 Installation of Web Servers 27

Figure 1.16: The Installation Options dialog

9. Click Install on the “Ready to install” screen to confirm the installation.


10. Click Yes to confirmconfiguring Apache when the dialog shown in Figure 1-17 appears.

Figure 1.17: Dialog confirming that the installer will configure Apache

11. Click OK on the Apache Config dialog to acknowledge the successful Apache update for
httpd.conf.
12. Click OK on the Apache Config dialog to acknowledge the successful Apache update for
mime.types.
13. The Successful Installation dialog appears.
14. Restart the Apache server by selecting Start → All Programs→ Apache HTTP Server 2.x.x
→ Control Apache Server → Restart, so that it can read the new configuration directives that the
PHP installer placed in the httpd.conf configuration file. This file tells Apache to load the PHP
process as a module. Alternatively, in the system tray, double-click the Apache icon
and click the Restart button.
28 Chapter 1. Introduction to Web Technologies

Installing Apache for Linux/UNIX


To download the Apache distribution for Linux, start at the Apache Server Web site, http: \\httpd.apache.org \,
and follow the link to Download. The current version is 2.2.4, and I prefer *.tar.gz files, so the file
used as an example throughout this section is httpd-2.2.4.tar.gz.
1. Type cp httpd-2.2.4.tar.gz usr\ local
\ \and press Enter to copy the Apache installation file to
\ \
the usr local \ \
src directory.
\ local
2. Go to usr \ src\ by \typing cd usr local
\ src \ and\pressing
\ Enter.
3. Unzip the Apache installation file by typing gunzip httpd-2.2.4.tar.gz and pressing Enter.
4. Extract the files by typing tar -xvf httpd-2.2.4.tar and pressing Enter. A directory struc-
ture will be created, and you’ll be back at the prompt. The parent directory will be
\ local
usr \ src \ httpd-2.0.49
\ . \
5. Enter the parent directory by typing cd httpd-2.2.4 and pressing Enter.
6. Type the following and press Enter to prepare to build Apache:

./configure --prefix=/usr/local/apache2 --enable-module=so

The configuration script will run through its process of checking your configuration and
creating makefiles, and then it will put you back at the prompt.
7. Type make and press Enter. This second step of the installation process will produce many
lines of output on your screen. When it is finished, you will be back at the prompt.
8. Type make install and press Enter. This final step of the installation process will again
produce many lines of output on your screen. When it is finished, you will be back at the
prompt
If your installation process produces any errors up to this point, go through the process again or
check the Apache Web site for any system-specific notes. In the next section, you’ll make some
minor changes to the Apache configuration file before you start Apache for the first time.

Configuring Apache on Linux


To run a basic installation of Apache, the only changes you need to make are to the server name,
which resides in the master configuration file called httpd.conf. This file lives in the conf directory,
within the Apache installation directory. So if your installation directory is \usr\local\apache2\,
the configuration files will be in \usr\local\apache2\conf\.
To modify the basic configuration, most importantly the server name, open the httpd.conf file
with a text editor and look for a heading called Main server configuration. You will find two
important sections of text.
We are going to change the values in the configuration file so that Apache knows where to find
things and who to send complaints to. The ServerAdmin, which is you, is simply the e-mail address
that people can send mail to in reference to your site. The ServerName is what Apache uses to
route incoming requests properly.
1. Change the value of ServerAdmin to your e-mail address.
2. Change the value of ServerName to something accurate and remove the preceding # so that
the entry looks like this:

ServerName somehost.somedomain.com

You do not want it to look like this:

#ServerName somehost.somedomain.com

3. Save the file.


Installation of Web Servers 29

Installing PHP for Linux


To download the PHP source distribution, visit the Downloads page at the PHP Web site: www.php.net/downloads.php.
1. The current source code version is 6.0.0, and that version number will be used in the following
steps.
2. Once downloaded to your system, type cp php-6.0-dev.tar.gz /usr/local/src/ and press Enter
to copy the PHP source distribution to the /usr/local/src/ directory.
3. Go to /usr/local/src/ by typing cd /usr/local/src/ and pressing Enter.
4. Unzip the source file by typing gunzip php-6.0-dev.tar.gz and pressing Enter.
5. Extract the files by typing tar -xvf php-6.0-dev.tar and pressing Enter. This will create
a directory structure and then put you back at the prompt. The parent directory will be
/usr/local/src/php-6.0.0/.
6. Enter the parent directory by typing cd php-6.0-dev and pressing Enter.
7. Type the following and press Enter to prepare to build PHP:
./configure --prefix=/usr/local/php5 --with-mysql=/usr/local/mysql/
--with-apxs2=/usr/local/apache2/bin/apxs

The configuration script will run through its process of checking your configuration and
creating makefiles and then will put you back at the prompt.
8. Type make and press Enter. This second step of the installation process will produce many
lines of output on your screen. When it is finished, you will be back at the prompt.
9. Type make install and press Enter. This final step of the installation process will produce
many lines of output on your screen. When it is finished, you will be back at the prompt.
Now, to get a basic version of PHP working with Apache, all you need to do is to make a few
modifications to the httpd.conf file.

Configuring Apache to Use PHP


The installation process will have placed a module in the proper place within the Apache directory
structure. Now you must make some modifications to the httpd.conf file before starting up Apache
with PHP enabled.
1. Open the httpd.conf file in your text editor of choice.
2. Look for the following line, which will have been inserted into the file by the installation
process:
LoadModule php6_module modules/libphp6.so

You want this line to be uncommented, so ensure that it is (as shown).


3. Look for the following lines:
# AddType allows you to add to or override the MIME configuration
# file mime.types for specific file types.
#AddType application/x-tar .tgz

4. Add to these lines the following:


AddType application/x-httpd-php .phtml .php

5. Save and close the httpd.conf file.

Installing IIS and PHP on Windows


Microsoft took another major step towards the seamless operation of PHP and IIS by launching the
Microsoft Web Platform Installer. This installation solution makes it easy to install a wide variety
of web development stacks, IIS and PHP included. To install PHP and IIS on your Windows 7,
30 Chapter 1. Introduction to Web Technologies

Vista, Server 2003, or Server 2008 machines, head over to http://php.iis.net and click the giant
Install PHP button.
Presuming you haven’t already installed the Microsoft Web Platform Installer, you’ll next be
prompted to do so. Per usual, you’ll need administrative privileges in order to run this installer.
Once downloaded, you’ll be prompted to install PHP. The version at the time of this writing was
a bit behind the curve (5.2.14), but it should nonetheless suffice for you to work through the vast
majority of examples found in this book. Click the Install button and then read and agree to the
license terms to complete the process. Believe it or not, once the installation process is complete,
PHP has been successfully configured to run on your machine.
At the time of this writing the Web Platform Installer console is unable to uninstall PHP,
meaning you’ll need to use Windows’ native program management tool to do so manually. On
Windows 7, this tool can be accessed by clicking the Uninstall a program option within the control
panel.

Installing a XAMPP on Linux


If you know much about Linux, you may have already set up and installed PHP and MySQL. If not,
your best bet is probably to look at XAMPP for Linux, which is available at http://apachefriends.org/en/xampp-
linux.html.
The process is relatively simple. After downloading, go to a Linux shell and log in as the
system administrator (root) by typing:

su

Enter your system administration password. Many desktop Linux systems allow you to use your
personal account’s password for the administration password. Some systems, including the popular
Ubuntu, encourage you not to use su to log in as root, but to precede each system administration
command with sudo instead. You’ll know what to do if you’ve performed any administrative tasks
on your system. Now extract the downloaded archive file to /opt with the following command
(inserting the appropriate filename if the version you downloaded is a later version):

tar xvfz xampp-linux-1.6.8a.tar.gz -C /opt

Any XAMPP version that was already installed will be overwritten by this command. Once the
command finishes, XAMPP will be installed below the /opt/lampp directory. To start it, enter the
following:

/opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.6.8a...


LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.
Ready. Apache and MySQL are running.

Now you are ready to test the setup. Type the following URL into your web browser’s address bar:

http://localhost
1.4 Installation of Web Servers 31

Figure 1.18: XAMPP for Linux, installed and running

Installing XAMPP on Windows


The following steps cover installing XAMPP on Windows:
1. Download the Basic Package XAMPP MSI installer found at http://www.apachefriends.org/en/xampp-
windows.html
2. Double-click the MSI installer file on your desktop, and you’ll see the installer shown in
Figure 1-19.

Figure 1.19: The Language selection dialog

3. Select English and click the OK button.


4. The Setup Wizard appears as shown in Figure 1-20. Click Next.
5. The dialog shown in Figure 1-21 is displayed. Click Next to accept the default installation
directory.
6. The XAMPP Options dialog displays, as shown in Figure 1-22. Leave the Service Section
checkboxes unchecked so you don’t install the components as services; instead, you’ll start
them from the Control Panel. Click Install.
7. The Completing the XAMPP Setup Wizard displays. Click Finish.
8. The option to start the Control Panel displays, Click Yes.
9. The Control Panel launches, as shown in Figure 1.23. The Control Panel can start and stop
32 Chapter 1. Introduction to Web Technologies

Figure 1.20: The Xampp Setup Wizard

Figure 1.21: Select the installation directory


1.4 Installation of Web Servers 33

Figure 1.22: Choose your installation options

Figure 1.23: The Control Panel starts and stops the components
34 Chapter 1. Introduction to Web Technologies

the services, as well as aid in their configuration.

Installing WAMP
If you are installing WampServer 2.1 d, then these following step will help you that how to install
the WampServer 2.1 d in your computer with windows 7. This server can be found for download at
official web page WampServer.
1. It is the time to install WampServer on our windows. You will receive a Security Warn-
ing after opening WampServer file. It is absolutely normal to run WampServer setup on
windows.(Figure 1-24)

Figure 1.24: Instalation Starting of WampServer

2. You will see a standard setup wizard of windows after clicking Run button on security
warning dialog.(Figure 1-25)
3. You have to agree the license of WampServer before selecting installation destination at your
windows machine.(Figure 1-26)
4. It is very important step of WampServer installation. I will recommend to install WampServer
at the drive other than Windows 7 installation. Suppose your Windows 7 is install in C drive
so you should install WampServer on D, E or any other location in hard drive except C drive.
I am going to install WampServer in D drive. Now you can click on Next button after
selecting installation location for WampServer 2.1d.(Figure 1-27)
5. When you click on the Next button then a Select Additional Tasks dialog will appear on your
screen, if you would like setup to perform while installing WampServer 2. You can check
following options,
• Create a Quick Launch icon
• Create a Desktop icon
I have not interested to create any icon in the above locations, but you can do. You will be at
“Ready to Install” window after clicking Next button.(Figure 1-28)
6. Setup is now ready to begin installing WampServer 2.1d on your computer. Click on Install
button to start installation of WampServer 2.1d.(Figure 1-29)
7. Now your WampServer is starting to install in your computer.(Figure 1-30)
1.4 Installation of Web Servers 35

Figure 1.25: WampServer 2 Setup Wizard

Figure 1.26: License Agreement


36 Chapter 1. Introduction to Web Technologies

Figure 1.27: Select Destination Location of WampServer

Figure 1.28: Select Additional Tasks


1.4 Installation of Web Servers 37

Figure 1.29: WampServer 2.1d Ready to Install

Figure 1.30: WampServer Installing


38 Chapter 1. Introduction to Web Technologies

8. You will receive a dialog for choosing your default browser for WampServer. You can choose
your favorite browser for WampServer as default, or simply click “Open” if you are not sure
about the installation or executable files of your favorite browser.(Figure 1-31)

Figure 1.31: Choice of Default Browser

9. WampServer installation has completed now and setup will guide you for Apache configura-
tions in the next steps.(Figure 1-32)

Figure 1.32: Complete The Installation

10. You will notice a “Windows Firewall” standard dialog while configuring Apache by WampServer.
(You may not observe this, if your windows firewall is not active). Click on “Allow Access”
by leaving default options as such to proceed for PHP mail parameters.(Figure 1-33)
11. After allowing access to Apache server, you are at SMTP server configuration dialog. You
can specify the SMTP server and the address mail to be used by PHP when using the function
mail(). I will recommend the following values,
1.4 Installation of Web Servers 39

Figure 1.33: Apache HTTP Server

• SMTP: localhost
• Email: Your email address.
Click “Next” after putting the above values for the installation final dialog.(Figure 1-34)

Figure 1.34: PHP Mail Parameters

12. You have successfully installed WampServer 2.1 d along with Apache, MySql, PHP, php-
MyAdmin and SqlBuddy at your computer.
Click “Finish” to start WampServer along with other services. Leave “Launch WampServer 2
now” check-box checked to start WampServer automatically after installation.(Figure 1-35)

Apache Tomcat
It is an application server or web server or servlet container developed by the Apache
Software Foundation (ASF) and released under the Apache License version 2. HTTP web
servers provide an environment for Java code to run in. It includes tools for configuration
40 Chapter 1. Introduction to Web Technologies

Figure 1.35: WampServer 2 Setup Wizard Completion

and management, but can also be configured by editing XML configuration files. Most of the
modern Java web frameworks are based on servlets and Java Server Pages and can run on
Apache Tomcat, for example Struts, Java Server Faces(JSF), Spring, etc.

Install Tomcat 7
There are certain steps we must follow for configuring Apache Tomcat 7.

Step 1: Download and Install Tomcat


(a) Go to http://tomcat.apache.org/download-70.cgi then go to the Binary Distribution/Core/
and download the "zip" package (for example "apache-tomcat-7.0.40.zip", about 8MB).
(b) Now unzip the downloaded file into a directory of our choice. Don’t unzip onto the
dekstop (since its path is hard to locate). I suggest using "e:\myserver". Tomcat will be
unzipped into the directory "e:\myserver\tomcat-7.0.40".

Step 2:
Check the installed directory to ensure it contains the following sub-directories:
• bin folder
• logs folder
• webapps folder
• work folder
• temp folder
• conf folder
• lib folder
Step 3
Now, we need to create an Environment Variable JAVA_HOME.
We need to create an environment variable called "JAVA_HOME" and set it to our JDK
installed directory.
(a) To create the JAVA_HOME environment variable in Windows XP/Vista/7 we need to
push the "Start" button then select "Control Panel" / "System" / "Advanced system
Installation of Web Servers 41

settings". Then switch to the "Advanced" tab and select "Environment Variables" /
"System Variables" then select "New" (or "Edit" for modification). In "Variable Name",
enter "JAVA_HOME". In "Variable Value", enter your JDK installed directory (e.g.,
"c:\Program Files\Java\jdk1.7.0_xx").
(b) For ensuring that it is set correctly, we need to start a command shell (to refresh the
environment) and issue: set JAVA_HOME
JAVA_HOME=c:\Program Files\Java\jdk1.7.0_{xx} ⇐ Check that this is OUR JDK
installed directory
(c) Sometimes we need to set JRE_HOME also. So for creating JRE_HOME we need
to use the same procedure. Push the "Start" button then select "Control Panel" /
"System" / "Advanced system settings". Then switch to the "Advanced" tab and
select "Environment Variables" / "System Variables" then select "New" (or "Edit" for
modification). In "Variable Name", enter "JRE_HOME". In "Variable Value", enter
your JRE installed directory (e.g., "C:\Program Files\Java\jre7\").

Step 4: Configure Tomcat Server


The configuration files of the Apache Tomcat Server are located in the "conf" sub-directory
of our Tomcat installed directory, for example "E:\myserver\tomcat7.0.40\conf". There are 4
configuration XML files:
(a) context.xml file
(b) tomcat-users.xml file
(c) server.xml file
(d) web.xml file
Before proceeding, make a BACKUP of the configuration files.

Step 4(a) "conf\web.xml"; Enabling a Directory Listing


Again, use a programming text editor to open the configuration file "web.xml", under the
"conf" sub-directory of Tomcat installed directory. We shall enable directory listing by
changing "listings" from "false" to "true" for the "default" servlet. This is handy for test
system, but not for production system for security reasons. Locate the following lines (around
Line 103) that define the "default" servlet; and change the "listings" from "false" to "true".

<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Step 4(b) "conf\server.xml file"; set the TCP Port Number


The default TCP port number configured in Tomcat is 8080, you may choose any number
between 1024 and 65535, which is not used by an existing application. We shall choose 9999
in this article. (For production server, you should use port 80, which is pre-assigned to HTTP
server as the default port number.)
42 Chapter 1. Introduction to Web Technologies

Locate the following lines (around Line 69) that define the HTTP connector, and change
port="8080" to port="9999".

<Connector port="9999" protocol="HTTP/1.1"


connectionTimeout="20000"
redirectPort="8443" />

Step 4(c) "conf\context.xml"; Enabling Automatic Reload


We shall add the attribute reloadable="true" to the < Context > element to enable automatic
reload after code changes. Again, this is handy for test system but not for production, due to
the overhead of detecting changes. Locate the < Context > start element (around Line 19),
and change it to <Context reloadable="true">.

<Context reloadable="true">
......
......
</Context>

Step 4(d) (Optional) "conf\tomcat-users.xml"


Enable the Tomcat’s manager by adding the highlighted lines, inside the < tomcat − users >
elements:

<tomcat-users>
<role rolename="manager-gui"/>
<user username="manager" password="xxxx" roles="manager-gui"/>
</tomcat-users>

This enables the manager GUI app for managing Tomcat server.

Step 5: Start Server


Launch a CMD shell. Set the current directory to "<TOMCAT_HOME>\bin", and run
"startup.bat" as follows:

// Change the current directory to Tomcat's "bin"


// Assume that Tomcat is installed in "d:\myProject\tomcat"
d: // Change the current drive
cd \myProject\tomcat\bin // Change Directory to YOUR Tomcat's "bin" directory

// Start Tomcat Server


startup

Hypertext Markup Language


What is HTML
HTML is a format that tells a computer how to display a web page. The documents themselves
are plain text files with special “tags” or codes that a web browser uses to interpret and
display information on your computer.
• HTML stands for Hyper Text Markup Language
• An HTML file is a text file containing small markup tags
• The markup tags tell the Web browser how to display the page
• An HTML file must have an htm or html file extension
1.5 Hypertext Markup Language 43

HTML Tags
What are HTML tags?
• HTML tags are used to mark-up HTML elements
• HTML tags are surrounded by the two characters < and >
• The surrounding characters are called angle brackets
• HTML tags normally come in pairs like < b > and < /b >
• The first tag in a pair is the start tag, the second tag is the end tag The
• text between the start and end tags is the element content HTML
• tags are not case sensitive, < b > means the same as < B >
HTML is a markup language that gives general guidelines for displaying of information. The
format of display is specified by tags or markups. A tag is a keyword enclosed with in the
angle brackets(< .. >) and has a special signature.
An HTML document is created as an ASCII text file, which contain markup tags. They are
usually named with the suffix “.html” or “.htm”. Web documents can be created on any text
editors (notepad, gedit, edit+, notepad++ etc,.) or any one of special commercially available
HTML editors. HTML is popular because of its ease of use.

HTML document structure


An element called HTML surrounds the whole document. This element contain two sub
elements, HEAD and BODY. These are required to form any HTML document.

<HTML>
<HEAD>
</title>First Page</title>
</HEAD>
<BODY>
......
......
</BODY>
</HTML>

Here <title> is the title of the document. The title of your document is appairs in a Web
Browser. <BODY> the remaining HTML elements are contained within these tags.

Elements
Headings Inside the BODY element, heading elements H1 through H6 are generally used
for major divisions of the document. Headings are not mandatory. • H1: should be
used as the highest level of heading, H2 as the next highest, and so forth.
• You should not skip heading levels: e.g., an H3 should not appear after an H1, unless
there is an H2 between them.
<HTML>
<HEAD>
<TITLE>HEADINGS</TITLE>
</HEAD>
<BODY>
<H1>Heading 1</H1>
<H2>Heading 2</H2>
<H3>Heading 3</H3>
<H4>Heading 4</H4>
44 Chapter 1. Introduction to Web Technologies

<H5>Heading 5</H5>
<H6>Heading 6</H6>
</BODY>
</HTML>

Paragraph <p> Paragraphs allow you to add text to a document in such a way that it will
automatically adjust the end of line to suit the window size of the browser in which it is
being displayed.
Syn:<p>......</p>
Break <BR> Line breaks allow you to decide where the text will break on a line or continue
to the end of the window. There may be instances where you want the text to appear on
the next line.
A <BR> is an Empty Element, meaning that it may contain attributes but it does not
contain content.
The <BR> element does not have a closing tag.
Horizontal Rule <HR> The <HR> element causes the browser to display a horizontal
line (rule) in your document. This element does not use a closing tag.
Key attributes for use with the <HR> element are size, width, noshade, align and color.
Ex: <HR align=center width=100% color=green>
Formatting Elements • <FONT SIZE="+2">Two sizes bigger</FONT>
• <B> Bold < /B >
• < I > Italic < /I >
• <U> Underline </U>
• <EM> Emphasis </EM> browsers usually display this as italics.
• <STRONG> STRONG </STRONG> browsers display this as bold.
• <STRIKE>strike-through text </STRIKE>
• <BIG> places text in a big font </BIG>
• <SMALL> places text in a small font <SMALL>
• <SUB> places text in subscript position </SUB>
• <SUP> places text in superscript style position</SUP>
Lists
HTML supplies several list elements. Most list elements are composed of one or more <LI>
(list item) elements.
Unordered List <UL> Items in this list start with a list mark such as a bullet. Browsers
will usually change the list mark in nested lists.
You have the choice of three bullet types: Disc (default), Circle, Square.
example:
<UL TYPE="SQUARE">
<LI>List item...</LI>
<LI>List item...</LI>
<LI>List item...</LI>
</UL>

Ordered List <OL> Items in this list are numbered automatically by the browser.
<OL TYPE=1>
<LI>List item...</LI>
<LI>List item...</LI>
<LI>List item...</LI>
</OL>
Hypertext Markup Language 45

You have the choice of setting the TYPE Attribute to one of five numbering styles.

1 Arabic numbers 1, 2, 3, . . .
a Lower alpha a, b, c, . . .
A Upper alpha A, B, C, . . .
i Lower roman i, ii, iii, . . .
I Upper roman I, II, III, . . .

Definition List This kind of list is different from the others. Each item in a DL consists
of one or more Definition Terms (DT elements) , followed by one or more Definition
Descriptions (DD elements).
<DL>
<DT>HTML</DT>
<DD>Hyper Text Markup Language</DD>
<DT>Dog</DT>
<DD>A human's best friend!</DD>
</DL>
Note:- the definition is always placed indented on the next line to emphasize the
relationship.
Nested List You can nest lists by inserting a UL, OL, etc., inside a list item (LI).

Images
This element is defines a graphic image on the page. It is typically used for inline image.
Image File (SRC): This value will be a URL (location of the image).
eg:< IMGsrc = X X X /abc. j pg >
Alignment (ALIGN): This allows you to align the image on your page. The options include
Bottom, Middle, Top, Left, Right, TextTop, ABSMiddle, Baseline, and ABSBottom.
Width (WIDTH): is the width of the image in pixels. This value can be obtained from a
graphics program or can be left unspecified.
Height (HEIGHT): is the height of the image in pixels. This value can be obtained from a
graphics program or can be left unspecified.
Border (BORDER): is for a border around the image, specified in pixels. If you use an
image in an anchor you will want to set the border value to zero so that it is not outlined.

Links
< AHREF = U RL > .. < /A >:
The HREF attribute of the anchor element specifies a URL. If this attribute has a value, the
contents of the <A></A> element will be highlighted when the document is displayed in a
browser window, and Clicking on this content will cause the browser to attempt to open the
file specified by the URL.
There are three major types of links:
Internal Links: are links within a document. They help in the navigation of large documents.
Local Links: are links to documents on the local web server. Local links can be the full
URL (Complete e.g. http://www.yourdomain.com/sales/report.htm) or partial (Relative to
your current directory e.g. /sales/report.htm).
External Links: links to pages on other web servers. External links are always the full URL.

Tables
The < TABLE >< /TABLE > element has four sub-elements; Table Row < T R ><
/T R >, Table Header < T H >< /T H >, Table Data < T D >< /T D >, and Caption
46 Chapter 1. Introduction to Web Technologies

< CAPT ION >< /CAPT ION >. The Table Row elements usually contain Table Header
elements or Table Data elements. The Table Header and Table Data elements can contain
several of the body elements, which allows for rich formatting of the data in the table. A
brief HTML code sample follows:
<TABLE BORDER="1">
<TR>
<TH>Column 1 Header</TH>
<TH>Column 2 Header</TH>
</TR>
<TR>
<TD>Row 1 - Col 1 </TD>
<TD>Row 1 - Col 2 </TD>
</TR>
<TR>
<TD>Row 2 - Col 1 </TD>
<TD>Row 2 - Col 2 </TD>
</TR>
<TR>
<TD>Row 3 - Col 1 </TD>
<TD>Row 3 - Col 2 </TD>
</TR>
</TABLE>

Attributes of table are: BGColor, Width, Border, Align, Backgroung, Bordercolor etc.,

Frameset
A framed page is actually made up of multiple HTML pages. There is one HTML document
that describes how to break up the single browser window into multiple windowpanes. Each
windowpane is filled with an HTML document.
A < FRAMESET > element is placed in the HTML document before the < BODY >
element. The < FRAMESET > describes the amount of screen real estate given to each
windowpane by dividing the screen into ROWS or COLS. The < FRAMESET > will then
contain < FRAME > elements, one per division of the browser window.
<HTML>
<HEAD>
<TITLE>Framed Page<TITLE>
</HEAD>
<FRAMESET COLS="23\%,77\%">
<FRAME SRC="doc1.htm" NAME="l_pane" SCROLLING="NO">
<FRAME SRC="doc2.htm" NAME="r_pane" SCROLLING="YES">
<BODY>
</BODY>
</FRAMESET>
</HTML>

Attributes of < Frameset >


ROWS: Determines the size and number of rectangular rows within a < FRAMESET >.
They are set from top of the display area to the bottom.
COLS: Determines the size and number of rectangular columns within a < FRAMESET >.
They are set from left to right of the display area.
HTML5 47

Attributes of < Frame >


SRC: Required, as it provides the URL for the page that will be displayed in the frame.
NAME: Required for frames that will allow tarGETing by other HTML documents.
SCROLLING: Displays a scroll bar(s) in the frame. Possible values are:
NORESIZE:(Optional) Prevents viewers from resizing the frame.

Forms
HTML forms are used to pass the data to server. An HTML form can contain input elements
like text fields, check boxes, Radio buttons, Submit button and more. A form can also contain
select lists, text area, field set, legend and label elements.
< INPU T > The < INPU T > element is used to select user information. An < INPU T >
element can very in many ways, depending on type attribute.
Types are TextField, Check box, Password, radio button, submit and more.
< INPU T TY PE = T EX T >
< INPU T TY PE = Radio >
< INPU T TY PE = Password >
< INPU T TY PE = Checkbox >
< INPU T TY PE = submit >
< T EX TAREA >< /T EX TAREA > It defines multi line input.
< select > .. < /select > Defines a drop down list. The < Option > is sub-element in
< SELECT > . This tag is used to put list in dropdown. eg:
<select>
<option>CSE</option>
<option>ECE</option>
<option>EEE</option>
<option>ME</option>
</select>

HTML5
HTML5 was the latest version of HTML with many updates over time on HTML. The major
diference between HTML and HTML5 are:

HTML5 Advantages for End User


HTML5 brought about a paradigm shift for both the developers and the end users. Some of the
many advantages that it provides the end users are:
• Mobile web development support provided by HTML5.
• responsive websites.
• The eradication of the need to use Adobe Flash allows developers to provide an aesthetic
graphic-rich user experience. The use of JavaScript and MPEG4 in conjunction with HTML5
has made life a lot better for users.
• The ability to support native audio and video elements means that the users won’t have to
download additional plugins to view multimedia on your website.

New Elements included in HTML5


• < article > Defines an article in a document
• < aside > Defines content aside from the page content
• < bdi > Isolates a part of text that might be formatted in a different direction from other text
outside it
48 Chapter 1. Introduction to Web Technologies

Html Html5
1. Doctype declaration in Html is too DOCTYPE declaration in Html5 is very sim-
longer <!DOCTY PEHT MLPU BLIC” − ple ” <!DOCTY PEhtml >
//W 3C//DT DHT ML4.01//EN””htt p :
//www.w3.org/T R/html4/strict.dtd” >
2. character encoding in Html is also character encoding (charset) declaration is also
longer <!DOCTY PEHT MLPU BLIC” − very simple < metacharset = ”U T F − 8” >
//W 3C//DT DHT ML4.0Transitional//EN” >
3. Audio and Video are not part of HTML4 Audio and Videos are integral part of HTML5
e.g. <audio> and <video> tags.
4. Vector Graphics is possible with the help of Vector graphics is integral part of HTML5 e.g.
technologies such as VML, Silverlight, Flash SVG and canvas
etc
5. It is almost impossible to get true GeoLocation JS GeoLocation API in HTML5 helps identify
of user browsing any website especially if it location of user browsing any website (pro-
vided user allows it)
comes to mobile devices.
It provides local storage in place of cookies.
6. Html5 use cookies.
Using Html5 you can draw shapes like circle,
7. Not possible to draw shapes like circle, rectan-
rectangle, triangle.
gle, triangle.
JS runs in same thread as browser interface.
8. Does not allow JavaScript to run in browser. Allows JavaScript to run in background. This
is possible due to JS Web worker API in
HTML5
Supported by all new browser.
9. Works with all old browsers

10.
HTML5 49

• < details > Defines additional details that the user can view or hide
• < dialog > Defines a dialog box or window
• < f igcaption > Defines a caption for a < f igure > element
• < f igure > Defines self-contained content
• < f ooter > Defines a footer for a document or section
• < header > Defines a header for a document or section
• < main > Defines the main content of a document
• < mark > Defines marked/highlighted text
• < menuitem > Defines a command/menu item that the user can invoke from a popup menu
• < meter > Defines a scalar measurement within a known range (a gauge)
• < nav > Defines navigation links
• < progress > Represents the progress of a task
• < r p > Defines what to show in browsers that do not support ruby annotations
• < rt > Defines an explanation/pronunciation of characters (for East Asian typography)
• < ruby > Defines a ruby annotation (for East Asian typography)
• < section > Defines a section in a document
• < summary > Defines a visible heading for a <details> element
• < time > Defines a date/time
• < wbr > Defines a possible line-break

New Form Elements in HTML5


datalist
The < datalist > element specifies a list of pre-defined options for an < input > element.
Users will see a drop-down list of the pre-defined options as they input data.
The list attribute of the <input> element, must refer to the id attribute of the <datalist> element.
Example

<form action="">
<input list="Department">
<datalist id="dept">
<option value="CSE">
<option value="ECE">
<option value="EEE">
<option value="Mech">
<option value="Civil">
</datalist>
</form>

Output
The < out put > element represents the result of a calculation (like one performed by a script).
Example: Perform a calculation and show the result in an <output> element:

<form action=""
oninput="x.value=parseInt(a.value)+parseInt(b.value)">
0
<input type="range" id="a" name="a" value="50">
100 (0 to 100)+
<input type="number" id="b" name="b" value="50">
=
<output name="x" for="a b"></output>
50 Chapter 1. Introduction to Web Technologies

<br><br>
<input type="submit">
</form>

New Input Types introduced in HTML5


• color: <input type="color">
• date
• datetime
• datetime-local
• email
• month
• number
• range
• search
• tel
• time
• url
• week
New Input Attributes
• autocomplete
• autofocus
• form
• formaction
• formenctype
• formmethod
• formnovalidate
• formtarget
• height and width
• list
• min and max
• multiple
• pattern (regexp)
• placeholder
• required
• step

XHTML-(EXTENSIBLE HYPERTEXT MARKUP LANGUAGE)


XHTML is essentially identical to HTML4 (the fourth iteration of HTML), but with elements of
XML that extend HTML’s capabilities. XHTML came along before HTML5, right after HTML4,
solving for some cross-browser compatibility issues and offering a “best of both worlds” scenario.
It’s a bit stricter than HTML, providing more precise standards and specifications for how a site’s
data is broken down and transmitted. This does make it a bit unforgiving, however, and it can be
tougher to debug.
XHTML is written in the same format as an XML application, another descriptive markup
language that functions like a complement to HTML, specifically handling how data is organized.
(In markup, XML describes elements of data, while HTML displays that data.)
Much of what XHTML was designed to do has been covered with the launch of HTML5,
however, making it nearly obsolete.
CSS 51

1.8 Cascading Style Sheets


What is CSS?
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify
the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what
background images or colors are used, as well as a variety of other effects.

Advantages of CSS:
CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML pages.
You can define a style for each HTML element and apply it to as many Web pages as you
want.
Pages load faster - If you are using CSS, you do not need to write HTML tag attributes every
time. Just write one CSS rule of a tag and apply to all the occurrences of that tag. So less
code means faster download times.
Easy maintenance - To make a global change, simply change the style, and all elements in all the
web pages will be updated automatically.
Superior styles to HTML - CSS has a much wider array of attributes than HTML so you can give
far better look to your HTML page in comparison of HTML attributes.
Multiple Device Compatibility - Style sheets allow content to be optimized for more than one
type of device. By using the same HTML document, different versions of a website can be
presented for handheld devices such as PDAs and cell phones or for printing.
Global web standards - Now HTML attributes are being deprecated and it is being recommended
to use CSS. So its a good idea to start using CSS in all the HTML pages to make them
compatible to future browsers.

CSS Inclusion - Associating Styles


There are four ways to associate styles with your HTML document. Most commonly used methods
are inline CSS and External CSS.

Inline CSS - The style Attribute:


You can use style attribute of any HTML element to define style rules. These rules will be applied
to that element only. Here is the generic syntax:

<element style="...style rules....">

Attributes:

Attribute Value Description


style style rules The value of style attribute is a combination of style decla-
rations separated by semicolon (;).

Example:
Following is the example of inline CSS based on above syntax:

<h1 style ="color:#36C;"> This is inline CSS </h1>


52 Chapter 1. Introduction to Web Technologies

Embedded CSS - The < style > Element:


You can put your CSS rules into an HTML document using the < style > element. This tag is
placed inside < head > ... < /head > tags. Rules defined using this syntax will be applied to all
the elements available in the document. Here is the generic syntax:
<head>
<style type="text/css" media="...">
Style Rules
............
</style>
</head>

Attributes:
Attributes associated with < style > elements are:

Attribute Value Description


type text/css Specifies the style sheet language as a content-type (MIME
type). This is required attribute.
media screen, tty, tv, pro- Specifies the device the document will be displayed on.
jection, handheld, , Default value is all. This is optional attribute.
print, braille, aural,
all

Example:
Following is the example of embed CSS based on above syntax:
<head>
<style type="text/css" media="all">
h1{
color: #36C;
}
</style>
</head>

External CSS - The < link > Element:


The < link > element can be used to include an external stylesheet file in your HTML document.
An external style sheet is a separate text file with .css extension. You define all the Style rules within
this text file and then you can include this file in any HTML document using < link > element.
Here is the generic syntax of including external CSS file:
<head>
<link type="text/css" href="..." media="..." />
</head>

Attributes:
Attributes associated with < style > elements are:

Example:
Consider a simple style sheet file with a name mystyle.css having the following rules:

h1, h2, h3 {
color: #36C;
CSS 53

Attribute Value Description


type text/css Specifies the style sheet language as a content-type (MIME
type). This attribute is required.
href URL Specifies the style sheet file having Style rules. This at-
tribute is a required.
media screen, tty, tv, pro- Specifies the device the document will be displayed on.
jection, handheld, Default value is all. This is optional attribute.
print, braille, aural,
all

font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

Now you can include this file mystyle.css in any HTML document as follows:
<head>
<link type="text/css" href="mystyle.css" media="all" />
</head>

CSS – Colors
CSS uses color values to specify a color. Typically, these are used to set a color either for the
foreground of an element(i.e., its text) or else for the background of the element. They can also be
used to affect the color of borders and other decorative effects. You can specify your color values in
various formats. Following table tells you all possible formats:

Format Syntax Example


Hex Code #RRGGBB pcolor:#FF0000;
Short Hex Code #RGB pcolor:#6A7;
RGB % rgb(rrr%,ggg%,bbb%) pcolor:rgb(50%,50%,50%);
RGB Absolute rgb(rrr,ggg,bbb) pcolor:rgb(0,0,255);
keyword aqua, black, etc. pcolor:aqua;

Examples
Set the background color:
Following is the example which demonstrates how to set the background color for an element.
<p style="background-color:aqua;">
This text has a yellow background color.
</p>

Set the background image:


Following is the example which demonstrates how to set the background image for an element.
<table style="background-image:url(/images/img1.gif);">
<tr><td>
This table has background image set.
</td></tr>
</table>
54 Chapter 1. Introduction to Web Technologies

Repeat the background image:


Following is the example which demonstrates how to repeat the background image if image is
small. You can use no-repeat value for background-repeat property if you don’t want to repeat an
image, in this case image will display only once.
By default background-repeat property will have repeat value.

<table style="background-image:url(/images/img.gif);
background-repeat: repeat;">
<tr><td>
This table has background image which repeats multiple times.
</td></tr>
</table>

Set the font style:


Following is the example which demonstrates how to set the font style of an element. Possible
values are normal, italic and oblique.
<p style="font-style:italic;">
This text will be rendered in italic style
</p>

Set the font size:


Following is the example which demonstrates how to set the font size of an element. The font-size
property is used to control the size of fonts. Possible values could be xx-small, x-small, small,
medium, large, x-large, xx-large, smaller, larger, size in pixels or in %
<p style="font-size:20px;">
This font size is 20 pixels
</p>
<p style="font-size:small;">
This font size is small
</p>
<p style="font-size:large;">
This font size is large
</p>

Set the space between characters:


Following is the example which demonstrates how to set the space between characters. Possible
values are normal or a number specifying space..
<p style="letter-spacing:5px;">
This text is having space between letters.
</p>

Set the text indent:


Following is the example which demonstrates how to indent the first line of a paragraph. Possible
values are % or a number specifying indent space..
<p style="text-indent:1cm;">
This text will have first line indented by 1cm
and this line will remain at its actual position
this is done by CSS text-indent property.
</p>
1.9 CSS3 55

CSS – Links
This tutorial will teach you how to set different properties of a hyper link using CSS. You can set
following properties of a hyper link:
We will revisit same properties when we will discuss Pseudo-Classes of CSS.
• The :link Signifies unvisited hyperlinks.
• The :visited Signifies visited hyperlinks.
• The :hover Signifies an element that currently has the user’s mouse pointer hovering over it.
• The :active Signifies an element on which the user is currently clicking.
Usually these all properties are kept in the header part of HTML document.
Remember a:hover MUST come after a:link and a:visited in the CSS definition in order to be
effective. Also, a:active MUST come after a:hover in the CSS definition as follows.

<style type="text/css">
a:link {color: #000000}
a:visited {color: #006600}
a:hover {color: #FFCC00}
a:active {color: #FF00CC}
</style>

CSS – Cursors
The cursor property of CSS allows you to specify the type of cursor that should be displayed to the
user.
One good usage of this property is in using images for submit buttons on forms. By default,
when a cursor hovers over a link, the cursor changed from a pointer to a hand. For a submit button
on a form this does not happen. Therefore, using the cursor property to change the cursor to a hand
whenever someone hovers over an image that is a submit button. This provides a visual clue that
they can click it.

<p>Move the mouse over the words to see the cursor change:</p>
<div style="cursor:auto">Auto</div>
<div style="cursor:crosshair">Crosshair</div>
<div style="cursor:default">Default</div>
<div style="cursor:pointer">Pointer</div>
<div style="cursor:move">Move</div>
<div style="cursor:e-resize">e-resize</div>
<div style="cursor:wait">wait</div>
<div style="cursor:help">help</div>

CSS3
CSS3 is the advance level of CSS2.0. In CSS3 we have new properties - border radius, box shadow, text
shadow, multiple background images, gradient , animations, transition, transform and much more.
• CSS3 is divided into many different documents called Modules. Every module adds new
capability or extends features defined in CSS2 over preserving backward Compatibility.
• Work on CSS3 started around the time of publication of the original CSS2 recommendation.
• Because of the modularization in CSS3, every modules has different stability and is in
different status.
• CSS3 supported by all new browsers. The CSS3 version supports many more browsers than
CSS2.
56 Chapter 1. Introduction to Web Technologies

• CSS3 has other added features such as new combinator, new CSS selectors, new pseudo-
elements and new style properties.

1.9.1 New Features in CSS3


Combinator: New addition of General Sibling Combinator is done to match sibling elements of a
given element through tilde ( ) Combinator.
CSS Selectors: While CSS2 had ’simple selectors’, the new version calls them the components as
’a sequence of simple selectors’.
Pseudo-Elements: Many Pseudo Elements have been added that allow in-depth yet easy styling
and a new convention of double colons ’::’ has been introduced.
New Background Style Properties : Multiple Background images can be layered in the box using
different elements like background image, position and repeat. Background-clip, origin, size and
style properties have been added.
Border Style: Styling of borders has been extended to images and rounded designs which includes
creating image of the borders and then automatically apply image to the borders through
CSS. Border-radius, image-source, image-slice, and the values for width outset and stretch
have been added in CSS3.

Exercise
1. Explain in detail Apache web server and its installation procedure.
2. How to handle HTTP requests & response? Explain in detail.
3. Write a short note on client/server model.
4. What is a web server?
5. Mention any three web servers and explain them.
6. What are the different types of web servers? Discuss briefly.
7. Explain in detail WAMP web server and its installation procedure.
8. Explain in detail about form tags in HTML.
9. Explain in detail about list tags in HTML.
10. Explain in detail about table tags in HTML.
11. Differentiate HTML and HTML5.
12. What are the additional features included in HTML5? Explain.
13. Explain about different types of style sheets.
14. Differentiate HTML5 and XHTML.
15. What are the features included in CSS and CSS3? Explain.
2. Java Script

An introduction to JavaScript DOM Model-Date and Objects,- Regular Expressions- Exception


Handling-Validation-Built-in objects-Event Handling- DHTML with JavaScript

*********************

Javascript is a dynamic computer programming language. It is lightweight and most commonly


used as a part of web pages, whose implementations allow client-side script to interact with the
user and make dynamic pages. It is an interpreted programming language with object-oriented
capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java. JavaScript made its first appearance in Netscape
2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded
in Netscape, Internet Explorer, and other web browsers.
Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser. It means that
a web page need not be a static HTML, but can include programs that interact with the user, control the
browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI serverside
scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail
address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.

Advantages
• Less server interaction : You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server. Immediate feedback
to the visitors : They don’t have to wait for a page reload to see if they have forgotten to
enter something. Increased interactivity : You can create interfaces that react when the
58 Chapter 2. Java Script

user hovers over them with a mouse or activates them via the keyboard. Richer interfaces :
You can use JavaScript to include such items as drag-and-drop components and sliders to
give a Rich Interface to your site visitors.

JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language.
JavaScript allows you to work with three primitive data types :
• Numbers, eg. 123, 120.50 etc.
• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data type
known as object. We will cover objects in detail in a separate chapter.
Note: JavaScript does not make a distinction between integer values and floating-point values. All
numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using
the 64-bit floating-point format defined by the IEEE 754 standard.

JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of as
named containers. You can place data into these containers and then refer to the data simply by
naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with
the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows:
<script type="text/javascript">
<!--
var money, name;
//-->
</script>

Storing a value in a variable is called variable initialization. You can do variable initialization at the
time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later.
For another variable, you can assign a value at the time of initialization as follows.

<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
2.2 JavaScript Variables 59

//-->
</script>

Note: Use the var keyword only for declaration or initialization, once for the life of any variable
name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data
type. Unlike many other languages, you don’t have to tell JavaScript during variable declaration
what type of value the variable will hold. The value type of a variable can change during the
execution of a program and JavaScript takes care of it automatically.

JavaScript Variable Scope


The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
• Global Variables: A global variable has global scope which means it can be defined anywhere
in your JavaScript code.
• Local Variables: A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If you declare a local variable or function parameter with the same name as a global
variable, you effectively hide the global variable. Take a look into the following example.

<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>

This produces the following result

local

JavaScript Variable Names


While naming your variables in JavaScript, keep the following rules in mind.
• You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable names
are not valid.
• JavaScript variable names should not start with a numeral (0-9). They must begin with a letter
or an underscore character. For example, 123test is an invalid variable name but _123test is a
valid one.
• JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.
60 Chapter 2. Java Script

JavaScript - Functions
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small and
manageable functions. Like any other advanced programming language, JavaScript also supports
all the features necessary to write modular code using functions. You must have seen functions like
alert() and write() in the earlier chapters. We were using these functions again and again, but they
had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to write your
own functions in JavaScript.

Function Definition
Before we use a function, we need to define it. The most common way to define a function
in JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax
The basic syntax is shown here.

<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>

Example
Try the following example. It defines a function called sayHello that takes no parameters

<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>

Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of that
function as shown in the following code.

<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
2.3 JavaScript - Functions 61

</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>

Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the function
and any manipulation can be done over those parameters. A function can take multiple parameters
separated by comma.

Example
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.

<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

The return Statement


A JavaScript function can have an optional return statement. This is required if you want to return a
value from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the function to return
their multiplication in your calling program.

<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
62 Chapter 2. Java Script

return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

JavaScript - Event Handling


JavaScript’s interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to
close windows, messages to be displayed to users, data to be validated, and virtually any other type
of response imaginable.
• onLoad - occurs when a page loads in a browser
• onUnload - occurs just before the user exits a page
• onMouseOver - occurs when you point to an object
• onMouseOut - occurs when you point away from an object
• onSubmit - occurs when you submit a form
• onClick - occurs when an object is clicked

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.

Example
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
2.4 JavaScript - Event Handling 63

<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>

onsubmit Event type


onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against this event type.

Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form will be
submitted, otherwise it will not submit the data.

<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well. The
onmouseover event triggers when you bring your mouse over any element and the onmouseout
triggers when you move your mouse out from that element.

<html>
<head>
<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
64 Chapter 2. Java Script

document.write ("Mouse Out");


}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

JavaScript - Document Object Model or DOM


Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.
The way a document content is accessed and modified is called the Document Object Model,
or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document.
• Window object : Top of the hierarchy. It is the outmost element of the object hierarchy.
• Document object : Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
• Form object: Everything enclosed in the < f orm > ... < / f orm > tags sets the form object.
• Form control elements: The form object contains all the elements defined for that object such
as text fields, buttons, radio buttons, and checkboxes.
Here is a simple hierarchy of a few important objects.
There are several DOMs in existence. The following sections explain each of these DOMs in
detail and describe how you can use them to access and modify document content.
• The Legacy DOM : This is the model which was introduced in early versions of JavaScript
language. It is well supported by all browsers, but allows access only to certain key portions
of documents, such as forms, form elements, and images.
• The W3C DOM : This document object model allows access and modification of all
document content and is standardized by the World Wide Web Consortium (W3C). This
model is supported by almost all the modern browsers.
• The IE4 DOM : This document object model was introduced in Version 4 of Microsoft’s
Internet Explorer browser. IE5 and later versions include support for most basic W3C DOM
features.

DOM compatibility
If you want to write a script with the flexibility to use either W3C DOM or IE4 DOM depending on
their availability, then you can use a capability-testing approach that first checks for the existence of
a method or property to determine whether the browser has the capability you desire. For example
if (document.getElementById) {
// If the W3C method exists, use it
}
else if (document.all) {
2.6 JavaScript Date Object 65

Figure 2.1: Javascript DOM

// If the all[] array exists, use it


}
else {
// Otherwise use the legacy DOM
}

JavaScript Date Object


JavaScript date objects are obviously used to track time. You might be thinking, "awesome, I can
make a clock." Please don’t limit yourself to just building a clock. You can use the date for so
much, such as sessions, updates, etc.

The Date object


The Date object is used to work with dates and times.
You create an instance of the Date object with the "new" keyword.
To store the current date in a variable called "my_date":

var my_date=new Date()

After creating an instance of the Date object, you can access all the methods of the object from the
"my_date" variable. If, for example, you want to return the date (from 1-31) of a Date object, you
should write the following:

my_date.getDate()

You can also write a date inside the parentheses of the Date() object, like this:
66 Chapter 2. Java Script

new Date("Month dd, yyyy hh:mm:ss")


new Date("Month dd, yyyy")
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new Date(milliseconds)

Here is how you can create a Date object for each of the ways above:

var my_date=new Date("October 12, 1988 13:14:00")


var my_date=new Date("October 12, 1988")
var my_date=new Date(88,09,12,13,14,00)
var my_date=new Date(88,09,12)
var my_date=new Date(500)

The Most Common Date Methods

Methods Explanation
Date() Returns a Date object
getDate() Returns the date of a Date object (from 1-31)
getDay() Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday,
etc.)
getMonth() Returns the month of a Date object (from 0-11. 0=January,
1=February, etc.)
getFullYear() Returns the year of the Date object (four digits)
getHours() Returns the hour of the Date object (from 0-23)
getMinutes() Returns the minute of the Date object (from 0-59)
getSeconds() Returns the second of the Date object (from 0-59)

Examples of Date Object


Date
Returns today’s date including date, month, and year. Note that the getMonth method returns 0 in
January, 1 in February etc. So add 1 to the getMonth method to display the correct date.

<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write(".")
document.write(d.getMonth() + 1)
document.write(".")
document.write(d.getFullYear())
</script>
</body>
</html>

Time
Returns the current local time including hour, minutes, and seconds. To return the GMT time use
getUTCHours, getUTCMinutes etc.
JavaScript Date Object 67

<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getHours())
document.write(".")
document.write(d.getMinutes() + 1)
document.write(".")
document.write(d.getSeconds())
</script>
</body>
</html>

Set date
You can also set the date or time into the date object, with the setDate, setHour etc. Note that in this
example, only the FullYear is set.

<html>
<body>
<script type="text/javascript">
var d = new Date()
d.setFullYear("1990")
document.write(".")
</script>
</body>
</html>

UTC time
The getUTCDate method returns the Universal Coordinated Time which is the time set by the
World Time Standard.

<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getUTCHours())
document.write(".")
document.write(d.getUTCMinutes() + 1)
document.write(".")
document.write(d.getUTCSeconds())
</script>
</body>
</html>

Display weekday
A simple script that allows you to write the name of the current day instead of the number. Note
that the array object is used to store the names, and that Sunday=0, Monday=1 etc.

<html>
<body>
68 Chapter 2. Java Script

<script type="text/javascript">
var d = new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday
document.write("Today is " + weekday[d.getDay()])
</script>
</body>
</html>

Display full date


How to write a complete date with the name of the day and the name of the month.

<html>
<body>
<script type="text/javascript">
var d = new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","
document.write(weekday[d.getDay()] + " ")
document.write(d.getDate() + ". ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>
</body>
</html>

Display time
How to display the time on your pages. Note that this script is similar to the Time example above,
only this script writes the time in an input field. And it continues writing the time one time per
second.

<html>
<body>
<script type="text/javascript">
var timer = null
function stop()
{
clearTimeout(timer)
}

function start()
{
var time = new Date()
var hours = time.getHours()
minutes=((minutes < 10) ? "0" : "") + minutes
var seconds = time.getSeconds()
seconds=((seconds < 10) ? "0" : "") + seconds
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
JavaScript Regular Expression 69

}
</script>
</body>
</html>

JavaScript Regular Expression


JavaScript RegExp (Regular Expressions) will save your life when you are searching and/or
replacing a set characters in a string. It is fundamental for any form validation. RegExp is actually
an object. Regular Expressions are common in any language to sift through string values. Usually,
RegExp is used to find something inside a string as in some form of validation.

What Is a Regular Expression?


A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you are
searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.

Syntax
/pattern/modifiers;

Example
var patt = /w3schools/i;

Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).

Modifiers
• i - not case sensitive
• g - finds all matches not just first match
• m - multiline matching

RegExp Methods
• exec() - returns first match if found
• test() - returns true if found, false it is isn’t found

Example
var example1 = "Meerkats";
var rEPattern1 = /s/gi; // the "s" is what we are searching for
var rEPattern2 = /z/gi; // the "z" is what we are searching for
document.write(rEPattern1.exec(example1) + "<br/>"); // s is found, returns s
document.write(rEPattern2.test(example1) + "<br/>"); // z is not found, returns false

OUTPUT:
s
false
70 Chapter 2. Java Script

2.7.1 Categories of Pattern Matching Characters


Pattern-matching characters can be grouped into various categories, which will be explained in
detail later. By understanding these characters, you understand the language needed to create a
regular expression pattern. The categories are:

Position matching
You wish to match a substring that occurs at a specific location within the larger string. For example,
a substring that occurs at the very beginning or end of string.

Symbol Description Example


Only matches the beginning of a ^
string. by not "In The Night"
^ Only matches the end of a string. /The/ matches "The" in "The night"
/and$/ matches "and" in "Land" but
$ not "landing"
\b Matches any word boundary (test
/ly\b/ matches "ly" in "This is really
characters must exist at the begin-
cool."
ning or end of a word within the
string)
\B Matches any non-word boundary.
/\Bor/ matches “or” in "normal" but
not "origami."

Special literal character matching


All alphabetic and numeric characters by default match themselves literally in regular expressions.
However, if you wish to match say a newline in Regular Expressions, a special syntax is needed,
specifically, a backslash ( ) followed by a designated character. For example, to match a newline,
the syntax "
n" is used, while "
r" matches a carriage return.

Symbol Description
Alphanumeric All alphabetical and numerical characters match themselves literally. So /2
days/ will match "2 days" inside a string.
\n Matches a new line character
\f Matches a form feed character
\r Matches carriage return character
\t Matches a horizontal tab character
\v Matches a vertical tab character
\xxx Matches the ASCII character expressed by the octal number xxx.
"\50" matches left parentheses character "("
\xdd Matches the ASCII character expressed by the hex number dd.
"\x28" matches left parentheses character "("
\uxxxx Matches the ASCII character expressed by the UNICODE xxxx.

Character classes matching


Individual characters can be combined into character classes to form more complex matches, by
placing them in designated containers such as a square bracket. For example, /[abc]/ matches "a",
"b", or "c", while /[a-zA-Z0-9]/ matches all alphanumeric characters.

Symbol Description Example


2.7 JavaScript Regular Expression 71

[xyz] Match any one character enclosed /[AN]BC/ matches "ABC" and
in the character set. You may use a "NBC" but not "BBC" since the
hyphen to denote range. For exam- leading "B" is not in the set.
ple. /[a-z]/ matches any letter in the
alphabet, /[0-9]/ any single digit.
[xyz] Match any one character not en- /[AN]BC/
^ matches "BBC" but not
^
closed in the character set. The caret "ABC" or "NBC".
indicates that none of the characters
NOTE: the caret used within a char-
acter class is not to be confused with
the caret that denotes the beginning
of a string. Negation is only per-
formed within the square brackets.
Match any character except newline
. (Dot). or another Unicode line terminator. /b.t/ matches "bat", "bit", "bet" and
Match any alphanumeric character so on.
\w including the underscore. Equiva- /\w/ matches "200" in "200%"
lent to [a-zA-Z0-9_].
Match any single non-word charac-
\W ^ /\W/ matches "%" in "200%"
Match any single digit. Equivalent
\d ter. Equivalent to [a-zA-Z0-9_].
to [0-9].
Match any non-digit. Equivalent to
\D /\D/ matches "No" in "No 342222"
^
[0-9].
Match any single space character.
\s
Equivalent to [ \t\r\n\v\f].
Match any single non-space charac-
\S
ter. Equivalent to [ \t\r\n\v\f].
^

Repetition matching
You wish to match character(s) that occurs in certain repetition. For example, to match "555", the
easy way is to use /5{3}/

Symbol Description
x Match exactly x occurrences of a regular expression.
x, Match x or more occurrences of a regular expression.
x,y Matches x to y number of occurrences of a regular expression.
? Match zero or one occurrences. Equivalent to 0,1.
* Match zero or more occurrences. Equivalent to 0,.
+ Match one or more occurrences. Equivalent to 1,.

Alternation and grouping matching


You wish to group characters to be considered as a single entity or add an "OR" logic to your pattern
matching.

Symbol Description
() Grouping characters together to cre-
ate a clause. May be nested.
72 Chapter 2. Java Script

| Alternation combines clauses into


one regular expression and then
matches any of the individual
clauses. Similar to "OR" statement.

Back reference matching


You wish to refer back to a subexpression in the same regular expression to perform matches where
one match is based on the result of an earlier match.

Symbol Description
( )\n Matches a parenthesized clause in the pattern string. n is the number of the
clause to the left of the backreference.

2.7.2 Examples
Valid Number
A valid number value should contain only an optional minus sign, followed by digits, followed by
an optional dot (.) to signal decimals, and if it’s present, additional digits. A regular expression to
do that would look like this:
var anum=/(^-*\d+$)|(^-*\d+\.\d+$)/

Valid Date Format


A valid short date should consist of a 2-digit month, date separator, 2-digit day, date separator, and
a 4-digit year (e.g. 02/02/2000). It would be nice to allow the user to use any valid date separator
character that your backend database supported such as slashes, dashes and periods. You want to be
sure the user enters the same date separator character for all occurrences. The following function
returns true or false depending on whether the user input matches this date format:

function checkdateformat(userinput){
var dateformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
return dateformat.test(userinput) //returns true or false depending on userinput
}

JavaScript - Form Validation


Form validation normally used to occur at the server, after the client had entered all the necessary
data and then pressed the Submit button. If the data entered by a client was incorrect or was simply
missing, the server would have to send all the data back to the client and request that the form be
resubmitted with correct information. This was really a lengthy process which used to put a lot of
burden on the server.
JavaScript provides a way to validate form’s data on the client’s computer before sending it to the
web server. Form validation generally performs two functions.
• Basic Validation: First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check for
data.
• Data Format Validation: Secondly, the data that is entered must be checked for correct
form and value. Your code must include appropriate logic to test correctness of data.

Example
We will take an example to understand the process of validation. Here is a simple form in html
format.
2.8 JavaScript - Form Validation 73

<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>

• Basic Form Validation


First let us see how to do a basic form validation. In the above form, we are calling validate() to
validate data when onsubmit event is occurring. The following code shows the implementation of
this validate() function.
<script type="text/javascript">
74 Chapter 2. Java Script

<!--
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>

• Data Format Validation


Now we will see how we can validate our entered form data before submitting it to the web server.
The following example shows how to validate an entered email address. An email address must
contain at least a ’@’ sign and a dot (.). Also, the ’@’ must not be the first character of the email
address, and the last dot must at least be one character after the ’@’ sign.

Example
Try the following code for email validation.

<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
2.9 DHTML with JavaScript 75

if (atpos < 1 || ( dotpos - atpos < 2 ))


{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>

DHTML with JavaScript


The difference between DHTML and JavaScript:
• DHTML is essentially Dynamic HTML. JavaScript is an interpreted computer programming
language.
• DHTML allows one to incorporate a client-side scripting language, such as JavaScript, a
presentation definition language, such as CSS, and the Document Object Model in HTML
web pages.
• A DHTML page uses JavaScript to dynamically respond to the user’s interactions.
• DHTML is not an individual technology. It is the product of three related technologies:
HTML, Cascading Style Sheets (CSS), and JavaScript.

Exercise
1. What is Java Script? What are the advantages and limitations?
2. Explain in detail about DOM objects.
3. Explain in detail about DAte and time functions.
4. Explain about Javascript validation using examples.
5. Explain about Regular Expression in Javascript with valid example.
6. Differentiate DHTML and JavaScript.
3. Servlets

ervlet technology is used to create web application (resides at server side and generates dynamic
web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Com-
mon Gateway Interface) scripting language was popular as a server-side programming language.
But there was many disadvantages of this technology. We have discussed these disadvantages
below.
There are many interfaces and classes in the servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.
• Servlet is a technology i.e. used to create web application.
• Servlet is an API that provides many interfaces and classes including documentations.
• Servlet is an interface that must be implemented for creating any servlet.
• Servlet is a class that extend the capabilities of the servers and respond to the incoming
request. It can respond to any type of requests.
• Servlet is a web component that is deployed on the server to create dynamic web page.

Figure 3.1: Servlet


78 Chapter 3. Servlets

Common Gateway Interface


The Common Gateway Interface, or CGI, is a set of standards that define how information is
exchanged between the web server and a custom script. The CGI specs are currently maintained by the
NCSA and NCSA defines CGI is as follows:
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface
with information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.

Figure 3.2: CGI

Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
• Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to protect the resources on a
server machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets and RMI mechanisms that you have
seen already.

Servlet Tasks
Servlets perform the following major tasks:
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent
in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
Servlets - Life Cycle 79

• Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.

Servlets - Life Cycle


A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet
• The servlet is initialized by calling the init () method.
• The servlet calls service() method to process a client’s request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.

The init() method :


The init method is designed to be called only once. It is called when the servlet is first created, and
not called again for each user request. So, it is used for one-time initializations, just as with the init
method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but
you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request
resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method
simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write the
formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}

The service () method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is
the signature of these two methods.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
80 Chapter 3. Servlets

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() method


The destroy() method is called only once at the end of the life cycle of a servlet. This method gives
your servlet a chance to close database connections, halt background threads, write cookie lists or
hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy
method definition looks like this:
public void destroy() {
// Finalization code...
}

Architecture
The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.

Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http requests
only.
Let’s see what are the interfaces of javax.servlet package.

Interfaces in javax.servlet package


There are many interfaces in javax.servlet package. They are as follows:
• Servlet
• ServletRequest
• ServletResponse
• RequestDispatcher
• ServletConfig
• ServletContext
Servlet API 81
82 Chapter 3. Servlets

• SingleThreadModel
• Filter
• FilterConfig
• FilterChain
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
• GenericServlet
• ServletInputStream
• ServletOutputStream
• ServletRequestWrapper
• ServletResponseWrapper
• ServletRequestEvent
• ServletContextEvent
• ServletRequestAttributeEvent
• ServletContextAttributeEvent
• ServletException
• UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
• HttpServletRequest
• HttpServletResponse
• HttpSession
• HttpSessionListener
• HttpSessionAttributeListener
• HttpSessionBindingListener
• HttpSessionActivationListener
• HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
• HttpServlet
• Cookie
• HttpServletRequestWrapper
• HttpServletResponseWrapper
• HttpSessionEvent
• HttpSessionBindingEvent
• HttpUtils (deprecated now)

Reading Servlet Parameters


The ServletRequest class includes methods that allow you to read the names and values of parame-
ters that are included in a client request. We will develop a servlet that illustrates their use. The
example contains two files.
A Web page is defined in sum.html and a servlet is defined in Add.java
Reading Servlet Parameters 83

sum.html
<html>
<body>
<center>
<form name="Form1" method="post"
action="Add">
<table>
<tr>
<td><B>Enter First Number</td>
<td><input type=textbox name="Enter First Number" size="25" value=""></td>
</tr>
<tr>
<td><B>Enter Second Number</td>
<td><input type=textbox name="Enter Second Number" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>

The HTML source code for sum.html defines a table that contains two labels and two text fields.
One of the labels is Enter First Number,and the other is Enter Second Number. There is also a
submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the
servlet to process the HTTP POST request.

Add.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Add
extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Get print writer.
response.getContentType("text/html");
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
int sum=0;
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
sum+=Integer.parseInt(pvalue);
84 Chapter 3. Servlets

pw.println(pvalue);
}
pw.println("Sum = "+sum);
pw.close();
}
}

The source code for Add.java contains doPost( ) method is overridden to process client requests.
The getParameterNames( ) method returns an enumeration of the parameter names. These are
processed in a loop.we can see that the parameter name and value are output to the client. The
parameter value is obtained via the getParameter( ) method.

Reading Initialization Parameters


Syntax to provide the initialization parameter for a servlet
The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.
<web-app>
<servlet>
......
<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>

Example of ServletConfig to get initialization parameter


In this example, we are getting the one initialization parameter from the web.xml file and printing
this information in the servlet.

DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
String driver=config.getInitParameter("driver");
out.print("Driver is: "+driver);
out.close();
}
}

web.xml
<web-app>
<servlet>
Reading Initialization Parameters 85

<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>

Example of ServletConfig to get all the initialization parameters


In this example, we are getting all the initialization parameter from the web.xml file and printing
this information in the servlet.

DemoServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
Enumeration<String> e=config.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br>Name: "+str);
out.print(" value: "+config.getInitParameter(str));
}
out.close();
}
}

web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>username</param-name>
86 Chapter 3. Servlets

<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>

HTTP Request

When a browser requests for a web page, it sends lot of information to the web server which can
not be read directly because this information travel as a part of header of HTTP request. You can
check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you would use
very frequently in web programming:
• Accept This header specifies the MIME types that the browser or other clients can handle.
Values of image/png or image/jpeg are the two most common possibilities.
• Accept-Charset This header specifies the character sets the browser can use to display the
information. For example ISO-8859-1.
• Accept-Encoding This header specifies the types of encodings that the browser knows how
to handle. Values of gzip or compress are the two most common possibilities.
• Accept-Language This header specifies the client’s preferred languages in case the servlet
can produce results in more than one language. For example en, en-us, ru, etc.
• Authorization This header is used by clients to identify themselves when accessing pass-
wordprotected Web pages. Connection This header indicates whether the client can handle
persistent HTTP connections. Persistent connections permit the client or other browser to
retrieve multiple files with a single request. A value of Keep-Alive means that persistent
connections should be used
• Content-Length This header is applicable only to POST requests and gives the size of the
POST data in bytes.
• Cookie This header returns cookies to servers that previously sent them to the browser.
• Host This header specifies the host and port as given in the original URL.
• If-Modified-Since This header indicates that the client wants the page only if it has been
changed after the specified date. The server sends a code, 304 which means Not Modified
header if no newer result is available.
• If-Unmodified-Since This header is the reverse of If-Modified-Since; it specifies that the
operation should succeed only if the document is older than the specified date.
• Referer This header indicates the URL of the referring Web page. For example, if you are at
Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the
Referer header when the browser requests Web page 2.
• User-Agent This header identifies the browser or other client making the request and can be
used to return different content to different types of browsers.
3.8 HTTP Request 87

Methods to read HTTP Header


There are following methods which can be used to read HTTP header in your servlet program.
These methods are available with HttpServletRequest object.
• Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent
with this request.
• Enumeration getAttributeNames() Returns an Enumeration containing the names of the
attributes available to this request.
• Enumeration getHeaderNames() Returns an enumeration of all the header names this
request contains.
• Enumeration getParameterNames() Returns an Enumeration of String objects containing
the names of the parameters contained in this request.
• HttpSession getSession() Returns the current session associated with this request, or if the
request does not have a session, creates one.
• HttpSession getSession(boolean create) Returns the current HttpSession associated with this
request or, if if there is no current session and create is true, returns a new session.
• Locale getLocale() Returns the preferred Locale that the client will accept content in, based
on the Accept-Language header.
• Object getAttribute(String name) Returns the value of the named attribute as an Object,
or null if no attribute of the given name exists.
• ServletInputStream getInputStream() Retrieves the body of the request as binary data
using a ServletInputStream.
• String getAuthType() Returns the name of the authentication scheme used to protect the
servlet, for example, "BASIC" or "SSL," or null if the JSP was not protected.
• String getCharacterEncoding() Returns the name of the character encoding used in the
body of this request.
• String getContentType() Returns the MIME type of the body of the request, or null if the
type is not known.
• String getContextPath() Returns the portion of the request URI that indicates the context
of the request.
• String getHeader(String name) Returns the value of the specified request header as a String.
• String getMethod() Returns the name of the HTTP method with which this request was
made, for example, GET, POST, or PUT.
• String getParameter(String name) Returns the value of a request parameter as a String, or
null if the parameter does not exist.
• String getPathInfo() Returns any extra path information associated with the URL the client
sent when it made this request.
• String getProtocol() Returns the name and version of the protocol the request.
• String getQueryString() Returns the query string that is contained in the request URL after
the path.
• String getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent
the request.
• String getRemoteHost() Returns the fully qualified name of the client that sent the request.
• String getRemoteUser() Returns the login of the user making this request, if the user has
been authenticated, or null if the user has not been authenticated.
• String getRequestURI() Returns the part of this request’s URL from the protocol name up
to the query string in the first line of the HTTP request.
• String getRequestedSessionId() Returns the session ID specified by the client.
• String getServletPath() Returns the part of this request’s URL that calls the JSP.
• String[] getParameterValues(String name) Returns an array of String objects containing
88 Chapter 3. Servlets

all of the values the given request parameter has, or null if the parameter does not exist.
• boolean isSecure() Returns a boolean indicating whether this request was made using a
secure channel, such as HTTPS.
• int getContentLength() Returns the length, in bytes, of the request body and made available
by the input stream, or -1 if the length is not known.
• int getIntHeader(String name) Returns the value of the specified request header as an int.
• int getServerPort() Returns the port number on which this request was received.

HTTP Header Request Example


Following is the example which uses getHeaderNames() method of HttpServletRequest to read
the HTTP header infromation. This method returns an Enumeration that contains the header
information associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using
hasMoreElements() method to determine when to stop and using nextElement() method to get each
parameter name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class DisplayHeader extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "HTTP Header Request Example";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<table width=\"100%\" border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
3.9 HTTP Response 89

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

HTTP Response
A Web server responds to a HTTP request to the browser, the response typically consists of a status
line, some response headers, a blank line, and the document. A typical response looks like this:

HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>

The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200
in the example), and a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the
browser from web server side and you would use them very frequently in web programming:
• Allow This header specifies the request methods (GET, POST, etc.) that the server supports.
• Cache-Control This header specifies the circumstances in which the response document can
safely be cached. It can have values public, private or no-cache etc. Public means document
is cacheable, Private means document is for a single user and can only be stored in private
(nonshared) caches and no-cache means document should never be cached.
• Connection This header instructs the browser whether to use persistent in HTTP connections
or not. A value of close instructs the browser not to use persistent HTTP connections and
keep-alive means using persistent connections.
• Content-Disposition This header lets you request that the browser ask the user to save the
response to disk in a file of the given name.
• Content-Encoding This header specifies the way in which the page was encoded during
transmission.
• Content-Language This header signifies the language in which the document is written. For
example en, en-us, ru, etc.
• Content-Length This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.
• Content-Type This header gives the MIME (Multipurpose Internet Mail Extension) type of
the response document.
• Expires This header specifies the time at which the content should be considered out-of-date
and thus no longer be cached.
90 Chapter 3. Servlets

• Last-Modified This header indicates when the document was last changed. The client can
then cache the document and supply a date by an
• If-Modified-Since request header in later requests.
• Location This header should be included with all responses that have a status code in the 300s.
This notifies the browser of the document address. The browser automatically reconnects to
this location and retrieves the new document.
• Refresh This header specifies how soon the browser should ask for an updated page. You can
specify time in number of seconds after which a page would be refreshed.
• Retry-After This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.
• Set-Cookie This header specifies a cookie associated with the page.

Methods to Set HTTP Response Header


There are following methods which can be used to set HTTP response header in your servlet
program. These methods are available with HttpServletResponse object.
• String encodeRedirectURL(String url) Encodes the specified URL for use in the sendRedi-
rect method or, if encoding is not needed, returns the URL unchanged.
• String encodeURL(String url) Encodes the specified URL by including the session ID in
it, or, if encoding is not needed, returns the URL unchanged.
• boolean containsHeader(String name) Returns a boolean indicating whether the named
response header has already been set.
• boolean isCommitted() Returns a boolean indicating if the response has been committed.
• void addCookie(Cookie cookie) Adds the specified cookie to the response.
• void addDateHeader(String name, long date) Adds a response header with the given name and
date-value.
• void addHeader(String name, String value) Adds a response header with the given name
and value.
• void addIntHeader(String name, int value) Adds a response header with the given name
and integer value.
• void flushBuffer() Forces any content in the buffer to be written to the client.
• void reset() Clears any data that exists in the buffer as well as the status code and headers.
• void resetBuffer() Clears the content of the underlying buffer in the response without
clearing headers or status code.
• void sendError(int sc) Sends an error response to the client using the specified status code
and clearing the buffer.
• void sendError(int sc, String msg) Sends an error response to the client using the specified
status.
• void sendRedirect(String location) Sends a temporary redirect response to the client using
the specified redirect location URL.
• void setBufferSize(int size) Sets the preferred buffer size for the body of the response.
• void setCharacterEncoding(String charset) Sets the character encoding (MIME charset)
of the response being sent to the client, for example, to UTF-8.
• void setContentLength(int len) Sets the length of the content body in the response In HTTP
servlets, this method sets the HTTP Content-Length header.
• void setContentType(String type) Sets the content type of the response being sent to the
client, if the response has not been committed yet.
• void setDateHeader(String name, long date) Sets a response header with the given name
and date-value.
• void setHeader(String name, String value) Sets a response header with the given name
HTTP Response 91

and value.
• void setIntHeader(String name, int value) Sets a response header with the given name and
integer value.
• void setLocale(Locale loc) Sets the locale of the response, if the response has not been
committed yet.
• void setStatus(int sc) Sets the status code for this response
Example
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class Refresh extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
// Set response content type
response.setContentType("text/html");
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
PrintWriter out = response.getWriter();
String title = "Auto Refresh Header Setting";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
92 Chapter 3. Servlets

Servlets - Cookies Handling


Cookies are text files stored on the client computer and they are kept for various information tracking
purpose. Java Servlets transparently supports HTTP cookies. There are three steps involved in
identifying returning users:
• Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it sends those cookies informa-
tion to the server and server uses that information to identify the user.

The Anatomy of a Cookie


Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a
browser). A servlet that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded. The expires field is an instruction to the browser to
"forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date.
If the user points the browser at any page that matches the path and domain of the cookie, it will
resend the cookie to the server. The browser’s headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

A servlet will then have access to the cookie through the request method request.getCookies()
which returns an array of Cookie objects.

Servlet Cookies Methods


Following is the list of useful methods which you can use while manipulating cookies in servlet.
• public void setDomain(String pattern) This method sets the domain to which cookie
applies, for example tutorialspoint.com.
• public String getDomain() This method gets the domain to which cookie applies, for
example tutorialspoint.com.
• public void setMaxAge(int expiry) This method sets how much time (in seconds) should
elapse before the cookie expires. If you don’t set this, the cookie will last only for the current
session.
3.10 Servlets - Cookies Handling 93

• public int getMaxAge() This method returns the maximum age of the cookie, specified in
seconds, By default, -1 indicating the cookie will persist until browser shutdown.
• public String getName() This method returns the name of the cookie. The name cannot be
changed after creation.
• public void setValue(String newValue) This method sets the value associated with the
cookie.
• public String getValue() This method gets the value associated with the cookie.
• public void setPath(String uri) This method sets the path to which this cookie applies. If
you don’t specify a path, the cookie is returned for all URLs in the same directory as the
current page as well as all subdirectories.
• public String getPath() This method gets the path to which this cookie applies.
• public void setSecure(boolean flag) This method sets the boolean value indicating whether
the cookie should only be sent over encrypted (i.e. SSL) connections.
• public void setComment(String purpose) This method specifies a comment that describes
a cookie’s purpose. The comment is useful if the browser presents the cookie to the user.
• public String getComment() This method returns the comment describing the purpose of
this cookie, or null if the cookie has no comment.

Setting Cookies with Servlet


Setting cookies with servlet involves three steps:
1. Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie
value, both of which are strings.
Cookie cookie = new Cookie("key","value");

Keep in mind, neither the name nor the value should contain white space or any of the
following characters:
[ ] ( ) = , " / ? @ : ;

2. Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie
should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);

3. Sending the Cookie into the HTTP response headers: You use response.addCookie to
add cookies in the HTTP response header as follows:
response.addCookie(cookie);

Example
Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
94 Chapter 3. Servlets

// Create cookies for first and last names.


Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Setting Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");
}
}

Compile above servlet HelloForm and create appropriate entry in web.xml file and finally try
following HTML page to call servlet.

<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Keep above HTML content in a file Hello.htm and put it in < Tomcat - installation - directory
>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the
actual output of the above form.
3.11 Servlets - Session Tracking 95

Servlets - Session Tracking


Servlet provides HttpSession Interface which provides a way to identify a user across more than one
page request or visit to a Web site and to store information about that user. The servlet container
uses this interface to create a session between an HTTP client and an HTTP server. The session
persists for a specified time period, across more than one connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of HttpServletRequest,
as below:
HttpSession session = request.getSession();

You need to call request.getSession() before you send any document content to the client. Here is a
summary of the important methods available through HttpSession object:
• public Object getAttribute(String name) This method returns the object bound with the
specified name in this session, or null if no object is bound under the name.
• public Enumeration getAttributeNames() This method returns an Enumeration of String
objects containing the names of all the objects bound to this session.
• public long getCreationTime() This method returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
• public String getId() This method returns a string containing the unique identifier assigned
to this session.
• public long getLastAccessedTime() This method returns the last time the client sent a
request associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
• public int getMaxInactiveInterval() This method returns the maximum time interval, in
seconds, that the servlet container will keep this session open between client accesses. public
• void invalidate() This method invalidates this session and unbinds any objects bound to it.
• public boolean isNew() This method returns true if the client does not yet know about the
session or if the client chooses not to join the session.
• public void removeAttribute(String name) This method removes the object bound with
the specified name from this session.
• public void setAttribute(String name, Object value) This method binds an object to this
session, using the name specified.
• public void setMaxInactiveInterval(int interval) This method specifies the time, in sec-
onds, between client requests before the servlet container will invalidate this session.

Example
This example describes how to use the HttpSession object to find out the creation time and the last-
accessed time for a session. We would associate a new session with the request if one does not
already exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
96 Chapter 3. Servlets

{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime =
new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your web page.
if (session.isNew()){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
Accessing a Database using Servlet 97

"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}

Accessing a Database using Servlet


Here is an example which shows how to access TEST database using Servlet.

// Loading required libraries


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// JDBC driver name and database URL
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
// Database credentials
static final String USER = "root";
static final String PASS = "password";
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
98 Chapter 3. Servlets

// Execute SQL query


Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
}
}

Exercise
1. Explain Java Servlet Architecture.
2. Explain in detail about servlet life cycle.
3.13 Exercise 99

3. Explain about Request and Response in Servlet.


4. Explain session handling in Servlets with example.
5. Explain Cookie management in servlets with example.
4. Java Server Page-JSP

JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content.
This helps developers insert java code in HTML pages by making use of special JSP tags, most of
which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application. Web developers write JSPs as text files that combine HTML
or XHTML code, XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages, and
sharing information between requests, pages etc.
JavaServer Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.
• Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having separate CGI files.
• JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is requested.
• JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
• JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications.
This means that JSP can play a part in the simplest applications to the most complex and demanding.

JSP - Architecture
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has
built-in JSP container to support JSP pages development.
102 Chapter 4. Java Server Page-JSP

A JSP container works with the Web server to provide the runtime environment and other services
a JSP needs. It knows how to understand the special elements that are part of JSPs. Following
diagram shows the position of JSP container and JSP files in a Web application.

Figure 4.1: Architecture of JSP

JSP Processing
The following steps explain how the web server creates the Webpage using JSP -
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html. The
• JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code. This code implements the corresponding
dynamic behavior of the page.
• The JSP engine compiles the servlet into an executable class and forwards the original request
to a servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format. The output is furthur
passed on to the web server by the servlet engine inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static HTML
content.
• Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram Typically, the JSP engine
checks to see whether a servlet for a JSP file already exists and whether the modification date on
the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container
assumes that the JSP hasn’t changed and that the generated servlet still matches the JSP’s contents.
This makes the process more efficient than with the other scripting languages (such as PHP) and
therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java
JSP Declarations 103

programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular
servlet.

JSP Declarations
A declaration declares one or more variables or methods that you can use in Java code later in the
JSP file. You must declare the variable or method before you use it in the JSP file. Following is the
syntax for JSP Declarations -

<%! declaration; [ declaration; ]+ ... %>

You can write the XML equivalent of the above syntax as follows -

<jsp:declaration>
code fragment
</jsp:declaration>

Following is an example for JSP Declarations -

<%! int i = 0; %>


<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

JSP Expression
A JSP expression element contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line
of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java Language
Specification but you cannot use a semicolon to end an expression.
Following is the syntax of JSP Expression -

<%= expression %>

You can write the XML equivalent of the above syntax as follows -

<jsp:expression>
expression
</jsp:expression>

Following example shows a JSP Expression -

<html>
<head><title>A Comment Test</title></head>
<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body>
</html>

The above code will generate the following result - Today’s date: 11-Sep-2010 21:24:25
104 Chapter 4. Java Server Page-JSP

JSP Comments
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is
useful when you want to hide or "comment out", a part of your JSP page. Following is the syntax
of the JSP comments -
<%-- This is JSP comment --%>
Following example shows the JSP Comments -
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>

A Test of Comments
There are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here’s a summary -

Syntax & Purpose


1. <%-- comment --%>
A JSP comment. Ignored by the JSP engine.
2. <!-- comment -->
An HTML comment. Ignored by the browser.
3. <%
Represents static <% literal.
4. %>
Represents static %> literal.
5. \'
A single quote in an attribute that uses single quotes.
6. \"
A double quote in an attribute that uses double quotes.

JSP - Directives
In this chapter, we will discuss Directives in JSP. These directives provide directions and instructions
to the container, telling it how to handle certain aspects of the JSP processing. A JSP directive
affects the overall structure of the servlet class. It usually has the following form -
<%@ directive attribute = "value" %>
Directives can have a number of attributes which you can list down as key-value pairs and separated
by commas.
There are three types of directive tag -
1. <%@ page ... %>
Defines page-dependent attributes, such as scripting language, error page, and buffering
requirements.
2. <%@ include ... %>
Includes a file during the translation phase.
3. <%@ taglib ... %>
Declares a tag library, containing custom actions, used in the page
4.6 JSP - Directives 105

JSP - The page Directive


The page directive is used to provide instructions to the container. These instructions pertain to the
current JSP page. You may code page directives anywhere in your JSP page. By convention, page
directives are coded at the top of the JSP page.
Following is the basic syntax of the page directive -
<%@ page attribute = "value" %>

You can write the XML equivalent of the above syntax as follows -

<jsp:directive.page attribute = "value" />

Attributes
Following table lists out the attributes associated with the page directive
1. buffer: Specifies a buffering model for the output stream.
2. autoFlush Controls the behavior of the servlet output buffer.
3. contentType Defines the character encoding scheme.
4. errorPage Defines the URL of another JSP that reports on Java unchecked runtime excep-
tions.
5. isErrorPage Indicates if this JSP page is a URL specified by another JSP page’s errorPage
attribute.
6. extends Specifies a superclass that the generated servlet must extend.
7. import Specifies a list of packages or classes for use in the JSP as the Java import statement
does for Java classes.
8. info Defines a string that can be accessed with the servlet’s getServletInfo() method.
9. isThreadSafe Defines the threading model for the generated servlet.
10. language Defines the programming language used in the JSP page.
11. session Specifies whether or not the JSP page participates in HTTP sessions
12. isELIgnored Specifies whether or not the EL expression within the JSP page will be ignored.
13. isScriptingEnabled Determines if the scripting elements are allowed for use.

The include Directive


The include directive is used to include a file during the translation phase. This directive tells the
container to merge the content of other external files with the current JSP during the translation
phase. You may code the include directives anywhere in your JSP page.
The general usage form of this directive is as follows -
<%@ include file = "relative url" >

The filename in the include directive is actually a relative URL. If you just specify a filename with no
associated path, the JSP compiler assumes that the file is in the same directory as your JSP. You
can write the XML equivalent of the above syntax as follows -
<jsp:directive.include file = "relative url" />

The taglib Directive


The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags
and a tag library is a set of user-defined tags that implement custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the
library, and provides means for identifying the custom tags in your JSP page.
The taglib directive follows the syntax given below -

<%@ taglib uri="uri" prefix = "prefixOfTag" >


106 Chapter 4. Java Server Page-JSP

Here, the uri attribute value resolves to a location the container understands and the prefix attribute
informs a container what bits of markup are custom actions.
You can write the XML equivalent of the above syntax as follows -

<jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />

Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used in the
JSP. The full syntax for the useBean tag is as follows -
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>

Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name among
other useBean declarations in the same JSP. Following example shows how to use the useBean
action -

<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>

You will receive the following result–

The date/time is Thu Sep 30 11:18:11 GST 2010

Accessing JavaBeans Properties


Along with < jsp : useBean :::> action, you can use the < jsp : getProperty =>action to access
the get methods and the < jsp : setProperty => action to access the set methods. Here is the full
syntax -
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that shoul
invoked.
Following example shows how to access the data using the above syntax -
<html>
<head>
<title>get and set properties Example</title>
</head>
4.8 JSP - Cookies Handling 107

<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student First Name:
<jsp:getProperty name = "students" property = "firstName"/>
</p>
<p>Student Last Name:
<jsp:getProperty name = "students" property = "lastName"/>
</p>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
</body>
</html>

Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the following
result will be displayed -
Student First Name: Zara
Student Last Name: Ali
Student Age: 10

JSP - Cookies Handling


Cookies are text files stored on the client computer and they are kept for various information tracking
purposes. JSP transparently supports HTTP cookies using underlying servlet technology.There are
three steps involved in identifying and returning users -
• Server script sends a set of cookies to the browser. For example, name, age, or identification
number, etc.
• Browser stores this information on the local machine for future use.
• When the next time the browser sends any request to the web server then it sends those
cookies information to the server and server uses that information to identify the user or may
be for some other purpose as well.

The Anatomy of a Cookie


Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a
browser). A JSP that sets a cookie might send headers that look something like this -
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded. The expires field is an instruction to the browser to
108 Chapter 4. Java Server Page-JSP

"forget" the cookie after the given time and date. If the browser is configured to store cookies, it
will then keep this information until the expiry date. If the user points the browser at any page that
matches the path and domain of the cookie, it will resend the cookie to the server. The browser’s
headers might look something like this -

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = xyz

A JSP script will then have access to the cookies through the request method request.getCookies()
which returns an array of Cookie objects. subsectionSetting Cookies with JSP Setting cookies with
JSP involves three steps

Step 1: Creating a Cookie object


You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Keep in mind, neither the name nor the value should contain white space or any of the following
characters -

[ ] ( ) = , " / ? @ : ;

Step 2: Setting the maximum age


You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following
code will set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

Step 3: Sending the Cookie into the HTTP response headers


You use response.addCookie to add cookies in the HTTP response header as follows

response.addCookie(cookie);

Example:
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
%>
<html>
4.8 JSP - Cookies Handling 109

<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Let us put the above code in main.jsp file and use it in the following HTML page -
<html>
<body>
<form action = "main.jsp" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

Reading Cookies with JSP


To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the
getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and
getValue() methods to access each cookie and associated value.

Example
Let us now read cookies that were set in the previous example :

<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with the this domain
cookies = request.getCookies();
110 Chapter 4. Java Server Page-JSP

if( cookies != null ) {


out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html>

Delete Cookies with JSP


To delete cookies is very simple. If you want to delete a cookie, then you simply need to follow
these three steps:
• Read an already existing cookie and store it in Cookie object.
• Set cookie age as zero using the setMaxAge() method to delete an existing cookie.
• Add this cookie back into the response header.
Example
Following example will show you how to delete an existing cookie named "first_name" and when
you run main.jsp JSP next time, it will return null value for first_name.

<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with the this domain
cookies = request.getCookies();
if( cookies != null ) {
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
4.9 JSP - Session 111

}
} else {
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>
</html>

JSP - Session
HTTP is a "stateless" protocol which means each time a client retrieves a Webpage, the client opens
a separate connection to the Web server and the server automatically does not keep any record of
previous client request.

Maintaining Session Between Web Client And Server


Let us now discuss a few options to maintain the session between the Web Client and the Web
Server:

Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not
recommended to use this procedure to maintain the sessions.

Hidden Form Fields


A web server can send a hidden HTML form field along with a unique session ID as follows :

<input type = "hidden" name = "sessionid" value = "12345">

This entry means that, when the form is submitted, the specified name and value are automatically
included in the GET or the POST data. Each time the web browser sends the request back, the
session_id value can be used to keep the track of different web browsers.
This can be an effective way of keeping track of the session but clicking on a regular (< AHREF... >)
hypertext link does not result in a form submission, so hidden form fields also cannot support
general session tracking.

URL Rewriting
You can append some extra data at the end of each URL. This data identifies the session; the server
can associate that session identifier with the data it has stored about that session. For example,
with http://skillsubsist.in/file.htm;sessionid=12345, the session identifier is attached as sessionid =
12345 which can be accessed at the web server to identify the client. URL rewriting is a better way to
maintain sessions and works for the browsers when they don’t support cookies. The drawback here
is that you will have to generate every URL dynamically to assign a session ID though page is a
simple static HTML page.

The session Object


Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession
Interface. This interface provides a way to identify a user across.
• a one page request or
• visit to a website or
112 Chapter 4. Java Server Page-JSP

• store information about that user


By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for
each new client automatically. Disabling session tracking requires explicitly turning it off by setting
the page directive session attribute to false as follows-

<%@ page session = "false" %>

The JSP engine exposes the HttpSession object to the JSP author through the implicit session object.
Since session object is already provided to the JSP programmer, the programmer can immediately
begin storing and retrieving data from the object without any initialization or getSession().
Here is a summary of important methods available through the session object
1. public Object getAttribute(String name): This method returns the object bound with the
specified name in this session, or null if no object is bound under the name.
2. public Enumeration getAttributeNames(): This method returns an Enumeration of String
objects containing the names of all the objects bound to this session.
3. public long getCreationTime(): This method returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
4. public String getId(): This method returns a string containing the unique identifier assigned
to this session.
5. public long getLastAccessedTime(): This method returns the last time the client sent a
request associated with the this session, as the number of milliseconds since midnight January 1,
1970 GMT.
6. public int getMaxInactiveInterval(): This method returns the maximum time interval, in
seconds, that the servlet container will keep this session open between client accesses.
7. public void invalidate(): This method invalidates this session and unbinds any objects
bound to it.
8. public boolean isNew(): This method returns true if the client does not yet know about the
session or if the client chooses not to join the session.
9. public void removeAttribute(String name): This method removes the object bound with
the specified name from this session.
10. public void setAttribute(String name, Object value): This method binds an object to this
session, using the name specified.
11. public void setMaxInactiveInterval(int interval): This method specifies the time, in sec-
onds, between client requests before the servlet container will invalidate this session.

Session Tracking Example


This example describes how to use the HttpSession object to find out the creation time and the last-
accessed time for a session. We would associate a new session with the request if one does not
already exist.

<%@ page import = "java.io.*,java.util.*" %>


<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this Webpage.
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
4.9 JSP - Session 113

String userID = new String("ABCD");


// Check if this is new comer on your Webpage.
if (session.isNew() ){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>
114 Chapter 4. Java Server Page-JSP

Deleting Session Data


When you are done with a user’s session data, you have several options
• Remove a particular attribute : You can call the public void removeAttribute(String name)
method to delete the value associated with the a particular key.
• Delete the whole session : You can call the public void invalidate() method to discard an
entire session.
• Setting Session timeout : You can call the public void setMaxInactiveInterval(int interval)
method to set the timeout for a session individually.
• Log the user out ": The servers that support servlets 2.4, you can call logout to log the client
out of the Web server and invalidate all sessions belonging to all the users.
• web.xml Configuration : If you are using Tomcat, apart from the above mentioned methods,
you can configure the session time out in web.xml file as follows.

<session-config>
<session-timeout>15</session-timeout>
</session-config>

The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tom-
cat. The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session
in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval()
returns 900.

JSP Database Connection


The database is used for storing various types of data which are huge and has storing capacity in
gigabytes. JSP can connect with such databases to create and manage the records.

Create Table
In MYSQL database, we can create a table in the database with any MYSQL client. Here we are
using PHPMyadminclient, and there we have an option "new" to create a new table using below
screenshot. In this, we have to provide table name as guru_test, and we will create two fields’

emp_id and emp_name.


Emp_id is havingdatatype as int
Emp_name is havingdatatype as varchar

Another option is by using command prompt and changes to MYSQL directory:

C:\>
C:\>cd Program Files\MY SQL\bin
C:\>Program Files\MySql\bin>
4.10 JSP Database Connection 115

We can login to database as follows:


C:\Program Files\MYSQL\bin>mysql -u gururoot -p
Enter Password: *******
Mysql>
Create table guru_testin the database named as GuruTestas the following on MYSQL prompt:
Mysql> use GuruTest;
MySql> create table guru_test(
Emp_idint NOT NULL,
Emp_namevarchar(11),
);
Once you execute this you get the following:
Query OK, 0 rows affected(0.10 sec)
MySQl> select * from guru_test;
Query OK, 0 rows affected(0.10 sec)
First the records are inserted using INSERT query and then we can use SELECTquery to check
whether the table is created or not.

Create Records
After creating a table we need to create records into the guru_test table using insert query, which is
shown below:
The records entered here are:
• 1 and guru emp1
• 2 and guru emp2
MySql>INSERT INTO `couch_tomato_db`.`guru_test` (`emp_id`, `emp_name`) VALUES ('1', 'guru
Query OK, 1 row affected (0.05 sec)
MySQL>INSERT INTO `couch_tomato_db`.`guru_test` (`emp_id`, `emp_name`) VALUES ('2', 'guru
Query OK, 1 row affected (0.05 sec)

Using JSP, we can do multiple operations into the database. We can insert the records, and also,
we can delete the records which are not required. If any record needs to be edited, then we can do
using an update. The Selectoperation will help to fetch the records which are required.
116 Chapter 4. Java Server Page-JSP

Select
The Select operation is used to select the records from the table.

Example
In this example, we are going to learn about the select operation of fetching records from guru_test
table which was created in the above section.

<%@ page import="java.io.*,java.util.*,java.sql.*"%>


<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Database JSP1</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>
<sql:query dataSource="${snapshot}" var="result">
SELECT * from guru_test;
</sql:query>
<table>
<tr>
<th>Guru ID</th>
<th>Name</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.emp_id}"/></td>
<td><c:out value="${row.emp_name}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>

Explanation of the code:


Code Line 1: Here we are importing io, uti and SQL libraries of java.
Code Line 3: Here we are importing core library of JSTL and giving its prefix as gurucore which
will help to get output.
Code Line 4: Here we are importing SQL library of jstl and giving its prefix as gurusql which will
help to do the SQL operations.
Code Line 15-17: Here using gurusql, we are connecting data source by naming variable as "guru"
and driver as a JDBC driver. Also adding username and password with "gururoot" and "guru".
Code Line 19-21: Here we are using sql query of the select query.
4.10 JSP Database Connection 117

Code Line 31-32: We are printing the output for emp id and emp name, which are fetched from the
results of the query and using foreach loop we print the output.
When you execute the above code, we will get the output as below;
Output: Here both the records will be fetched from the database

1 guru emp1
2 guru emp2

Insert
Insert operator is used to insert the records into the database.

Example:
In this example, we are going to learn about inserting the records in the table guru_test

<%@ page import="java.io.*,java.util.*,java.sql.*"%>


<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/htm
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Database JSP1</title>
</head>
<body>
<gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>
<gurusql:update dataSource="${guru}" var="guruvar">
INSERT INTO guru_test VALUES (3, 'emp emp3');
</gurusql:update>
</body>
</html>

Explanation of the code:


Code Line 19-20: Here we are inserting records into the table guru_test of GuruTestdatabase.The
records inserted are: empID - 3 and empname - emp emp3.These records will be inserted in the
table
When you execute the code, the records are inserted into the table as guru_test ,with value 3 and
emp emp3.
Note: Here we are not showing the output as we are just inserting the record in the table. We can
get the record using select query as ’select * from guru_test’. If the record was inserted then, we
would get the value as 3 and emp3.If the record is not inserted then, 3 will not be seen in records in
the table.

Delete
This is delete operation where we delete the records from the table guru_test.
118 Chapter 4. Java Server Page-JSP

Example:
Here we will delete query to delete the record from the table guru_test. The record which has to be
deleted has to be set in variable "guruid", and the corresponding record is deleted from the database.
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Database JSP1</title>
</head>
<body>
<gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>
<gurucore:set var="guruid" value="3"/>
<gurusql:update dataSource="${guru}" var="guruvar">
DELETE FROM guru_test WHERE emp_id = ?
<gurusql:param value="${guruid}" />
</gurusql:update>
</body>
</html>

Explanation of the code:


Code Line 18: We are setting a variable guruid whose value is 3, which has to be deleted from the
database. This is always a primary key of the table. In this case, the primary key is the emp_id.
Code Line 19-22: Here we are using a delete query which is setting a parameter in the where
clause.Here parameter is guruid which is set in code line 18. The corresponding record is deleted.

Output:
When you execute the above code, the record with emp_id as 3 is deleted. Note: In this example,
we cannot show the output as we are deleting the record from the table.To check whether that record is
deleted, we need to use select query "select * from guru_test". In that case, if we get 3 as emp id then
delete query has failed else the record has been deleted successfully.

Update
The update is used to edit the records in the table.

Example:
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html
4.11 compare JSP and servlet 119

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Database JSP1</title>
</head>
<body>
<gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/GuruTest"
162 Chapter 5. Java Server Page
user="gururoot" password="guru"/>
<gurucore:set var="guruid" value="2"/>
<gurusql:update dataSource="${guru}" var="guruvar">
UPDATE guru_test SET emp_name='emp guru99'
<gurusql:param value="${guruid}" />
</gurusql:update>
</body>
</html>

Explanation of the code:


Code Line 18: Here we are setting a variable guruid as 2. This is the ID where we want to update the
record.
Code Line 19-22: Here we are using an update query to update the record in the table guru_test of
the record, which is set in point 18.Here emp guru2 is replaced by emp guru99

Output:
When you execute the above code the record with emp_id 2 is changed to 99. So, now the output
will show emp"guru99" instead of emp "guru2"

compare JSP and servlet


Following are the comparisons of JSP and servlets.

Servlet JSP
1 Servlet is faster than jsp JSP is slower than Servlet because it
first translate into java code then com-
pile.
2 In Servlet, if we modify the code In JSP, if we do any modifications then
then we need recompilation, reloading, just we need to click on refresh button
restarting the server> It means it is time and recompilation, reloading, restart the
consuming process. server is not required.
3 Servlet is a java code. JSP is tag based approach.
4 In Servlet, there is no such method for In JSP, we can use the client side vali-
running JavaScript at client side. dations using running the JavaScript at
client side.
5 To run a Servlet you have to make an For running a JSP there is no need to
entry of Servlet mapping into the de- make an entry of Servlet mapping into
ployment descriptor file i.e. web.xml the web.xml file externally, you may or
file externally. not make an entry for JSP file as wel-
come file list.
6 Coding of Servlet is harden than jsp. Coding of jsp is easier than Servlet be-
cause it is tag based.
120 Chapter 4. Java Server Page-JSP

7 In MVC pattern, Servlet plays a con- In MVC pattern, JSP is used for show-
troller role. ing output data i.e. in MVC it is a view.
8 Servlet accept all protocol request. JSP will accept only http protocol re-
quest.
9 In Servlet, aervice() method need to In JSP no need to override service()
override. method.
10 In Servlet, by default session manage- In JSP, session management is automat-
ment is not enabled we need to enable ically enabled.
explicitly.
11 In Servlet we do not have implicit ob- In JSP, we have implicit object support.
ject. It means if we want to use an ob-
ject then we need to get object explicitly
form the servlet.
12 In Servlet, we need to implement busi- In JSP, we can separate the business
ness logic, presentation logic combined. logic from the presentation logic by
uses javaBean technology.
13 In Servlet, all package must be imported In JSP, package imported anywhere top,
on top of the servlet. middle and bottom.

Exercise
1. Explain the Advantages and drawbacks of JSP.
2. Explain the JDBC with examples.
3. Explain JSP-sessions.
4. Explain JSP Cookie concepts.
5. Write a HTML forms by embedding JSP code.
6. Differentiate JSP and Servlets.
5. Introduction to PHP

Introduction to PHP: The problem with other Technologies (Servelets and JSP), Downloading,
installing, configuring PHP, Programming in a Web environment and The anatomy of a PHP Page.
Variables and data types, Operators, Expressions and Statements, Strings, Arrays and Functions.
PHP Advanced Concepts: Using Cookies, Using HTTP Headers, Using Sessions, Authenticating
users, Using Environment and Configuration variables, Working with Date and Time.

*********************

Server Side Programming


It is a technique used in Web design which involves embedded scripts in an HTML source code
which results in a Client’s request to the Server website being handled by a script/program running
Server-Side before the Server responds to the client request.

Advantages of Server Side Programs:


• All programs reside in one machine called the Server. Any number of Clients can access the
server programs.
• New functionalities to existing programs can be added at the server side.
• Migrating to new versions, architectures, design patterns, switching to new databases can be
done at the Server side without having to bother about Clients.
• Issues relating to enter price applications like resource management, concurrency, session
management, security and performance are managed by Server side applications.
• They are portable and possess the capability to generate dynamic and user-based content.

Some of the Server side programming Languages


ASP (Active Server Pages): This venerable Microsoft technology has been around since 1997,
and was one of the first Web application technologies to integrate closely with the Web server,
resulting in fast performance. ASP scripts are usually written in VBScript, a language derived
from BASIC. This contrasts with PHP’s more C - like syntax. Although both languages have
122 Chapter 5. Introduction to PHP

their fans, I personally find that it’s easier to write structured, modular code in PHP than in
VBScript.
ASP.NET: This is the latest incarnation of ASP, though in fact it’s been rebuilt from the ground
up. It’s actually a framework of libraries that you can use to build Web sites, and you have a
choice of languages to use, including C#, VB.NET (Visual Basic), and J# (Java). Because
ASP.NET gives you a large library of code for doing things like creating HTML forms and
accessing database tables, you can get a Web application up and running very quickly.
PHP, although it has a very rich standard library of functions, doesn’t give you a structured
framework to the extent that ASP.NET does.
Perl: Perl was one of the first languages used for creating dynamic Web pages, initially through
the use of CGI scripting and, later, integrating tightly into Web servers with technologies
like the Apache mod_perl module and ActivePerl for IIS. Though Perl is a powerful scripting
language, it’s harder to learn than PHP. It’s also more of a general - purpose language than
PHP, although Perl’s CPAN library includes some excellent modules for Web development.
Java: Like Perl, Java is another general - purpose language that is commonly used for Web
application development. Thanks to technologies like JSP (JavaServer Pages) and servlets,
Java is a great platform for building large - scale, robust Web applications. With software
such as Apache Tomcat, you can easily build and deploy Java - based Web sites on virtually
any server platform, including Windows, Linux, and FreeBSD.
Disadvantages of Servlets:
• Servlet is a mixture of Java skills and web related HTML skills, because you have to
write the business logic in Java and the presentation you should use the HTML, so
the role based development is missing in pure Servlet. The developer who is writing
Servlet should know Java and HTML.
• If your application is build on using Servlet technology, it very difficult for enhance-
ment and bugfixing.
• The servlet technolody require more steps to develop, Servlet require too longtime for
development.
• Designing in Servlet is difficult and slow down the application.
• You need to a Java Runtime environment on the server to run Servlet.
Disadvantages of JSP:
• JSP pages require about double the disk space to hold the page, Because JSP pages are
translated into class files, the server has to store the resultant class file with the JSP
pages.
• JSP pages must be compiled on the server when first accessed this initial compilation
produces a noticeable delay when accessing the JSP page for the first time.
• JSP implementation typically issue poor diagnostics, Because JSP pages are translated,
and then compiled into Java servlets, errors that creep in your pages are rarely seen as
errors arising from the coding of JSP pages.
• Lack of separation between presentation and logic means that providing multiple
presentations carries a very high cost.
Python: Conceived in the late 1980s, Python is another general - purpose programming language
that is now commonly used to build dynamic Web sites. Although it doesn’t have much
in the way of Web - specific features built into the language, many useful modules and
frameworks, such as Zope and Django, are available that make building Web applications
relatively painless. Many popular sites such as Google and YouTube are built using Python.
Python is a very nice language, but PHP is currently a lot more popular, and has a lot more
built - in functionality to help with building Web sites.
Ruby: Like Python, Ruby is another general - purpose language that has gained a lot of traction
Introduction to PHP 123

with Web developers in recent years. This is largely due to the excellent Ruby on Rails
application framework, which uses the Model - View - Controller (MVC) pattern, along
with Ruby’s extensive object - oriented programming features, to make it easy to build a
complete Web application very quickly. As with Python, Ruby is fast becoming a popular
choice among Web developers, but for now, PHP is much more popular.
ColdFusion: Along with ASP, Adobe ColdFusion was one of the first Web application frameworks
available, initially released back in 1995. ColdFusion’s main selling points are that it’s easy
to learn, it lets you build Web applications very quickly, and it’s really easy to create database
- driven sites.
An additional plus point is its tight integration with Flex, another Adobe technology that al-
lows you to build complex Flash - based Web applications. ColdFusion’s main disadvantages
compared to PHP include the fact that it’s not as popular (so it’s harder to find hosting and
developers), it’s not as flexible as PHP for certain tasks, and the server software to run your
apps can be expensive.
Note: ASP and ASP.NET have a couple of other disadvantages compared to PHP. First of all, they have a
commercial license, which can mean spending additional money on server software, and hosting is often
more expensive as a result. Secondly, ASP and ASP.NET are fairly heavily tied to the Windows platform,
whereas the other technologies in this list are much more cross - platform.

Introduction to PHP
PHP stands for PHP: Hypertext Preprocessor, which gives you a good idea of its core purpose: to
process information and produce hypertext (HTML) as a result.
• PHP is a server - side scripting language , which means that PHP scripts, or programs,
usually run on a Web server.
• PHP is an interpreted language - a PHP script is processed by the PHP engine each time it ’
s run.
PHP is a programming language for building dynamic, interactive Web sites. As a general rule,
PHP programs run on a Web server, and serve Web pages to visitors on request. One of the key
features of PHP is that you can embed PHP code within HTML Web pages, making it very easy for
you to create dynamic content quickly.
Although PHP only started gaining popularity with Web developers around 1998, it was created
by Rasmus Lerdorf way back in 1994. PHP started out as a set of simple tools coded in the C
language to replace the Perl scripts that Rasmus was using on his personal home page (hence the
original meaning of the “ PHP ” acronym). He released PHP to the general public in 1995, and
called it PHP version 2.
In 1997, two more developers, Zeev Suraski and Andi Gutmans, rewrote most of PHP and,
along with Rasmus, released PHP version 3.0 in June 1998. By the end of that year, PHP had
already amassed tens of thousands of developers, and was being used on hundreds of thousands of
Web sites.
For the next version of PHP, Zeev and Andi set about rewriting the PHP core yet again, calling
it the “Zend Engine” (basing the name “Zend” on their two names). The new version, PHP
4, was launched in May 2000. This version further improved on PHP 3, and included session
handling features, output buffering, a richer core language, ISAPI support, Perl Compatible Regular
Expressions (PCRE) library and support for a wider variety of Web server platforms.
Although PHP 4 was a marked improvement over version 3, it still suffered from a relatively
poor object - oriented programming (OOP) implementation. PHP 5, released in July 2004, addressed
this issue, with private and protected class members; final, private, protected, and static methods;
abstract classes; interfaces; and a standardized constructor/destructor syntax.
124 Chapter 5. Introduction to PHP

PHP 5 was yet another watershed in the evolution of the PHP language. Although previous
major releases had enormous numbers of new library additions, version 5 contained improvements
over existing functionality and added several features commonly associated with mature program-
ming language architectures like Vastly improved object-oriented capabilities, Try/catch exception
handling, Improved XML and Web Services support and Native support for SQLite.
PHP 5.3 is actually the most significant upgrade to the language since the release of 5.0.
Heralding a powerful array of new features including namespaces, late static binding, lambda
functions and closures, a new MySQL driver, and a variety of syntactical additions such as
NOWDOC syntax, version 5.3 represents a serious step forward in PHP’s evolution.
A new major version of PHP known as PHP 6 has been concurrently developed alongside PHP
5.X for several years, with the primary goal of adding Unicode support to the language. Although
PHP 6 beta releases had previously been made available at http://snaps.php.net

Difference between HTML & PHP

Sno HTML PHP


1. Hyper Text Markup Language Hypertext Preprocessor (Personal Home Page)
2. It is a Markup Language It is a Scripting Language
3. It is used to design a Static Web pages It is used to design a Dynamic Web pages
4. This code is executed in Client Machine (i.e This code is executed in Server machine
Web Browser)
5. No additional software is used to execute. Additionally PHP and Any server is needed to
execute the code
6. It does’t converted to any language After execution of php code is converted to
html code.
7. HTML is very easy and forgiving of mistakes Compare to html php is complex.
8. HTML easier than php learning time of PHP is longer than HTML
9. HTML where anything you put in creates an PHP would not give you an output if some-
output thing is wrong with your code
10. Extension .html Extension .php

Table 5.1: Difference between HTML and PHP

Features of PHP
Practicality
From the very start, the PHP language was created with practicality in mind. PHP’s early evolution
was not the result of the explicit intention to improve the language itself, but rather to increase its
utility to the user. The result is a language that allows the user to build powerful applications even
with a minimum of knowledge. For instance, a useful PHP script can consist of as little as one line;
unlike C, there is no need for the mandatory inclusion of libraries.
PHP is a loosely typed language, meaning there is no need to explicitly create, typecast, or
destroy a variable, although you are not prevented from doing so. PHP handles such matters
internally, creating variables on the fly as they are called in a script, and employing a best-guess
formula for automatically typecasting variables.

Power
PHP’s ability to interface with databases, manipulate form information, and create pages dynami-
cally, you might not know that PHP can also do the following:
• Create and manipulate Adobe Flash and Portable Document Format (PDF) files.
The anatomy of a PHP Page 125

• Evaluate a password for guessability by comparing it to language dictionaries and easily


broken patterns.
• Parse even the most complex of strings using the POSIX and Perl-based regular expression
libraries.
• Authenticate users against login credentials stored in flat files, databases, and even Microsoft’s
Active Directory.
• Communicate with a wide variety of protocols, including LDAP, IMAP, POP3, NNTP, and
DNS, among others.
• Tightly integrate with a wide array of credit-card processing solutions.
Possibility
• PHP developers are rarely bound to any single implementation solution. On the contrary, a
user is typically fraught with choices offered by the language.
• PHP’s flexible string-parsing capabilities offer users of differing skill sets the opportunity to
not only immediately begin performing complex string operations but also to quickly port
programs of similar functionality over to PHP.
• PHP offers comprehensive support for both procedural programming and object-oriented
paradigm.
• The recurring theme here is that PHP allows you to quickly capitalize on your current skill set
with very little time investment.

Price
PHP is available free of charge! Since its inception, PHP has been without usage, modification, and
redistribution restrictions. In recent years, software meeting such open licensing qualifications has
been referred to as open source software.
• Free of licensing restrictions imposed by most commercial products: Open source soft-
ware users are freed of the vast majority of licensing restrictions one would expect of
commercial counterparts.
• Open development and auditing process: Although not without incidents, open source
software has long enjoyed a stellar security record. Such high-quality standards are a
result of the open development and auditing process.
• Participation is encouraged: Development teams are not limited to a particular organiza-
tion. Anyone who has the interest and the ability is free to join the project. The absence
of member restrictions greatly enhances the talent pool for a given project, ultimately
contributing to a higher-quality product.

The anatomy of a PHP Page


PHP documents end with the extension .php. When a web server encounters this extension in a
requested file, it automatically passes it to the PHP processor. It need some syntactical rules for
parsing PHP code.

Embedding PHP Code in Your Web Pages


Default Syntax
The default delimiter syntax satrts with <?php and ends with ? >, like this

<h3>Welcome!</h3>
<?php
echo "<p>Welcome to PHP !</p>";
?>
126 Chapter 5. Introduction to PHP

<p>Some static output here!</p>

:::::::::: OUTPUT ::::::::::


Welcome to PHP !
Some static output here!
“<?php” This is due to the fact that PHP can be embedded within HTML Web pages. The final line
of your simple script tells the PHP engine that it’s reached the end of the current section of PHP
code, and that the following lines (if any) contain plain HTML again: “? >”

Short Tags
For less motivated typists, an even shorter delimiter syntax is available. Known as short-tags, this
syntax forgoes the php reference required in the default syntax, you may also encounter code where
the opening and closing syntax used is like this:
<?
echo "Welcome to PHP !";
?>

:::::::::: OUTPUT ::::::::::


Welcome to PHP !
When short-tags syntax is enabled and you want to quickly escape to and from PHP to output a bit
of dynamic text, you can omit these statements using an output variation known as short-circuit
syntax:
<?="This is another PHP example.";?>

Script
Certain editors have historically had problems dealing with PHP’s more commonly used escape
syntax variants. Therefore, support for another mainstream delimiter variant, < script >, is offered:
<script language="php">
print "This is another PHP example.";
</script>

:::::::::: OUTPUT ::::::::::


This is another PHP example.

ASP Style
Microsoft ASP pages employ a delimiting strategy similar to that used by PHP, delimiting static
from dynamic syntax by using a predefined character pattern: opening dynamic syntax with < %,
and concluding with %>. If you’re coming from an ASP background and prefer to continue using
this escape syntax, PHP supports it. Here’s an example:
<%
print "This is another PHP example.";
%>

:::::::::: OUTPUT ::::::::::


This is another PHP example.
Keep in mind that just because you can do something doesn’t mean you should. The ASP Style and
Script delimiting variants are rarely used and should be avoided unless you have ample reason for
doing so.
5.3 The anatomy of a PHP Page 127

Embedding Multiple Code blocks


You can escape to and from PHP as many times as required within a given page. For instance, the
following example is perfectly acceptable:

<html>
<head>
<title><?php echo "Welcome to PHP!";?></title>
</head>
<body>
<?php
$date = "Jan 1, 2014";
?>
<p>Today's date is <?=$date;?></p>
</body>
</html>

:::::::::: OUTPUT ::::::::::


Today's date is Jan 1, 2014

Commenting Your Code


Whether for your own benefit or for that of somebody tasked with maintaining your code, the im-
portance of thoroughly commenting your code cannot be overstated. PHP offers several syntactical
variations for documenting your code.

Single-Line C++ Syntax


Comments often require no more than a single line. Because of its brevity, there is no need to
delimit the comment’s conclusion because the newline ( \ n) character fills this need quite nicely.
PHP supports C++ single-line comment syntax, which is prefaced with a double slash (), like this:

<?php
// Filename: firstpage.php
// date: Aug 25, 2013
// This program printing a simple message
echo "This is a PHP program.";
?>

Shell Syntax
PHP also supports an alternative to the C++ -style single-line syntax, known as shell syntax, which
is prefaced with a hash mark (#). Revisiting the previous example, I’ll use hash marks to add some
information about the script:

<?php
# Filename: firstpage.php
# date: Aug 25, 2013
# This program printing a simple message
echo "This is a PHP program.";
?>

Multi-Line C Syntax
PHP also offers a multiple-line variant that can open and close the comment on different lines.
Here’s an example:
128 Chapter 5. Introduction to PHP

<?php
/*
Filename: firstpage.php
date: Aug 25, 2013
This program printing a simple message
*/
echo "This is a PHP program.";
?>

Output of above three programs are same i.e This is a PHP program.

Outputting Data to the Browser


print() statement
The print() statement outputs data passed to it . Its prototype looks like this:
int print(argument)

All of the following are plausible print() statements:


<?php
print("<p>PHP was created by Rasmus Lerdorf.</p>");
?>
<?php
$str = "Rasmus Lerdorf";
print "<p>PHP was created by $str.</p>";
?>
<?php
print "<p>PHP was created by Rasmus Lerdorf.</p>";
?>

All these statements produce identical output:PHP was created by Rasmus Lerdorf.
The print() statement’s return value is misleading because it will always return 1 regardless of
outcome.

echo() statement
Alternatively, you could use the echo() statement for the same purposes as print(). While there are
technical differences between echo() and print(), they’ll be irrelevant to most readers and therefore
aren’t discussed here. echo()’s prototype looks like this:

void echo(string argument1 [, ...string argumentN])

To use echo(), just provide it with an argument just as was done with print():

echo "PHP was created by Rasmus Lerdorf.";

As you can see from the prototype, echo() is capable of outputting multiple strings. The utility of this
particular trait is questionable; using it seems to be a matter of preference more than anything else.
Nonetheless, it’s available should you feel the need. Here’s an example:
<?php
$heavyweight = "Lennox Lewis";
$lightweight = "Floyd Mayweather";
echo $heavyweight, " and ", $lightweight, " are great fighters.";
?>
The anatomy of a PHP Page 129

This code produces the following: Lennox Lewis and Floyd Mayweather are great fighters.

The key difference between echo() and print() are


1. print() returns integer value echo() returns boolean(i.e TRUE or FALSE) value.
2. Through print() we pass only one string, in echo() we pass multiple strings.

printf() statement
The printf() statement is ideal when you want to output a blend of static text and dynamic infor-
mation stored within one or several variables. It’s ideal for two reasons. First, it neatly separates
the static and dynamic data into two distinct sections, allowing for easy maintenance. Second,
printf() allows you to wield considerable control over how the dynamic information is rendered to the
screen in terms of its type, precision, alignment, and position. Its prototype looks like this:
integer printf(string format [, mixed args])

For example, suppose you wanted to insert a single dynamic integer value into an otherwise static
string:
printf("one $ equals to %d rupees ", 62);

Executing this command produces the following:


one $ equals to 62 rupees In this example, %d is a placeholder known as a type specifier, and the d
indicates an integer value will be placed in that position. When the printf() statement executes, the
lone argument, 100, will be inserted into the placeholder.
The key difference between print() and printf() are
1. In print() paranthesis are optional where as in printf() compulsary.
2. Through print() we pass only one string, in printf() we pass multiple strings.
3. print() gives unformatted output where as printf() gives formatted output through type
specifiers.
The control strings are as follows

Type Description
%b Argument considered an integer; presented as a binary number
%d Argument considered an integer
%c Argument considered an integer; presented as a signed decimal number
%f Argument considered a floating-point number; presented as a floating-point number
%o Argument considered an integer; presented as an octal number
%s Argument considered a string; presented as a string
%u Argument considered an integer; presented as an unsigned decimal number
%x Argument considered an integer; presented as a lowercase hexadecimal number
%X Argument considered an integer; presented as an uppercase hexadecimal number

Table 5.2: Commonly Used Type Specifiers

sprintf() statement
The sprintf() statement is functionally identical to printf() except that the output is assigned to a
string rather than rendered to the browser. The prototype follows:
string sprintf(string format [, mixed arguments]);

An example follows:
130 Chapter 5. Introduction to PHP

$cost = sprintf("$%.2f", 43.2); // $cost = $43.20

In this example, %f is a placeholder known as a type specifier, and the f indicates a float value will be
placed in that position.
sprintf() print output to a variable, remaing three functions (i.e print(), echo(), and printf()) print
output on Web browser.

Identifiers
Identifiers are names made up by the programmer to refer to variables, functions, or types.
An identifier can consist of one or more characters and must begin with a letter or an underscore.
Furthermore, identifiers can consist of only letters, numbers, underscore characters, and other
ASCII characters from 127 through 255.

Rules for naming Identifiers


• Identifiers are case sensitive. Therefore, a variable named $recipe is different from a variable
named $Recipe, $rEciPe, or $recipE.
• Identifiers can be any length.
• An identifier name can’t be identical to any of PHP’s predefined keywords.
• The same identifier can be used in different scopes to refer to different elements.
• The first character must be a letter or an underscore(_).
• Identifier does’t starts with Numbers.
• Identifiers does’t contains any special characters except underscore(_).
Valid and Invalid Identifiers Examples

Valid Invalid
name,_name 2name
x_y x&y
xnoty x!y

Table 5.3: Valid and Invalid Identifiers

Variables
Variables are a fundamental part of any programming language. A variable is simply a container that
holds a certain value. Variables get their name because that certain value can change throughout the
execution of the script. It’s this ability to contain changing values that make variables so useful. “A
variable is a named memory location that contains data and may be manipulated
throughout the execution of the program.”

Rules for naming a variable


• Variable names begin with a dollar sign ( $ ).
• The first character after the dollar sign must be a letter or an underscore.
• The remaining characters in the name may be letters, numbers, or underscores without a
fixed limit
• An Variable name can’t be identical to any of PHP’s predefined keywords.
• Variables are case sensitive. Therefore, a variable named $recipe is different from a variable
named $Recipe, $rEciPe, or $recipE.
Declaring a variable is as simple as using its name in your script:
$my_ f irst_variable;
5.5 Variables 131

When PHP first sees a variable’s name in a script, it automatically creates the variable at that
point.
Here ’ s an example of declaring and initializing a variable:
$my_ f irst_variable = 3;
This creates the variable called $my_ f irst_variable , and uses the = operator to assign it a value of
3.
The following script creates two variables, initializes them with the values 5 and 6 , then outputs
their sum ( 11 ):
$x = 5;
$y = 6;
echo$x + $y;

Valid variables Invalid Variables


$color color
$_some_variable $2variable
$variable1 $%variable (or) varia%ble

Variable scope
The scope of a variable is the context within which it is defined. For the most part all PHP variables
only have a single scope. This single scope spans included and required files as well.

Local Variables
A variable declared in a function is considered local. That is, it can be referenced only in that
function. Any assignment outside of that function will be considered to be an entirely different
variable from the one contained in the function.
$x = 4;
function assignx () {
$x = 0;
printf("\$x inside function is %d <br />", $x);
}
assignx();
printf("\$x outside of function is %d <br />", $x);

OUTPUT:
$x inside function is 0
$x outside of function is 4

Global Variables
Global scope refers to any variable that is defined outside of any function. Global variables can be
accessed from any part of the script that is not insids the function. To access a global variable in php
, use the global keyword.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
132 Chapter 5. Introduction to PHP

echo "Inside the sum() function= $b";


}
Sum();
echo "<br>Outside sum() function= $b";
?>

:::::::::: OUTPUT ::::::::::


Inside the sum() function= 3
Outside sum() function= 3

The above script will output 3. By declaring aandb global within the function, all references to
either variable will refer to the global version. There is no limit to the number of global variables
that can be manipulated by a function.

static variables
Another important feature of variable scoping is the static variable. A static variable exists only
in a local function scope, but it does not lose its value when program execution leaves this scope.
Consider the following example

<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>

This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++
which increments the variable serves no purpose since as soon as the function exits the $a variable
disappears. To make a useful counting function which will not lose track of the current count, the
$a variable is declared static.

Variable variables
Sometimes it is convenient to be able to have variable variable names. That is, a variable name
which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a = 'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the
above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

<?php
$$a = 'world';
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with
contents “hello” and $hello with contents “world”. Therefore, this statement:
5.6 Constants 133

<?php
echo "$a ${$a}";
echo "$a World";
echo "$a $hello";
?>

i.e. above three statements produce the same output as: hello world.

Constants
A constant is a value that cannot be modified throughout the execution of a program. Constants are
particularly useful when working with values that definitely will not require modification, such as
Pi (3.141592). Once a constant has been defined, it cannot be changed (or redefined) at any other
point of the program. Constants are defined using the define() function.

boolean define(string name, mixed value [, bool case_insensitive])

If the optional parameter case_insensitive is included and assigned TRUE, subsequent references to
the constant will be case insensitive. Consider the following example in which the mathematical
constant Pi is defined:

define("PI", 3.141592);

Example: Valid and invalid constant names


<?php

// Valid constant names


define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");

// Invalid constant names


define("2FOO", "something");

// This is valid, but should be avoided:


// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");
?>

These are the differences between constants and variables:


• Constants do not have a dollar sign ($) before them;
• Constants may only be defined using the define() function, not by simple assignment;
• Constants may be defined and accessed anywhere without regard to variable scoping rules;
• Constants may not be redefined or undefined once they have been set; and
• Constants may only evaluate to scalar values.
PHP provides a large number of predefined constants to any script which it runs. Many of these
constants, however, are created by various extensions, and will only be present when those exten-
sions are available, either via dynamic loading or because they have been compiled in.
134 Chapter 5. Introduction to PHP

Scalar Data types Boolean, integer, float, and string


Compound data types array and object
Special data types resource and NULL

Table 5.4: Data Types in PHP

Data Types
PHP supports eight primitive data types with three classifications.

Scalar Data Types


Boolean
This is the simplest type. A boolean expresses a truth(TRUE/FALSE) value. It can be either TRUE
or FALSE. Alternatively, you can use zero to represent FALSE, and any nonzero(1,-1,8 etc.,) value
to represent TRUE.
Examples

$a = false; // $a is false.
$a = 0; // $a is false.
$a = 1; // $a is true.
$a = -1; // $a is true.
$a = 8; // $a is true.

Integer
An integer is representative of any whole number or, in other words, a number that does not contain
fractional parts. PHP supports integer values represented in base 10 (decimal), base 8 (octal), binary
(base 2) notation or base 16 (hexadecimal) numbering systems(optionally preceded by a sign (- or
+)).
Note: Binary integer literals are available since PHP 5.4.0.
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the
number with 0x. To use binary notation precede the number with 0b.

Example Number System


542 decimal
-987600 decimal
0542 octal
0xA1F6 hexadecimal
0b010101 binary

Table 5.5: Examples for valid Integers

The size of an integer is platform-dependent. although this is typically positive or negative 231
for PHP version 5 and earlier. PHP 6 introduced a 64-bit integer value, meaning PHP will support
integer values up to positive or negative 263 in size

float
Floating point numbers also known as floats, doubles, or real numbers, allow you to specify
numbers that contain fractional parts.
Floats are used to represent monetary values, weights, distances, and a whole host of other
representations in which a simple integer value won’t suffice. PHP’s floats can be specified in a
variety of ways, several of which are demonstrated here:
5.8 Expressions 135

4.5678
4.0
1.2e3;
7E-10;

Strings
A string is series of characters, where a character is the same as a byte. Strings are delimited by
single or double quotes in PHP.
Examples
"PHP is a great language"
"sri-venkatesa-perumal"
'*9technology\n'
"879#%^564"

Compound Data Types


Compound data types allow for multiple items of the same type to be aggregated under a single
representative entity.

Arrays
An array, is formally defined as an indexed collection of data values. Each member of the array
index (also known as the key) references a corresponding value and can be a simple numerical
reference to the value’s position in the series, or it could have some direct correlation to the value.
branch[0]="CSE";
branch[1]="ECE";
branch[2]="EEE";
.
.
.
branch[0]="MECH";

Object
The other compound datatype supported by PHP is the object. The object is a central concept of the
object-oriented programming paradigm. Unlike the other data types contained in the PHP language,
an object must be explicitly declared.
This declaration of an object’s characteristics and behavior takes place within something called
a class.
class Appliance {
private $_power;
function setPower($status) {
$this->_power = $status;
}
}
...
$blender = new Appliance;

Expressions
Expressions are the most important building stones of PHP. In PHP, almost anything you write is
an expression. The simplest yet most accurate way to define an expression is “anything that has a
value”
136 Chapter 5. Introduction to PHP

The most basic forms of expressions are constants and variables. When you type“$a = 5”,
you’re assigning ‘5’ into $a. ‘5’, obviously, has the value 5, or in other words ‘5’ is an expression
with the value of 5 (in this case, ‘5’ is an integer constant).
After this assignment, you’d expect $a’s value to be 5 as well, so if you wrote $b = $a, you’d
expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of
5 as well. If everything works right, this is exactly what will happen.
PHP takes expressions much further, in the same way many other languages do. PHP is an
expression-oriented language, in the sense that almost everything is an expression.

Operators
An operator is a symbol that specifies a particular action in an expression.

Arithmetic Operators
The arithmetic operators, perform various mathematical operations and will probably be used
frequently in many of your PHP programs. The division operator (“/”) returns a float value unless

Example Name Result


$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.

Table 5.6: Arithmetic Operators

the two operands are integers (or strings that get converted to integers) and the numbers are evenly
divisible, in which case an integer value will be returned. Operands of modulus are converted to
integers (by stripping the decimal part) before processing.
The result of the modulus operator % has the same sign as the dividend - that is, the result of $a
% $b will have the same sign as $a. For example:

<?php
echo (5 % 3)."\n"; // prints 2
echo (5 % -3)."\n"; // prints 2
echo (-5 % 3)."\n"; // prints -2
echo (-5 % -3)."\n"; // prints -2
?>

Assignment Operators
The basic assignment operator is “=”. Your first inclination might be to think of this as “equal to”.
Don’t. It really means that the left operand gets set to the value of the expression on the right (that
is, “gets set to”).
The value of an assignment expression is the value assigned. That is, the value of “$a = 3” is 3.
This allows you to do some tricky things:

<?php
$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.
?>
5.9 Operators 137

For arrays, assigning a value to a named key is performed using the "=>" operator. The
precedence of this operator is the same as other assignment operators. In addition to the basic
assignment operator, there are “combined operators” for all of the binary arithmetic, array union
and string operators that allow you to use a value in an expression and then set its value to the result
of that expression. For example:
<?php
$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";
?>

Note that the assignment copies the original variable to the new one, so changes to one will
not affect the other. This may also have relevance if you need to copy something like a large array
inside a tight loop.

Assignment by Reference
Assignment by reference is also supported, using the “$var = &$othervar;” syntax. Assignment by
reference means that both variables end up pointing at the same data, and nothing is copied
anywhere.
<?php
$a = 3;
$b = &$a; // $b is a reference to $a
print "$a\n"; // prints 3
print "$b\n"; // prints 3
$a = 4; // change $a
print "$a\n"; // prints 4
print "$b\n"; // prints 4 as well, since $b is a reference to $a,
// which has been changed
?>

Bitwise Operators
Bitwise operators allow evaluation and manipulation of specific bits within an integer.

Example Name Result


$a & $b And Bits that are set in both $a and $b are set.
Or (inclusive or) Bits that are set in either $a or $b are set.
$a | $b
ˆ
$a $b Xor (exclusive or) Bits that are set in $a or $b but not both are set.
$̃a Not Bits that are set in $a are not set, and vice versa.
$a << $b Shift left Shift the bits of $a $b steps to the left (each step means
"multiply by two")
$a >> $b Shift right Shift the bits of $a $b steps to the right (each step means
"divide by two")

Table 5.7: Bitwise Operators

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros
shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is
not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an
operand is preserved.
138 Chapter 5. Introduction to PHP

Comparison Operators
Comparison operators, as their name implies, allow you to compare two values. You may also be
interested in viewing the type comparison tables, as they show examples of various type related
comparisons.

Example Name Result


$a == $b Is equal to True if $a and $b are equivalent
$a != $b Is not equal to True if $a is not equal to $b
$a === $b Is identical to True if $a and $b are equivalent and $a and $b have
the same type
$a < $b Less than True if $a is less than $b
$a >$b Greater than True if $a is greater than $b
$a <= $b Less than or equal to True if $a is less than or equal to $b
$a >= $b Greater than or equal to True if $a is greater than or equal to $b
($a == 12) ? 5 : -1 Ternary If $a equals 12, return value is 5; otherwise, return
value is -1

Table 5.8: Comparison Operators

Error Control Operators


PHP supports one error control operator: the “at” sign (“@”). When prepended to an expression in
PHP, any error messages that might be generated by that expression will be ignored.
If you have set a custom error handler function with set_error_handler() then it will still get
called, but this custom error handler can (and should) call error_reporting() which will return 0
when the call that triggered the error was preceded by an @.
If the track_errors feature is enabled, any error message generated by the expression will be
saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early
if you want to use it.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");
// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
?>

Execution Operators
PHP supports one execution operator: backticks (´). PHP will attempt to execute the contents of the
backticks as a shell command; the output will be returned. Use of the backtick operator is identical
to shell_exec().

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>
5.9 Operators 139

Incrementing/Decrementing Operators
PHP supports C-style pre- and post-increment and decrement operators.
Note: The increment/decrement operators do not affect boolean values. Decrementing NULL
values has no effect too, but incrementing them results in 1.

Example Name Result


++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
–$a Pre-decrement Decrements $a by one, then returns $a.
$a– Post-decrement Returns $a, then decrements $a by one.

Table 5.9: Increment/decrement Operators

String Operators
There are two string operators. The first is the concatenation operator (’.’), which returns the
concatenation of its right and left arguments. The second is the concatenating assignment operator
(’.=’), which appends the argument on the right side to the argument on the left side. Please read
Assignment Operators for more information.

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>

Logical Operators

Example Name Result


$a && $b AND True if both $a and $b are true
$a AND $b AND True if both $a and $b are true
$a || $b OR True if either $a or $b is true
$a OR $b OR True if either $a or $b is true
!$a NOT True if $a is not true
NOT $a NOT True if $a is not true
$a XOR $b Exclusive OR True if only $a or only $b is true

Table 5.10: Logical Operators

Array Operators
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in
both arrays, the elements from the left-hand array will be used, and the matching elements from the
right-hand array will be ignored.

Example:
<?php
140 Chapter 5. Introduction to PHP

Example Name Result


$a + $b Union Union of $a and $b.
$a == $b Equality TRUE if $a and $b have the same keyvalue
pairs.
$a === $b Identity TRUE if $a and $b have the same keyvalue
pairs in the same order and of the same types.
$a != $b Inequality TRUE if $a is not equal to $b.
$a <> $b Inequality TRUE if $a is not equal to $b.
$a !== $b Non-identity TRUE if $a is not identical to $b.

Table 5.11: Array Operators

$a = array("a" => "apple", "b" => "banana");


$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b


echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // Union of $b and $a


echo "Union of \$b and \$a: \n";
var_dump($c);
?>

Operator Precedence
The precedence of an operator specifies how “tightly” it binds two expressions together. For
example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*")
operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force
precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.
When operators have equal precedence, their associativity decides whether they are evaluated
starting from the right, or starting from the left.

Operator Associativity
The associativity characteristic of an operator specifies how operations of the same precedence are
evaluated as they are executed. Associativity can be performed in two directions, left-to-right or
right-to-left. Left-to-right associativity means that the various operations making up the expression
are evaluated from left to right.
$value = 3 * 4 * 5 * 7 * 2;

The preceding example is the same as the following:


$value = ((((3 * 4) * 5) * 7) * 2);

This expression results in the value 840 because the multiplication (*) operator is left-to-right
associative. In contrast, right-to-left associativity evaluates operators of the same precedence from
right to left:
$c = 5;
print $value = $a = $b = $c;
5.10 Statements 141

The preceding example is the same as the following:

$c = 5;
$value = ($a = ($b = $c));

When this expression is evaluated, variables $value, $a, $b, and $c will all contain the value 5
because the assignment operator (=) has right-to-left associativity.

Statements
Any PHP script is built out of a series of statements. A statement can be an assignment, a function
call, a loop, a conditional statement or even a statement that does nothing (an empty statement).
Statements usually end with a semicolon. In addition, statements can be grouped into a statement-
group by encapsulating a group of statements with curly braces. A statement-group is a statement
by itself as well.

Conditional Statements
Conditional statements make it possible for your computer program to respond accordingly to a
wide variety of inputs, using logic to discern between various conditions based on input value.

The if Statement
The if construct is one of the most important features of many languages, PHP included. It allows
for conditional execution of code fragments. PHP features an if structure that is similar to that of C.

if (expr)
statement;

As described in the section about expressions, expression is evaluated to its Boolean value. If
expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it’ll
ignore it.
The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a > $b)
echo "a is bigger than b";
?>

Often you’d want to have more than one statement to be executed conditionally. Of course,
there’s no need to wrap each statement with an if clause. Instead, you can group several statements
into a statement group. For example, this code would display a is bigger than b if $a is bigger than
$b, and would then assign the value of $a into $b:

<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>

If statements can be nested infinitely within other if statements, which provides you with
complete flexibility for conditional execution of the various parts of your program.
142 Chapter 5. Introduction to PHP

The else Statement


Often you’d want to execute a statement if a certain condition is met, and a different statement if
the condition is not met. This is what else is for. else extends an if statement to execute a statement
in case the expression in the if statement evaluates to FALSE. For example, the following code
would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise:
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>

The else statement is only executed if the if expression evaluated to FALSE,

The elseif/else if Statement


elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to
execute a different statement in case the original if expression evaluates to FALSE. However, unlike
else, it will execute that alternative expression only if the elseif conditional expression evaluates to
TRUE.
For example, the following code would display a is bigger than b, a equal to b or a is smaller
than b:
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>

There may be several elseifs within the same if statement. The first elseif expression (if any)
that evaluates to TRUE would be executed. In PHP, you can also write ‘else if’ (in two words) and the
behavior would be identical to the one of ’elseif’ (in a single word). The syntactic meaning is
slightly different (if you’re familiar with C, this is the same behavior) but the bottom line is that
both would result in exactly the same behavior.
The elseif statement is only executed if the preceding if expression and any preceding elseif
expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

switch
The switch statement is similar to a series of IF statements on the same expression. In many
occasions, you may want to compare the same variable (or expression) with many different values,
and execute a different piece of code depending on which value it equals to. This is exactly what
the switch statement is for.
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
5.10 Statements 143

echo "i equals 1";


} elseif ($i == 2) {
echo "i equals 2";
}

switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
It is important to understand how the switch statement is executed in order to avoid mistakes. The
switch statement executes line by line (actually, statement by statement). In the beginning, no code
is executed. Only when a case statement is found with a value that matches the value of the switch
expression does PHP begin to execute the statements.
A special case is the default case. This case matches anything that wasn’t matched by the other
cases. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
The case expression may be any expression that evaluates to a simple type, that is, integer
or floating-point numbers and strings. Arrays or objects cannot be used here unless they are
dereferenced to a simple type.

Looping Statements
Looping mechanisms offer a simple means for accomplishing a commonplace task in programming:
repeating a sequence of instructions until a specific condition is satisfied.

The while Statement


while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The
basic form of a while statement is:
144 Chapter 5. Introduction to PHP

while (expr)
statement;

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s)
repeatedly, as long as the while expression evaluates to TRUE.
The value of the expression is checked each time at the beginning of the loop, so even if this
value changes during the execution of the nested statement(s), execution will not stop until the end
of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the
while expression evaluates to FALSE from the very beginning, the nested statement(s) won’t even
be run once.
Like with the if statement, you can group multiple statements within the same while loop by
surrounding a group of statements with curly braces, or by using the alternate syntax:
while (expr):
statement
...
endwhile;

The following examples are identical, and both print the numbers 1 through 10:
<?php
/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}

/* example 2 */
$i = 1;
while ($i <= 10):
echo $i;
$i++;
endwhile;
?>

The do...while Statement


do-while loops are very similar to while loops, except the truth expression is checked at the end
of each iteration instead of in the beginning. The main difference from regular while loops is that
the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at
the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth
expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the
beginning, the loop execution would end immediately).
There is just one syntax for do-while loops:

<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
5.10 Statements 145

The above loop would run one time exactly, since after the first iteration, when truth expression
is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.
Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping
execution in the middle of code blocks, by encapsulating them with do-while (0), and using the
break statement. The following code fragment demonstrates this:

<?php
do {
if ($i < 5) {
echo "i is not big enough";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "i is ok";/* process i */
} while (0);
?>

The for Statement


for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of
a for loop is:
for (expr1; expr2; expr3)
statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of
the loop.
In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues
and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions separated by commas. In
expr2, all expressions separated by a comma are evaluated but the result is taken from the last part.
expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE,
like C). This may not be as useless as you might think, since often you’d want to end the loop using
a conditional break statement instead of using the for truth expression.
Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* example 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
146 Chapter 5. Introduction to PHP

/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may
find that being able to use empty expressions in for loops comes in handy in many occasions.
PHP also supports the alternate “colon syntax” for for loops.

for (expr1; expr2; expr3):


statement
...
endfor;

The foreach Statement


The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays
and objects, and will issue an error when you try to use it on a variable with a different data type or
an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)


statement
foreach (array_expression as $key => $value)
statement

The first form loops over the array given by array_expression. On each iteration, the value of
the current element is assigned to $value and the internal array pointer is advanced by one (so on
the next iteration, you’ll be looking at the next element).
The second form will additionally assign the current element’s key to the $key variable on each
iteration.

The break Statements


break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are
to be broken out of.

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
5.10 Statements 147

/* Using the optional argument. */


$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
?>

The goto Statements


The goto operator can be used to jump to another section in the program. The target point is
specified by a label followed by a colon, and the instruction is given as goto followed by the desired
target label. This is not a full unrestricted goto. The target label must be within the same file and
context, meaning that you cannot jump out of a function or method, nor can you jump into one.
You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a
common use is to use a goto in place of a multi-level break. An example follows:
<?php
for ($count = 0; $count < 10; $count++)
{
$randomNumber = rand(1,50);
if ($randomNumber < 10)
goto less;
else
echo "Number greater than 10: $randomNumber<br />";
}
less:
echo "Number less than 10: $randomNumber<br />";
?>

The continue Statement


continue is used within looping structures to skip the rest of the current loop iteration and continue
execution at the condition evaluation and then the beginning of the next iteration.
Note: PHP the switch statement is considered a looping structure for the purposes of continue.
continue accepts an optional numeric argument which tells it how many levels of enclosing loops
it should skip to the end of. The default value is 1, thus skipping to the end of the current
loop.

<?php
while (list($key, $value) = each($arr)) {
if (!($key % 2)) { // skip odd members
continue;
}
148 Chapter 5. Introduction to PHP

do_something_odd($value);
}
$i = 0;
while ($i++ < 5) {
echo "Outer<br />\n";
while (1) {
echo "Middle<br />\n";
while (1) {
echo "Inner<br />\n";
continue 3;
}
echo "This never gets output.<br />\n";
}
echo "Neither does this.<br />\n";
}
?>

Omitting the semicolon after continue can lead to confusion. Here’s an example of what you
shouldn’t do.

<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>

return
If called from within a function, the return statement immediately ends execution of the current
function, and returns its argument as the value of the function call. return will also end the execution
of an eval() statement or script file.
If called from the global scope, then execution of the current script file is ended. If the current
script file was included or required, then control is passed back to the calling file. Furthermore, if the
current script file was included, then the value given to return will be returned as the value of the
include call. If return is called from within the main script file, then script execution ends. If the current
script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini,
then that script file’s execution is ended.

require
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR
level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING)
which allows the script to continue.

include
The include statement includes and evaluates the specified file. The documentation below also
applies to require.
Files are included based on the file path given or, if none is given, the include_path specified. If the
file isn’t found in the include_path, include will finally check in the calling script’s own directory
5.11 Arrays 149

and the current working directory before failing. The include construct will emit a warning if it
cannot find a file; this is different behavior from require, which will emit a fatal error.
If a path is defined - whether absolute (starting with a drive letter or\ on Windows, or / on
Unix/Linux systems) or relative to the current directory (starting with . or ..) - the include_path will
be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent
directory to find the requested file.
For more information on how PHP handles including files and the include path, see the
documentation for include_path.
When a file is included, the code it contains inherits the variable scope of the line on which the
include occurs. Any variables available at that line in the calling file will be available within the
called file, from that point forward. However, all functions and classes defined in the included file
have the global scope.

Arrays
An array is a single variable that can hold more than one value at once. You can think of an array as
a list of values. Each value within an array is called an element , and each element is referenced
by its own index , which is unique to that array. To access an element’s value - whether you’re
creating, reading, writing, or deleting the element - you use that element’s index.
Note: An array index is often referred to as a key. Typically, a numeric index is called an index
and a string index is called a key; however there’s no hard - and - fast rule with this.
In PHP, There are three kinds of Arrays:-
• Numeric Array:- An Array with numeric Key(index).
• Associative Array:- An array where each key is associated with a value.
• Multi-dimentional Array:- An array containing one or more arrays.

Creating Arrays
Individual elements of a PHP array are referenced by denoting the element between a pair of square
brackets. Because there is no size limitation on the array, you can create the array simply by making
reference to it, like this:
$branch[0] = "CSE";

Additional values can be added by mapping each new value to an array index, like this:
$branch[1] = "EEE";
$branch[2] = "ECE";
...
$branch[10] = "MECH";

Interestingly, if you intend for the index value to be numerical and ascending, you can omit the
index value at creation time:
$branch[] = "CSE";
$branch[] = "ECE";
...
$branch[] = "EEE";

Creating Arrays with array()


The simplest way to create a new array variable is to use PHP’s built - in array() construct. This
takes a list of values and creates an array containing those values, which you can then assign to a
variable:
150 Chapter 5. Introduction to PHP

$branch = array( "CSE", "ECE","EEE","MECH" );

In this line of code, an array of four elements is created, with each element containing a string
value. The array is then assigned to the variable $branch . You can now access any of the array
elements via the single variable name, $branch , as you see in a moment.
If you want to create an associative array, where each element is identified by a string index
rather than a number, you need to use the => operator, as follows:
$student = array( "Name" = > "PRAVEEN","branch" = > "CSE","Gender" => "Male");

This creates an array with three elements: “ PRAVEEN ” , which has an index of “ Name “ ; “
CSE ”, which has an index of “ branch “ ; and “Male” , which has an index of “ Gender ”.

Multidimentional arrays
In Multi-dimentional array elements in the array can be an array, and each element in the sub-array
can be an arrya and so on.
Example:- In this example we create multidimentional array, with automatically assigned keys.
<?php
$svpp=array("UG"=>array("CSE","ECE","EEE","MECH"),
"PG"=>array("M.Tech(CSE)","M.Tech(CS)","M.Tech(VLSI)"),
"Dip"=>array("DCME","DECE","DEEE"));
?>

The above array would look like this it written to the output:
Arry([UG]=>Array( [0]=>CSE
[1]=>ECE
[2]=>EEE
[3]=>MECH)
[PG]=>Array( [0]=>M.Tech(CSE)
[1]=>M.Tech(CS)
[2]=>M.Tech(VLSI))
[Dip]=>Array([0]=>DCME
[1]=>DECE
[2]=>DEEE))

Accessing Array Elements


Once you’ve created your array, how do you access the individual values inside it? In fact, you do
this in much the same way as you access the individual characters within a string:
$branches = array( "CSE","ECE","EEE","MECH" );
$mybranch = $branches[0]; // $mybranch contains "CSE"
$anotherbranch = $branches[1]; // $anotherbranch contains "ECE"

In other words, you write the variable name, followed by the index of the element in square
brackets. If you want to access the elements of an associative array, simply use string indices rather
than numbers:
$student = array( "Name" = > "PRAVEEN","branch" = > "CSE","Gender" => "Male");

$studentName = $student["Name"]; // $studentName contains "PRAVEEN"


$studentBranch = $student["branch"]; // $studentBranch contains "CSE"
5.11 Arrays 151

You don’t have to use literal values within the square brackets; you can use any expression, as
long as it evaluates to an integer or string as appropriate:
$branches = array( "CSE", "IT", "ECE", "EEE" );
$pos = 2;
echo $branches[$pos + 1]; // Displays EEE

Outputting an Array
The most common way to output an array’s contents is by iterating over each key and echoing the
corresponding value. For instance, a foreach statement does the trick nicely:
$branchs = array("CSE", "ECE", "EEE");
foreach ($branchs AS $branch) {
echo "{$branch}<br />";
}

Outputting an Entire Array with print_r()


You can’t just print an array with print() or echo() , like you can with regular variables, because
these functions can work with only one value at a time. However, PHP does give you a function
called print_r() that you can use to output the contents of an array for debugging.
Using print_r() is easy - just pass it the array you want to output:

print_r( $array );

Example:

print_r($student);

:::::::::: OUTPUT ::::::::::


array( "Name" = > "PRAVEEN","branch" = > "CSE","Gender" => "Male")

Adding and Removing Array Elements


PHP provides a number of functions for both growing and shrinking an array.

Adding a Value to the Front of an Array


The array_unshift() function adds elements to the front of the array. All preexisting numerical
keys are modified to reflect their new position in the array, but associative keys aren’t affected. Its
prototype follows:

int array_unshift(array array, mixed variable [, mixed variable...])

The following example adds two branches to the branch of the $branchs array:

$branchs = array("IT", "EEE", "MECH");


array_unshift($branchs, "CSE", "ECE");
// $branchs = array("CSE", "ECE", "IT", "EEE", "MECH");

Adding a Value to the End of an Array


The array_push() function adds a value to the end of an array, returning the total count of elements in
the array after the new value has been added. You can push multiple variables onto the array
simultaneously by passing these variables into the function as input parameters. Its prototype
follows:
152 Chapter 5. Introduction to PHP

int array\_push(array array, mixed variable [, mixed variable...])

The following example adds two more branchs onto the $branchs array:

$branchs = array("IT", "EEE", "MECH");


array_push($branchs, "CSE", "ECE");
// $branchs = array("IT", "EEE", "MECH", "CSE", "ECE");

Removing a Value from the Front of an Array


The array_shift() function removes and returns the first item found in an array. If numerical keys
are used, all corresponding values will be shifted down, whereas arrays using associative keys will
not be affected. Its prototype follows:

mixed array\_shift(array array)

The following example removes the first branch from the $branchs array:

$branchs = array("IT", "EEE", "MECH", "CSE", "ECE");


$branch = array_shift($branchs);
// $branchs = array( "EEE", "MECH", "CSE", "ECE")
// $branch = "IT"

Removing a Value from the End of an Array


The array_pop() function removes and returns the last element from an array. Its prototype follows:

mixed array_pop(array array)

The following example removes the last branch from the $branchs array:

$branchs = array( "EEE", "MECH", "CSE", "ECE")


$branch = array_pop($branchs);
// $branchs = array( "EEE", "MECH", "CSE")
// $branch = "ECE"

Searching an Array
The in_array() function searches an array for a specific value, returning TRUE if the value is found
and FALSE otherwise. Its prototype follows:

boolean in_array(mixed needle, array haystack [, boolean strict])

In the following example, a message is output if a specified branch is found in an array


consisting of branchs.

$branch = "CSE";
$branchs = array( "EEE", "MECH", "CSE", "ECE");
if(in_array($branch, $branchs)) echo "$branch existed in array";

The optional third parameter, strict, forces in_array() to also consider type.
5.12 Strings 153

Sorting an Array
The sort() function sorts an array, ordering elements from lowest to highest value. Its prototype
follows:

void sort(array array [, int sort_flags])

The sort() function doesn’t return the sorted array. Instead, it sorts the array “in place,” returning
nothing, regardless of outcome. The optional sort_flags parameter modifies the function’s default
behavior in accordance with its assigned value:
SORT_NUMERIC: Sorts items numerically. This is useful when sorting integers or floats.
SORT_REGULAR: Sorts items by their ASCII value. This means that B will come before a, for
instance. A quick search online produces several ASCII tables, so one isn’t reproduced in
this book.
SORT_STRING: Sorts items in a fashion that better corresponds with how a human might
perceive the correct order. See natsort() for more information about this matter, introduced
later in this section.

$grades = array(42, 98, 100, 100, 43, 12);


sort($grades);
print_r($grades);

:::::::::: OUTPUT ::::::::::


Array ( [0] => 12 [1] => 42 [2] => 43 [3] => 98 [4] => 100 [5] => 100 )

Reversing Array Element Order


The array_reverse() function reverses an array’s element order. Its prototype follows:

array array_reverse(array array [, boolean preserve_keys])

If the optional preserve_keys parameter is set to TRUE, the key mappings are maintained.
Otherwise, each newly rearranged value will assume the key of the value previously presiding at
that position:

$grades = array(42, 98, 100, 100, 43, 12);


print_r(array_reverse($grades));

:::::::::: OUTPUT ::::::::::


Array ( [0] => 12 [1] => 43 [2] => 100 [3] => 100 [4] => 98 [5] => 42 )

Arrays with associative keys are not affected by preserve_keys; key mappings are always preserved
in this case.

Strings
There are three ways to write a literal string in your program: using single quotes, double quotes, and
the here document (heredoc) format derived from the Unix shell. These methods differ in whether
they recognize special escape sequences that let you encode other characters or interpolate variables.
154 Chapter 5. Introduction to PHP

Single-Quoted Strings
Single-quoted strings do not interpolate variables. Thus, the variable name in the following string
is not expanded because the string literal in which it occurs is singlequoted:
$name = 'Fred';
$str = 'Hello, $name'; // single-quoted
echo $str;
OUTPUT: Hello, $name

The only escape sequences that work in single-quoted strings are ’, which puts a single quote in a
single-quoted string, and \\, which puts a backslash in a single-quoted string. Any other occurrence
of a backslash is interpreted simply as a backslash:
$name = 'Tim O\'Reilly';// escaped single quote
echo $name;
$path = 'C:\\WINDOWS'; // escaped backslash
echo $path;
$nope = '\n'; // not an escape
echo $nope;

Double-Quoted Strings
Strings enclosed in double quotes are the most commonly used in PHP scripts because they offer the
most flexibility.
Escape sequences are also parsed. Consider this example:
<?php
$output = "This is one line.\n And this is another line.";
echo $output;
?>

Here Documents (heredocs)


You can easily put multiline strings into your program with a heredoc, as follows:
$clerihew = <<< Identifier
Sir Humphrey Davy
Abominated gravy.
He lived in the odium
Of having discovered sodium.
identifier;
echo $clerihew;
The <<< identifier token tells the PHP parser that you’re writing a heredoc. There must be a space
after the <<< and before the identifier. You get to pick the identifier. The next line starts the text
being quoted by the heredoc, which continues until it reaches a line that consists of nothing but the
identifier.
As a special case, you can put a semicolon after the terminating identifier to end the statement,
as shown in the previous code. If you are using a heredoc in a more complex expression, you need
to continue the expression on the next line, as shown here:
printf(<<< Template
%s is %d years old.
Template
, "Fred", 35);
5.12 Strings 155

String Manipulation Functions


Length of a String
In PHP we use the function strlen() to determine the length of the String(s). I treturns number of
characters in a string including spaces. The prototype is as follows:

int strlen(string str);

The following example to check length of user name

<?php
$uname = "dontap";
if (strlen($uname) <= 10)
echo "uname is too short!";
else
echo "Uname is valid!";
?>

Comparing two strings


In PHP, Comparing two strings using strcmp() function. It compare two strings with case-sensitive.
The prototyep is as follows:

int strcmp(string str1, string str2)

It returns three possible values: 0 if str1 and str2 are same, -1 if str1 is less than str2 and 1 if str1 is
greater than str2.
The following example demonstrate comparing password and confirm password:

<?php
$pwd = "dontap";
$cpwd = "donthap";
if (strcmp($pwd, $cpwd) != 0) {
echo "Password and Confirm-password do not match!";
} else {
echo "Password and Confirm-password match!";
}
?>

Changing Case
PHP has several functions for changing the case of strings: strtolower() and strtoup per() operate
on entire strings, ucfirst() operates only on the first character of the string, and ucwords() operates
on the first character of each word in the string. Each function takes a string to operate on as an
argument and returns a copy of that string, appropriately changed. For example:

$string1 = "FRED flintstone";


$string2 = "barney rubble";
print(strtolower($string1));
print(strtoupper($string1));
print(ucfirst($string2));
print(ucwords($string2));
156 Chapter 5. Introduction to PHP

Removing HTML tags from strings


The strip_tags() function removes HTML tags from a string.

$input = '<p>Howdy, &quot;Cowboy&quot;</p>';


$output = strip_tags($input);
// $output is 'Howdy, &quot;Cowboy&quot;'

The function may take a second argument that specifies a string of tags to leave in the string. List
only the opening forms of the tags. The closing forms of tags listed in the second parameter are
also preserved:

$input = 'The <b>bold</b> tags will <i>stay</i><p>';


$output = strip_tags($input, '<b>');
// $output is 'The <b>bold</b> tags will stay'

Attributes in preserved tags are not changed by strip_tags(). Because attributes such as style and
onmouseover can affect the look and behavior of web pages, preserving some tags with strip_tags()
won’t necessarily remove the potential for abuse.

Regular Expressions
Regular expressions provide the foundation for describing or matching data according to defined
syntax rules. A regular expression is nothing more than a pattern of characters itself, matched against
a certain parcel of text It is used like validations in forms when taking the input from users.
The structure of a POSIX (Portable Operating System Interface for Unix) regular expression
is similar to that of a typical arithmetic expression: various elements (operators) are combined to
form a more complex expression. The meaning of the combined regular expression elements is
what makes them so powerful. You can use the syntax to find not only literal expressions, such as a
specific word or number, but also a multitude of semantically different but syntactically similar
strings, such as all HTML tags in a file.
Brackets ([]) are used to represent a list, or range, of characters to be matched.
• [0 − 9] matches any decimal digit from 0 through 9.
• [a − z] matches any character from lowercase a through lowercase z.
• [A − Z] matches any character from uppercase A through uppercase Z.
• [A − Za − z] matches any character from uppercase A through lowercase z.

Character Classes
In PHP, We have several predefined character ranges, also known as character classes. Character
classes specify an entire range of characters-for example, the alphabet or an integer set. Standard
classes include the following:
• [: al pha :]: Lowercase and uppercase alphabetical characters. This can also be specified as
[A-Za-z].
• [: alnum :]: Lowercase and uppercase alphabetical characters and numerical digits. This can
also be specified as [A-Za-z0-9].
• [: cntrl :]: Control characters such as tab, escape, or backspace.
• [: digit :]: Numerical digits 0 through 9. This can also be specified as [0-9].
• [: graph :]: Printable characters found in the range of ASCII 33 to 126.
• [: lower :]: Lowercase alphabetical characters. This can also be specified as [a-z].
• [: punct :]: Punctuation characters, including `! # $ % &ˆ ( ) - _ + = { } [ ] : ; ’ <> , . ? and /.
• [: upper :]: Uppercase alphabetical characters. This can also be specified as [A-Z].
5.14 Functions 157

• [: space :]: Whitespace characters, including the space, horizontal tab, vertical tab, new line,
form feed, or carriage return.
• [: xdigit :]: Hexadecimal characters. This can also be specified as [a-fA-F0-9].

Functions
A function is a named block of code that performs a specific task, possibly acting upon a set of
values given to it, or parameters, and possibly returning a single value.

Pre-define Functions
More than 1,000 functions are built into the standard PHP distribution. You can invoke the function
you want simply by specifying the function name, assuming that the function has been made
available either through the library’s compilation into the installed distribution or via the include()
or require() statement.
Example:

<?php
$value = pow(5,3); // returns 125
echo $value;
# or
# echo pow(5,3);
?>

User-Defined Functions
PHP support User-defined functions also. To define a function, use the following syntax:

function functionName(parameters)
{
function-body
}

Example:

function myFun() //called function..


{
echo "My first Function";
}
myFun();//Calling function..

Passing Arguments by Value


You’ll often find it useful to pass data into a function. Example

<?php
$a=20;
$value = pow(5,3);
myFun($value,$a,10);
echo $value;
function myFun($value,$a,$c)
{
$b=$a+$value+$c;
echo "<br> $b <br>";
158 Chapter 5. Introduction to PHP

}
?>
//Output: 155 & 125

This function accepts two parameters, aptly named $value and $a, which are used in the calculation.
When you pass an argument in this manner, it’s called passing by value. This means that any
changes made to those values within the scope of the function are ignored outside of the function.

Passing Arguments by Reference


We may want any changes made to an argument within a function to be reflected outside of the
function’s scope. Passing the argument by reference accomplishes this. Passing an argument by
reference is done by appending an ampersand to the front of the argument. Here’s an example:
<?php
$a=20;
$value = pow(5,3);
myFun($value,$a,10);
echo $value,"<br>";
echo $a,"<br>";
function myFun(&$value,&$a,$c)
{
$c=$a+$value+$c;
echo "<br> $c <br>";
$value+=10;
$a=$a*$a;
}
?>
//OUTPUT: 155,135,400

Default Argument Values


Default values can be assigned to input arguments, which will be automatically assigned to the
argument if no other value is provided. Example
<?php
$a=20;
myFun($a,10);
echo $a,"<br>";
function myFun($a,$c,$value=0.876)
{
$c=$a+$value+$c;
echo "<br> $c <br>";
$value+=10;
$a=$a*$a;
echo $value;
}
?>
//output:30.876, 10.876400

Returning Values from a Function


The return Statement The return() statement returns any ensuing value back to the function caller,
returning program control back to the caller’s scope in the process. If return() is called from
within the global scope, the script execution is terminated. Example:
Functions 159

<?php
$a=20;
$x=myFun($a,10);
echo $a,"<br>";
echo $x;
function myFun($a,$c,$value=0.876)
{
$c=$a+$value+$c;
$value+=10;
$a=$a*$a;
echo $value;
return $c;
}
?>
//Output: 10.87620
30.876

Returning Multiple Values It’s often convenient to return multiple values from a function. Exam-
ple:

<?php
function UserProfile()
{
$user[] = "08G01A0542";
$user[] = "D PRAVEEN KUMAR";
$user[] = "dontap@csta.acm.org";
return $user;
}
list($rno, $name, $email) = UserProfile();
echo "Roll Number: <b>$rno</b> <br> Name: <b>$name</b> <br> email: <b>$email</b>";
?>
OUTPUT: Roll Number: 08G01A0542
Name: D PRAVEEN KUMAR
email: dontap@csta.acm.org

Accomplishing this is much easier than you might think, with the help of a very useful
language construct, list(). The list() construct offers a convenient means for retrieving values
from an array

Recursive Functions
Recursive functions, or functions that call themselves.

<?php
function factorial ($natural) {
// This guarantees that the function will return 1 (even with 0 as argument)
$result = 1;
if ($natural > 0) {
// Here we're applying the second formula: n * (n - 1)!
$result = $natural * factorial(($natural - 1));
}
// return the acumulated result
160 Chapter 5. Introduction to PHP

return $result;
}
echo factorial(6);
?>
OUTPUT: 720

Programming Exercise
1. Write a PHP program to sort list without using sort().
<?php
$array=array('2','4','8','5','1','7','6','9','10','3');

echo "Unsorted array is: ";


echo "<br />";
foreach ($array as $value) {
echo $value . ",";
}
echo "<br />";
echo "<br />";
for($j = 0; $j < count($array); $j ++) {
for($i = 0; $i < count($array)-1; $i ++){

if($array[$i] > $array[$i+1]) {


$temp = $array[$i+1];
$array[$i+1]=$array[$i];
$array[$i]=$temp;
}
}
}
echo "Sorted Array is: ";
echo "<br />";
#print_r($array);
foreach ($array as $value) {
echo $value . ",";
}
?>

2. Write a PHP program to decompose a string into individual elements and store them
in an array.
Use PHP's explode() function to split a string by delimiter and store the separate
segments in a numerically indexed array:
<?php
// define string
$alphabetStr = "a b c d e f g h i j k";
// break string into array
// using whitespace as the separator
// result: ("a","b","c","d","e","f","g","h","i","j","k")
print_r(explode(" ", $alphabetStr));
?>
Programming Exercise 161

3. You want to strip an array of all duplicate elements to obtain a unique set.(Removing
Duplicate Elements in an Array)
<?php
// define an array containing duplicates
$numbers = array(10,20,10,40,35,80,35,50,55,10,55,30,40,70,50,10,35,85,40,90,30);
// extracts all unique elements into a new array
// result: "10, 20, 40, 35, 80, 50, 55, 30, 70, 85, 90"
echo join(", ", array_unique($numbers));
?>

4. Write a PHP program to sort a multidimensional array using multiple keys.


<?php
// create a multidimensional array
$data = array();
$data[0] = array("title" => "Net Force", "author" => "Clancy, Tom",
"rating" => 4);
$data[1] = array("title" => "Every Dead Thing", "author" => "Connolly,
John", "rating"=> 5);
$data[2] = array("title" => "Driven To Extremes", "author" => "Allen,
James", "rating" => 4);
$data[3] = array("title" => "Dark Hollow", "author" => "Connolly,
John", "rating" => 4);
$data[4] = array("title" => "Bombay Ice", "author" => "Forbes,
Leslie", "rating" => 5);
// separate all the elements with the same key
// into individual arrays
foreach ($data as $key=>$value) {
$author[$key] = $value['author'];
$title[$key] = $value['title'];
$rating[$key] = $value['rating'];
}
// sort by rating and then author
array_multisort($rating, $author, $data);
print_r($data);
?>

5. Write a PHP script to protect a publicly-displayed e-mail address from being captured
by an e-mail address harvester.
<?php
// function to protect
// publicly-displayed e-mail addresses
// replace @ with "at"
// . with "dot"
// - with "dash"
// _ with "underscore"
function protectEmail($email) {
// define array of search and replacement terms
$search = array(".", "-", "_", "@");
$replace = array(" dot ", " dash ", " underscore ", " at ");
162 Chapter 5. Introduction to PHP

// perform search and replace operation


return str_replace($search, $replace, $email);
}
// result: "dontap at cst dash a dot acm dot org"
print protectEmail("dontap@csta.acm.org");
?>

Using Cookies
Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying
return users. PHP transparently supports HTTP cookies.
A cookie lets you store a small amount of data within the user ’ s browser itself. Then, whenever
the browser requests a page on your Web site, all the data in the cookie is automatically sent to the
server within the request.This means that you can send the data once to the browser, and the data is
automatically available to your script from that moment onward. A cookie is sent from the server
to the browser as part of the HTTP headers.

Setting Cookies
We can set cookies using the setcookie() function.
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other
headers, cookies must be sent before any output from your script (this is a protocol restriction). This
requires that you place calls to this function prior to any output, including < html > and < head >
tags as well as any whitespace.

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Here is the detail of all the arguments:


• Name - This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
• Value :-This sets the value of the named variable and is the content that you actually want to
store.
• Expiry :- This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After
this time cookie will become inaccessible. If this parameter is not set then cookie will
automatically expire when the Web Browser is closed.
• Path :-This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
• Domain :- This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
• Security :- This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
• httponly :- When TRUE the cookie will be made accessible only through the HTTP protocol.
This means that the cookie won’t be accessible by scripting languages, such as JavaScript. It
has been suggested that this setting can effectively help to reduce identity theft through XSS
attacks (although it is not supported by all browsers), but that claim is often disputed. Added
in PHP 5.2.0. TRUE or FALSE
5.16 Using Cookies 163

Example
<?php
//File name: setcook.php
//Let's say that the correct login is based on these global user and pass values.
//In the real world, this would be taken from the database most likely.
$username="test_uname";
$password="test_pwd";
setcookie ("cookie_user", $username, time()+60*60*24*30);
setcookie ("cookie_pass", $password, time()+60*60*24*30);
header("read_cook.php");
?>

when we execute above script the cookie values are stored internally in the form of arrays as
follows:
Array ( [cookie_user] => test_uname [cookie_pass] => test_pwd)

Reading Cookies
Cookies can indeed be read - and quite easily. By using the $_COOKIE superglobal, you can have
full access to your cookie for reading and writing to it from your script.
The following example demonstrate reading values from cookies. In this example retrive values
of previous example values

Example
<?
//File name: read_cook.php
echo "User name from cookie:".$_COOKIE['cookie_user'];
echo "<br>password from cookie:".$_COOKIE['cookie_pass'];
?>

:::::: OUTPUT ::::::


User name from cookie:test_uname
password from cookie:test_pwd

Deleting Cookies
Removing cookies is also a simple task.
• You should note that cookies will disappear by themselves if you have set them up to do so.
Example is as follows:
setcookie("cookie_user", $value, time()+3600); /* expire in 1 hour */

• Cookies that have not been assigned a time to die will simply be removed when the browser
window closes. Example is as follows:
setcookie("cookie_user", $value);

• a user will want to be able to clear the cookies on a site. When deleting a cookie you should
assure that the expiration date is in the past, to trigger the removal mechanism in your browser.
Examples follow how to delete cookies sent in previous example:
<?php
// set the expiration date to one hour ago
164 Chapter 5. Introduction to PHP

setcookie ("cookie_user", "", time() - 3600);


?>

::::: OUTPUT ::::::


After execution of above script it returns null value.

Using HTTP Headers


HTTP headers are slightly finicky but rather powerful sets of functionality. The most important
aspect to remember about headers is that they can be called only before any output has been written
to the web page. We can use them to control everything, including setting the current page location,
finding out what file format is being displayed, and managing all aspects of the browser cache. In
the following examples, you will learn how to use the header() function in a variety of ways.
Prototype of header() function is as follows:
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

sring: The header string.


replace: The optional replace parameter indicates whether the header should replace a previous
similar header, or add a second header of the same type. By default it will replace, but if you pass
in FALSE as the second argument you can force multiple headers of the same type.
http_response_code: Forces the HTTP response code to the specified value. Note that this
parameter only has an effect if the string is not empty.

Redirecting to a Different Location


One of the more common uses for HTTP headers is redirecting a script. By using headers inside
processing scripts, you can force the browser to return to any page we want.
The following program shows the login page. after successful login header() function forwarded
to home.php page.
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Login</title>
<style>
.error {
font-weight: bold;
color: #FF0000;
}
</style>
</head>
<body>
<div style="width: 500px; text-align: left;">
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="cse"; // Database name
$tbl_name="reg"; // Table name

//Function to determine a valid e-mail address.

//Default to showing the form.


5.17 Using HTTP Headers 165

$goodtogo = false;
//Handle the incoming data.

if ($_SERVER["REQUEST_METHOD"] == "POST"){
//Let's declare a submission value that tells you if you are fine.
$goodtogo = true;

//Validate the name.


try {
if (trim ($_POST['name']) == "" || trim ($_POST['pwd'])==""){
$goodtogo = false;
throw new exception ("Sorry, you must enter your name & Password.<br />");
}
else{
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name where name='".$_POST['name']."' and pwd='".$_POST['pwd']."'";
$result=mysql_query($sql);
if($info = mysql_fetch_array($result)){
$goodtogo = false;

header("Location: home.php"); //this function forward to home.php


}else{
$goodtogo = false;
throw new exception ("Sorry, your User name password not matched.<br />");
}
}
} catch (exception $e) {
?><span class="error"><?php echo $e->getmessage(); ?></span><?php
}
}

if (!$goodtogo){
?>
<form action="<?php $_SERVER["PHP_SELF"];?>" method="post">
<p>Login form:</p>
User Name: <input type="text" name="name" maxlength="150" value="<?
if ($_SERVER["REQUEST_METHOD"] == "POST"){echo $_POST['name'];}?>"/><br /><br />
Password: <input type="password" name="pwd" maxlength="150" value="<?
if ($_SERVER["REQUEST_METHOD"] == "POST"){echo $_POST['pwd'];}?>" /><br />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
<?php
}
?>
</div>
</body>
</html>

home.php
166 Chapter 5. Introduction to PHP

<html>
<head>
<title> heade </title>
</head>
<body>
<form action="">
<h2>
This is the home page after successful login
header function forwarded to this page..
</h2>
</form>
</body>
</html>
:::::::::: OUTPUT ::::::::::
This is the home page after successful login header function forwarded to this page..

The header() function is rather nice in that it will redirect you automatically to the appropriate file
without a single hiccup in the processing. You will simply find yourself at the appropriate page.

Sending Content Types Other Than HTML


The Content-Type header field is used to specify the nature of the data in the body of an entity, by
giving type and subtype identifiers, and by providing auxiliary information that may be required for
certain types. After the type and subtype names, the remainder of the header field is simply a set of
parameters, specified in an attribute/value notation. The set of meaningful parameters differs for
the different types. The ordering of parameters is not significant.
The header function is more than versatile enough to take care of this issue. To make the most
out of this function, you can effectively output other file types by simply declaring the content type you
want to output.

Content Type Application


application/pdf Adobe Portable Document Format (PDF) types
application/msword Microsoft Word documents
application/excel Microsoft Excel documents
image/gif GIF images
image/png PNG images
application/octet-stream Zip files
text/plain Plain text (text files)

Table 5.12: Common File Format Content Types

Forcing File “Save As” Downloads


Because web browsers can output many different file types directly onto the screen, the default
when you use headers to output a wide variety of file types is to make them automatically appear
on the screen. What if you would rather have the file appear as a download, though? You can use
the header()function to force a Save As dialog box to appear for the user to accept a download.
<?php
header("Content-type:application/pdf");
$output=downloaded;
// It will be called downloaded.pdf
5.18 Using Sessions 167

header("Content-Disposition:attachment;filename=".$output.".pdf");

// The PDF source is in original.pdf


readfile("original.pdf");
?>
:::::: OUTPUT ::::::

Figure 5.1: Output of forcing Save As downloads

The key point in this code is showing content-disposition in the header. By making content-
disposition an attachment value, the browser will force a download rather than display the file inline.
By using this, you can force the download to appear with any particular filename you prefer and
also with pretty much any file extension. By using content-type, you force the browser to output a
file of the requested type.

Using Sessions
Because cookies are getting less and less trusted, a means had to be created to allow user authenti-
cation without having to store physical data on a client system. As a solution, sessions came onto
the scene.

session_start() function needs to be called at the beginning of every page where you want
session access. When session_start() is called or when a session auto starts, PHP will call the open
and read session save handlers. This function returns TRUE if a session was successfully started,
otherwise FALSE.
The prototypes for these session-related functions are as follows:
bool session_start ( void )
bool session_destroy ( void )

Setting Sessions
Setting the data in sessions is very easy in php. The session support allows to store data between
requests in the $_SESSION superglobal array. The following example creates a session state, sets a
session:
<?php
session_start();

$_SESSION['uname']="test_user";
$_SESSION['pwd']="test_pwd";
168 Chapter 5. Introduction to PHP

?>
When we are executing the above script internally SESSION store the information
in an associative array as follows:
Array ( [uname] => test_user [pwd] => test_pwd )

Reading Sessions
Reading the values from SESSIONs is also very easy using $_SESSION superglobal variable. The
following example shows the reading and accessing data from SESSIONs.
<?php
session_start();

echo "Username in SESSION is <b>".$_SESSION['uname']."</b><br>";


echo "Password in SESSION is <b>".$_SESSION['pwd']."</b>";

?>
:::::: OUTPUT ::::::
Username in SESSION is test_user
Password in SESSION is test_pwd

Deleting Sessions
In php we are using three functions to deleate or clear SESSION information.
• session_unset()
The session_unset() function frees all session variables currently registered. the prototype is
as follows:
void session_unset ( void )
• session_destroy()
The session_destroy() destroys all of the data associated with the current session. It does not
unset any of the global variables associated with the session, or unset the session cookie. To
use the session variables again, session_start() has to be called. The prototype is as follows:
bool session_destroy ( void )
• unset()
unset() destroys the specified variables. The behavior of unset() inside of a function can vary
depending on what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the local variable is destroyed.
The variable in the calling environment will retain the same value as before unset() was
called. The prototype is as follows:
void unset ( mixed $var [, mixed $... ] )
Example: unset($_SESSION[‘uname’]);
After executing the above statement only uname will be cleared from session.

Storing Simple Data Types in Sessions


Sessions have really been useful only for passing simple data types around. Sessions handle simple
data types, and they handle them well. Like any PHP variable, however, the data type of a current
session is based upon what was last assigned to it and can be changed quite easily. The following
example describes this:
<?php
session_start();
5.18 Using Sessions 169

(int)$_SESSION['inumber']=1024;
(float)$_SESSION['fnumber']=10.23;
(string)$_SESSION['str']="String";

?>
Internally SESSION stores information as follows:
Array ( [inumber] => 1024 [fnumber] => 10.23 [str] => String )

Storing Complex Data Types in Sessions


One of the major improvements to PHP is the ability to store complex data types (arrays and
objects) within a session.

Store & Access Arrays in SESSION


The following example demonstrate how to store arrays in Sessions.

<?php
session_start();

$x=array('uname'=> "Praveen",'pwd'=>"password");
$_SESSION['str']=$x;
?>
Internally session store the data in the form of two-dimentional array as follows:
Array ( [str] => Array ( [uname] => Praveen [pwd] => password ) )

The following example demonstrate accessing the arrays in sessions. When we store arrays in
SESSIONs we are accessing $_SESSION as a two dimentional array.

<?
session_start();
echo "User name:::::::::::".$_SESSION['str']['uname']."<BR>";
echo "Password:::::::::::".$_SESSION['str']['pwd']."<BR>";
/?>
:::::: OUTPUT ::::::
User name:::::::::::Praveen
Password:::::::::::password

Store & Access Objects in SESSION


PHP allows you to store objects within sessions. Using this technique, you can easily store large
quantities of data within a single object, use the functionality within the session for these purposes,
and then pass the data along to other pages.

<?php
session_start();
//A class that does not do too much.
class myclass {
protected $myvalue;
public function setmyvalue ($newvalue){
$this->myvalue = $newvalue;
}
public function getmyvalue (){
return $this->myvalue;
170 Chapter 5. Introduction to PHP

}
}
$_SESSION['myclass_value'] = new myclass ();
//This function exists for the sole purpose of showing how sessions can be called
//from anywhere within the scope of the session state.
function outputsessions (){
$_SESSION['myclass_value']->setmyvalue ("Hello World");
echo $_SESSION['myclass_value']->getmyvalue ();
}
//Then you can call the function from here:
outputsessions();
?>

Difference between cookies & sessions

Cookies Sessions
1. Cookies store data on the Client machine Sessions store data on the server
2. Less secure More Secure than cookies
3. Stores less amount of data Here we store more amount of data
4. It store only primitive datatypes It stores both primitive and Compound
datatypes.
5. More amount of time Data stored in cookies Less time sessions store the data.
6. No need to require additional space to store Sessions need extra space, unlike cookies to
data store data
7. No need to call additional functions Here it need session_start() to create sessions.
8. Setting and deleting use setcookie() For setting session use $_SESSION[] super-
global array, and delete session information
use unset() or session_destroy().
9. Accessing cookie using $_COOKIE[] super- Accessing sessions using $_SESSION[] super-
global array. global array

Authenticating Your Users


PHP uses two predefined variables to authenticate a user.
1. $_SERVER[’PHP_AUTH_USER’]
2. $_SERVER[’PHP_AUTH_PW’]
These two superglobal variables store the Username and password values respectively while
authenticating is as simple as comparing the expected username and password to these variables.
The isset() function determines whether a variable has been assigned a value. the prototype is
as follows:

boolean isset(mixed var[,mixed var[,......]])

It returns TRUE if the variable contains a value and FALSE if it does not.It applied to User authenti-
cation, the isset() function is useful for determining whether the $_SERVER[’PHP_AUTH_USER’]
and $_SERVER[’PHP_AUTH_PW’] variables are properly set.
Using isset() to verify whether a variable contain a value or not.

<?php
if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']){
Using Environment and Configuration Variables 171

header('www-Authenticate: Basic replays="Authentication");


header("HTTP/1.1 401 Unauthorized");
}
else{
echo "User Name is $_SERVER['PHP_AUTH_USER']";
echo "password is $_SERVER['PHP_AUTH_PW']";
}
?>

Using Environment and Configuration Variables


PHP provides a means to use and verify the configuration settings and environment variables
relative to the server space the script is occupying. A common use of the environment variables in
PHP is for dynamic imaging. While Windows systems commonly store their fonts in one folder,
Linux-based systems keep theirs in another. By using PHP’s environment variables to determine
the current operating system, you can make your code slightly more portable.
Using configuration variables can also come in quite handy, particularly with file upload scripts.
The base PHP installation leaves only enough processing time to upload files that are generally
2MB or smaller in size. By manipulating the PHP configuration files temporarily, you can increase
the limit enough to allow a script to process much larger files.

Reading Environment Variables


The $_ENV superglobal is PHP’s method for reading a system’s environment variables and has an
argument set that is based upon the current environment that is available to it. We can retrieve them
using the getenv() function also.

<?php
echo $_ENV['Program Files'] . "<br />"; //Outputs C:\Program Files.
echo getenv("ProgramFiles") . "<br />"; //Outputs C:\Program Files.
echo $_ENV['COMPUTERNAME'] . "<br />"; //Outputs COMPUTER-2339.
echo getenv("COMPUTERNAME") . "<br />"; //Also Outputs COMPUTER-2339.
?>

Reading Configuration Variables


Reading configuration variables, on the other hand, takes place through two functions, ini_get() and
ini_get_all(). The function ini_get() will retrieve the value of a specified configuration variable,
and the function ini_get_all() will retrieve an array filled with the entire selection of configuration
variables that are available.

<?php
echo ini_get ("post_max_size") . "<br />"; //Outputs 8MB.
//And you can output the entire listing with this function.
print_r (ini_get_all());
?>

Setting Environment Variables


Setting environment and configuration variables is just as easy as it is to get them. While working
with environment variables, you merely need to assign a new value to the $_ENV superglobal to
process a temporary change. The change will be in effect for the script’s duration.
172 Chapter 5. Introduction to PHP

<?php
echo $_ENV['COMPUTERNAME'] . "<br />"; // Echoes COMPUTER-2339.
$_ENV['COMPUTERNAME'] = "dp";
echo $_ENV['COMPUTERNAME'] . "<br />"; //Echoes the new COMPUTERNAME.
?>

Setting Configuration Variables


The same applies for configuration variables but with a different approach. To set a configuration
variable, you have to use the PHP function ini_set(), which will allow you to set a configuration
variable for the script’s duration. Once the script finishes executing, the configuration variable will
return to its original state. The prototype for ini_set() is as follows:
string ini_set ( string varname, string newvalue )
<?php
echo ini_get ('post_max_size'); //Echoes 8MB.
//Then you set it to 200M for the duration of the script.
ini_set('post_max_size','200M');
echo ini_get ('post_max_size'); //Echoes 200MB.
//Any files that are to be uploaded in this script will be OK up to 200M.
?>

Working with Date and Time


In the programming world, date and time values formatted in Unix epoch manner.
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds
that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO
8601: 1970-01-01T00:00:00Z). Literally speaking the epoch is Unix time 0 (midnight 1/1/1970),
but ’epoch’ is often used as a synonym for ’Unix time’. Many Unix systems store epoch dates as a
signed 32-bit integer, which might cause problems on January 19, 2038 (known as the Year 2038
problem or Y2038).
The following are some of the date and time functions.

time()
It returns the current system date and time as a Unix timestamp.
<?php
echo time();
?>
:::::: OUTPUT ::::::
1386331271

date()
Returns a string formatted according to the given format string using the given integer timestamp
or the current time if no timestamp is given. The prototype is a s follows:
string date ( string $format [, int $timestamp = time() ] )

The following example demonstrate date() function.


<?php
echo date("r");
5.21 Working with Date and Time 173

echo "<br>".date("d:M:Y:::H:S:I");
?>
:::::: OUTPUT ::::::
Fri, 06 Dec 2013 13:24:49 +0100
06:Dec:2013:::13:49:0

Character Description
F Full name of the month (January, February, and so on).
M Three-letter abbreviation for the month (Jan, Feb, and so on).
m Numeric representation for the month, with leading zero (two digits). n
Numeric representation for the month (no leading zero).
y Two-digit year.
Y Four-digit year.
d Day of the month, with leading zeros (two digits).
j Day of the month (no leading zeros).
D A textual representation of a day, three letters (Mon, Tue, and so on).
w Numeric representation of the day of the week (0 = Sunday, 6 = Saturday).
h Hour in 12-hour format, with leading zero (two digits).
g Hour in 12-hour format (no leading zero).
H Hour in 24-hour format, with leading zero (two digits). G
Hour in 24-hour format (no leading zero).
a am/pm (lowercase).
A AM/PM (uppercase).
i Minute, with leading zero (two digits).
j Minute (no leading zero)
s Second, with leading zero (two digits).
r RFC-2822 format WWW, DD MMM YYYY HH:MM:SS ± HHMM
Table 5.13: Formatting Characters for the date() Function

checkdate()
Checks the validity of the date formed by the arguments. A date is considered valid if each
parameter is properly defined. The prototype is as follows:
bool checkdate ( int $month , int $day , int $year )

Returns TRUE if the date given is valid; otherwise returns FALSE.


<?php
echo checkdate(12, 31, 2000);// Return 1
echo checkdate(2, 29, 2001); //Return 0
?>

mktime()
Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer
containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and
the time specified.
Arguments may be left out in order from right to left; any arguments thus omitted will be set to
the current value according to the local date and time. The prototype is as follows:
174 Chapter 5. Introduction to PHP

int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second =
date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y")
[, int $is_dst = -1 ]]]]]]] )

A simple example is :
<?php
echo mktime(11,00,6,12,6,2012);
?>
:::::: OUTPUT ::::::
1354788006

strtotime()
The function expects to be given a string containing an English date format and will try to parse
that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC),
relative to the timestamp given in now, or the current time if now is not supplied.
Each parameter of this function uses the default time zone unless a time zone is specified in
that parameter. Be careful not to use different time zones in each parameter unless that is intended. The
prototype is as follows:

int strtotime ( string $time [, int $now = time() ] )

Example to demonstrate strtotome()

<?php
echo strtotime("20131206"); // Output: 1386284400
?>

getdate()
Returns an associative array containing the date information of the timestamp, or the current local
time if no timestamp is given.

array getdate ([ int $timestamp = time() ] )

Example programs demonstrate getdate()

<?php
print_r(getdate(time()));
?>
:::::: OUTPUT ::::::
Array ( [seconds] => 36 [minutes] => 4 [hours] => 14 [mday] => 6 [wday] => 5
[mon] => 12 [year] => 2013 [yday] => 339 [weekday] => Friday
[month] => December [0] => 1386335076 )

strptime()
strptime() returns an array with the date parsed, or FALSE on error.

array strptime ( string $date , string $format )


5.22 Programming Exercise 175

Function Description
date_sunrise() Returns time of sunrise for a given day and location (new in PHP 5).
date_sunset() Returns time of sunset for a given day and location (new in PHP 5).
gmdate() Formats a GMT/UTC date/time. Uses the same formatting characters as the
date() function.
gmmktime() Converts a set of GMT date/time values into a Unix timestamp (analogous to
mktime()).

Table 5.14: More PHP 5 Date/Time Functions

Programming Exercise
1. Write a PHP program that works on date & time using functions.

<?php
$b = time ();
print date("m/d/y",$b) . "<br>";
print date("D, F jS",$b) . "<br>";
print date("l, F jS Y",$b) . "<br>";
print date("g:i A",$b) . "<br>";
print date("r",$b) . "<br>";
print date("g:i:s A D, F jS Y",$b) . "<br>";
?>

Exercise
1. Explain the anatomy of a PHP page.
2. How it differs from an html page?
3. What is server side programming?
4. Briefly discuss about any two server side programming languages.
5. What makes PHP a choice among the other scripting languages?
6. Where can we use PHP scripts?
7. What is the impact of programming on web environments? Explain with an example.
8. Explain installation, configure of PHP on Windows.
9. Explain installation, configure of PHP on Linux.
10. Explain different types of operators in PHP with examples.
11. Write a PHP program that removes HTML from the given string.
12. Explain about PHP data types in detail.
13. Write a PHP program that uses all the data types.
14. What is ternary operator? Explain with an example.
15. Write a PHP program that works on date & time using functions.
16. Explain about scope of a variable.
17. What is the use of scope resolution operator? Explain.
18. Explain about operator precedence & associativity.
19. Explain different types of operators in PHP.
20. What is the use of scope resolution operator? Explain.
21. Explain in detail about statements in PHP.
22. Explain how arrays are used in PHP.
23. How functions are declare in PHP? Explain recursive functions in PHP with example.
24. List and Explain different array functions in PHP?
25. Explain different ways to print an array?
176 Chapter 5. Introduction to PHP

26. What is the role of associative arrays in PHP? Explain with examples.
27. How to declare and access the multidimentional arrays in PHP? Explain.
28. How to set a cookie on user computer? Explain with an example.
29. Explain Briefly how to redirect the HTTP headers to different locations.
30. What are cookies? What are the advantages of cookies?
31. Briefly explain different parameters available when setting a cookie.
32. What are Cookies? Explain the following:
33. Setting Cookies.
34. Deleting Cookies.
35. Explain briefly how to use the header() function in different ways.
36. Explain the advantages of the PHP functions available for the time and date.
37. What are cookies? What are the advantages of cookies?
38. Briefly explain different parameters available when setting a cookie.
39. Explain briefly how to redirect the HTTP headers to different locations.
40. Explain briefly how to use the header ( ) function in different ways.
41. Explain why cookies are becoming less trusted.
42. What is a session? Explain briefly about sessions.
43. Explain why cookies are becoming less trusted.
44. Explain briefly how to use the header ( ) function in different ways.
45. What are the advantages and disadvantages of cookies?
46. How to set a cookie on user computer? Explain with an example.
6. XML- eXternal Markup Language

XML stands for Extensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML).

Difference between HTML and XML

SNo. HTML XML


1) HTML is used to display data and fo- XML is a software and hardware inde-
cuses on how data looks. pendent tool used to transport and store
data. It focuses on what data is.
2) HTML is a markup language itself. XML provides a framework to define
markup languages.
3) HTML is not case sensitive. XML is case sensitive.
4) HTML is a presentation language. XML is neither a presentation language
nor a programming language.
5) HTML has its own predefined tags. We can define tags according to your
need.
6) In HTML, it is not necessary to use a XML makes it mandatory to use a clos-
closing tag. ing tag.
7) HTML is static because it is used to XML is dynamic because it is used to
display data. transport data.
8) HTML does not preserve whitespaces. XML preserve whitespaces.

XML tags identify the data and are used to store and organize the data, rather than specifying how
to display it like HTML tags, which are used to display the data. XML is not going to replace
HTML in the near future, but it introduces new possibilities by adopting many successful features
of HTML. There are three important characteristics of XML that make it useful in a variety of
systems and solutions:
• XML is extensible: XML allows you to create your own self-descriptive tags, or language,
that suits your application.
178 Chapter 6. XML- eXternal Markup Language

• XML carries the data, does not present it: XML allows you to store the data irrespective of
how it will be presented.
• XML is a public standard: XML was developed by an organization called the World Wide
Web Consortium (W3C) and is available as an open standard.

XML Usage
A short list of XML usage says it all:
• XML can work behind the scene to simplify the creation of HTML documents for large web
sites.
• XML can be used to exchange the information between organizations and systems.
• XML can be used for offloading and reloading of databases.
• XML can be used to store and arrange the data, which can customize your data handling
needs.
• XML can easily be merged with style sheets to create almost any desired output.
• Virtually, any type of data can be expressed as an XML document.
What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format that is
both human-readable and machine-readable. So what exactly is a markup language? Markup is
information added to a document that enhances its meaning in certain ways, in that it identifies the
parts and how they relate to each other. More specifically, a markup language is a set of symbols
that can be placed in the text of a document to demarcate and label the parts of that document.
Following example shows how XML markup looks, when embedded in a piece of text:

<message>
<text>Hello, world!</text>
</message>

XML Syntax
This chapter takes you through the simple syntax rules to write an XML document. Following is a
complete XML document:

<?xml version="1.0"?>
<contact-info>
<name>Web Technologies</name>
<company>Amazon Kindle</company>
<phone>(040) 123-4567</phone>
</contact-info>

You can notice there are two kinds of information in the above example:
• The markup, like < contact − in f o > and
• The text, or the character data, amazon and (040) 123-4567.

XML Declaration
The XML document can optionally have an XML declaration. It is written as below:

<?xml version="1.0" encoding="UTF-8"?>

Where version is the XML version and encoding specifies the character encoding used in the
document.
XML Syntax 179

Syntax Rules for XML declaration


• The XML declaration is case sensitive and must begin with "<?xml >" where "xml" is
written in lower-case.
• If document contains XML declaration, then it strictly needs to be the first statement of the
XML document.
• The XML declaration strictly needs be the first statement in the XML document.
• An HTTP protocol can override the value of encoding that you put in the XML declaration.

Tags and Elements


An XML file is structured by several XML-elements, also called XML-nodes or XML-tags.
XMLelements’ names are enclosed by triangular brackets<>as shown below:
<element>

Syntax Rules for Tags and Elements


Element Syntax:
Each XML-element needs to be closed either with start or with end elements as shown below:
<element>....</element>
or in simple-cases, just this way:
<element/>

Nesting of elements:
An XML-element can contain multiple XML-elements as its children, but the children elements
must not overlap. i.e., an end tag of an element must have the same name as that of the most recent
unmatched start tag.
Following example shows incorrect nested tags:
<?xml version="1.0"?>
<contact-info>
<company>
Skillsubsist
<contact-info>
</company>
Following example shows correct nested tags:
<?xml version="1.0"?>
<contact-info>
<company>Skillsubsist</company>
<contact-info>

Root element:
An XML document can have only one root element. For example, following is not a correct XML
document, because both the x and y elements occur at the top level without a root element:
<x>...</x>
<y>...</y>
The following example shows a correctly formed XML document:
<root>
<x>...</x>
<y>...</y>
</root>
180 Chapter 6. XML- eXternal Markup Language

Case sensitivity:
The names of XML-elements are case-sensitive. That means the name of the start and the end
elements need to be exactly in the same case. For example
< contact-info > is different from <Contact-Info >.

Attributes
An attribute specifies a single property for the element, using a name/value pair. An XML-element
can have one or more attributes. For example:
<a href="http://www.skillsubsist.in/">Skillsubsist</a>

Here href is the attribute name and http://www.skillsubsist.in/ is attribute value.

Syntax Rules for XML Attributes


• Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are
considered two different XML attributes.
• Same attribute cannot have two values in a syntax. The following example shows incorrect
syntax because the attribute b is specified twice:
<a b="x" c="y" b="z">....</a>

• Attribute names are defined without quotation marks, whereas attribute values must always
appear in quotation marks. Following example demonstrates incorrect xml syntax:
<a b=x>....</a>

• In the above syntax, the attribute value is not defined in quotation marks.
Attributes are part of the XML elements. An element can have multiple unique attributes. Attribute
gives more information about XML elements. To be more precise, they define properties of
elements. An XML attribute is always a name-value pair.

Syntax
An XML attribute has following syntax:
<element-name attribute1 attribute2 >
....content..
< /element-name>

where attribute1 and attribute2 has the following form:


name = "value"

value has to be in double (" ") or single (’ ’) quotes. Here, attribute1 and attribute2 are unique
attribute labels. Attributes are used to add a unique label to an element, place the label in a
category, add a Boolean flag, or otherwise associate it with some string of data. Following example
demonstrates the use of attributes:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE garden [
<!ELEMENT garden (plants)*>
<!ELEMENT plants (#PCDATA)>
<!ATTLIST plants category CDATA #REQUIRED>
XML Document Type Declaration 181

]>
<garden>
<plants category="flowers" />
<plants category="shrubs">
</plants>
</garden>

Attributes are used to distinguish among elements of the same name. When you do not want to
create a new element for every situation. Hence, use of an attribute can add a little more detail in
differentiating two or more similar elements.
In the above example, we have categorized the plants by including attribute category and
assigning different values to each of the elements. Hence we have two categories of plants, one
flowers and other color. Hence we have two plant elements with different attributes. You can also
observe that we have declared this attribute at the beginning of the XML.

6.3.1 Attribute Types


StringType
It takes any literal string as a value. CDATA is a StringType. CDATA is character data. This means,
any string of non-markup characters is a legal part of the attribute.

TokenizedType
This is more constrained type. The validity constraints noted in the grammar are applied after the
attribute value is normalized. The TokenizedType attributes are given as:
• ID : It is used to specify the element as unique.
• IDREF : It is used to reference an ID that has been named for another element.
• IDREFS : It is used to reference all IDs of an element.
• ENTITY : It indicates that the attribute will represent an external entity in the document.
• ENTITIES : It indicates that the attribute will represent external entities in the document.
• NMTOKEN : It is similar to CDATA with restrictions on what data can be part of the
attribute.
• NMTOKENS : It is similar to CDATA with restrictions on what data can be part of the
attribute.

EnumeratedType
This has a list of predefined values in its declaration. out of which, it must assign one value. There
are two types of enumerated attribute:
• NotationType : It declares that an element will be referenced to a NOTATION declared
somewhere else in the XML document.
• Enumeration : Enumeration allows you to define a specific list of values that the attribute
value must match.

XML Document Type Declaration


The XML Document Type Declaration, commonly known as DTD, is a way to describe XML
language precisely. DTDs check vocabulary and validity of the structure of XML documents against
grammatical rules of appropriate XML language.
An XML DTD can be either specified inside the document, or it can be kept in a separate
document and then liked separately.
182 Chapter 6. XML- eXternal Markup Language

Syntax
Basic syntax of a DTD is as follows:
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>

In the above syntax,


The DTD starts with <!DOCTYPE delimiter.
An element tells the parser to parse the document from the specified root element.
DTD identifier is an identifier for the document type definition, which may be the path to a file
on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called
External Subset.
The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.

Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To refer
it as internal DTD, standalone attribute in XML declaration must be set to yes. This means, the
declaration works independent of external source.

Syntax
The syntax of internal DTD is as shown:
<!DOCTYPE root-element [element-declarations]>

where root-element is the name of root element and element-declarations is where you declare the
elements.

Example
Following is a simple example of internal DTD:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

Let us go through the above code:


Start Declaration- Begin the XML declaration with following statement
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

DTD- Immediately after the XML header, the document type declaration follows, commonly
referred to as the DOCTYPE:
XML Document Type Declaration 183

<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The
DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body- The DOCTYPE declaration is followed by body of the DTD, where you declare
elements, attributes, entities, and notations:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>
Several elements are declared here that make up the vocabulary of the < name > document. <
!ELEMENT name(PCDATA) > defines the element name to be of type "PCDATA"’:Here PCDATA
means parse-able text data.
End Declaration - Finally, the declaration section of the DTD is closed using a closing bracket
and a closing angle bracket (]>). This effectively ends the definition, and thereafter, the XML
document follows immediately.

Rules
• The document type declaration must appear at the start of the document (preceded only by
the XML header)— it is not permitted anywhere else within the document.
• Similar to the DOCTYPE declaration, the element declarations must start with an exclamation
mark.
• The Name in the document type declaration must match the element type of the root element.

External DTD
In external DTD elements are declared outside the XML file. They are accessed by specifying the
system attributes which may be either the legal .dtd file or a valid URL. To refer it as external DTD,
standalone attribute in the XML declaration must be set as no. This means, declaration includes
information from the external source.

Syntax
Following is the syntax for external DTD:
<!DOCTYPE root-element SYSTEM "file-name">
where file-name is the file with .dtd extension.

Example
The following example shows external DTD usage:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
The content of the DTD file address.dtd are as shown:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
184 Chapter 6. XML- eXternal Markup Language

Types
You can refer to an external DTD by using either system identifiers or public identifiers.

System Identifiers
A system identifier enables you to specify the location of an external file containing DTD declara-
tions. Syntax is as follows:

<!DOCTYPE name SYSTEM "address.dtd" [...]>

As you can see, it contains keyword SYSTEM and a URI reference pointing to the location of the
document.

Public Identifiers
Public identifiers provide a mechanism to locate DTD resources and are written as below:

<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">

As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public
identifiers are used to identify an entry in a catalog. Public identifiers can follow any format,
however, a commonly used format is called Formal Public Identifiers, or FPIs.

XML-Schemas
XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and
validate the structure and the content of XML data. XML schema defines the elements, attributes
and data types. Schema element supports Namespaces. It is similar to a database schema that
describes the data in a database.

Syntax
You need to declare a schema in your XML document as follows:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

Example
The following example shows how to use schema:

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="contact">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

The basic idea behind XML Schemas is that they describe the legitimate format that an XML
document can take.
6.5 XML-Schemas 185

Elements
As we saw in the XML - Elements chapter, elements are the building blocks of XML document. An
element can be defined within an XSD as follows:
<xs:element name="x" type="y"/>

Definition Types
You can define XML schema elements in following ways:

Simple Type
- Simple type element is used only in the context of the text. Some of predefined simple types are:
xs:integer, xs:boolean, xs:string, xs:date. For example:
<xs:element name="phone_number" type="xs:int" />

Complex Type
- A complex type is a container for other element definitions. This allows you to specify which
child elements an element can contain and to provide some structure within your XML documents.
For example:
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

In the above example, Address element consists of child elements. This is a container for other
< xs : element > definitions, that allows to build a simple hierarchy of elements in the XML
document.

Global Types
- With global type, you can define a single type in your document, which can be used by all other
references. For example, suppose you want to generalize the person and company for different
addresses of the company. In such case, you can define a general type as below:
<xs:element name="AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>

Now let us use this type in our example as below:


<xs:element name="Address1">
<xs:complexType>
<xs:sequence>
186 Chapter 6. XML- eXternal Markup Language

<xs:element name="address" type="AddressType" />


<xs:element name="phone1" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Address2">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone2" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

Instead of having to define the name and the company twice (once for Address1 and once for
Address2), we now have a single definition. This makes maintenance simpler, i.e., if you decide to
add "Postcode" elements to the address, you need to add them at just one place.

Attributes
Attributes in XSD provide extra information within an element. Attributes have name and type
property as shown below:

<xs:attribute name="x" type="y"/>

Document Object Model


The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy
of informational units called nodes; DOM is a way of describing those nodes and the relationships
between them.
A DOM Document is a collection of nodes or pieces of information organized in a hierarchy.
This hierarchy allows a developer to navigate through the tree looking for specific information.
Because it is based on a hierarchy of information, the DOM is said to be tree based.
The XML DOM, on the other hand, also provides an API that allows a developer to add, edit,
move, or remove nodes in the tree at any point in order to create an application.

Example
The following example (sample.htm) parses an XML document ("address.xml") into an XML DOM
object and then extracts some information from it with JavaScript:

<!DOCTYPE html>
<html>
<body>
<h1> DOM example </h1>
<div>
<b>Name:</b> <span id="name"></span><br>
<b>Company:</b> <span id="company"></span><br>
<b>Phone:</b> <span id="phone"></span>
</div>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
XML - Parsers 187

xmlhttp = new XMLHttpRequest();


}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/xml/address.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("company").innerHTML=
xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;
document.getElementById("phone").innerHTML=
xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
</script>
</body>
</html>

Contents of address.xml are as below:


<?xml version="1.0"?>
<contact-info>
<name>XML</name>
<company>Skill subsist</company>
<phone>(011) 123-4567</phone>
</contact-info>

Now let us keep these two files sample.htm and address.xml in the same directory /xml and execute
the sample.htm file by opening it in any browser. This should produce an output as shown below:
Name: XML
Company: Skill subsist
phone: (040) 123-4567

Here, you can see how each of the child nodes is extracted to display their values.

XML - Parsers
XML parser is a software library or a package that provides interface for client applications to work
with XML documents. It checks for proper format of the XML document and may also validate the
XML documents. Modern day browsers have built-in XML parsers.

Following diagram shows how XML parser interacts with XML document:
• The goal of a parser is to transform XML into a readable code.
• To ease the process of parsing, some commercial products are available that facilitate the
breakdown of XML document and yield more reliable results.

Some commonly used parsers are listed below:


• MSXML (Microsoft Core XML Services) : This is a standard set of XML tools from
Microsoft that includes a parser.
• System.Xml.XmlDocument : This class is part of .NET library, which contains a number
of different classes related to working with XML.
188 Chapter 6. XML- eXternal Markup Language

Figure 6.1: XML- Parser Output

• Java built-in parser : The Java library has its own parser. The library is designed such that
you can replace the built-in parser with an external implementation such as Xerces from
Apache or Saxon.
• Saxon : Saxon offers tools for parsing, transforming, and querying XML.
• Xerces : Xerces is implemented in Java and is developed by the famous open source Apache
Software Foundation.

Extensible Stylesheet Language (XSL)


XSL is a language for expressing stylesheets
• support for browsing, printing, and aural rendering
• formatting highly structured documents (XML)
• performing complex publishing tasks: tables of contents, indexes, reports,...
• addressing accessibility and internationalization issues
• written in XML

Figure 6.2: XSL Architecture

Components
XSL is constituted of three main components:
• XSLT: a transformation language
• XPath: an expression language for addressing parts of XML documents
6.8 Extensible Stylesheet Language (XSL) 189

Figure 6.3: XSL Transformations

• FO: a vocabulary of formatting objects with their associated formatting properties


XSL uses XSLT which uses XPath

6.8.1 XSL Transformations


XSLT - Basic Principle
Patterns and Templates
• A style sheets describes transformation rules
• A transformation rule: a pattern + a template
• Pattern: a configuration in the source tree
• Template: a structure to be instantiated in the result tree
• When a pattern is matched in the source tree, the corresponding pattern is generated in the
result tree
An Example: Transformation

<xsl:template match="Title">
<H1>
<xsl:apply-templates/>
</H1>
</xsl:template>

Input : < Title >Introduction< /Title >


Output : < H1 >Introduction< /H1 >

An Example: Formatting

<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
result-ns="fo">
<xsl:template match="/">
190 Chapter 6. XML- eXternal Markup Language

<fo:page-sequence font-family="serif">
<xsl:apply-templates/>
</fo:page-sequence>
</xsl:template>
<xsl:template match="para">
<fo:block font-size="10pt" space-before="12pt">
<xsl:apply-templates/>
</fo:block>
</xsl:template>
</xsl:stylesheet>

XPath: XML Path Language


An elementary XPath expression contains
• an axis, which specifies the tree relationship: child, descendants, ancestors, siblings, at-
tributes,...
• a node test, which specifies the node type
• predicates, to further refine the set of nodes selected
Example: all para children that have a type attribute with value warning

child::para[attribute::type="warning"]

XSL Usage
• Format XML documents by generating FOs
• Generate HTML or XHTML pages from XML data/documents
• Transform XML documents into other XML documents
• Generate some textual representation of an XML document
• ...and more
XSL may be used server-side or client-side, but is not intended to send FOs over the wire

Implementation
XSL software include:
• XSLT transformation engines: 4XSLT, IE5, iXSLT, LotusXSL, Transformiix, Resin, Sablotron,
Saxon, Xalan, XML Parser (Oracle), XT
• FO formatters: FOP, FO2PDF, InDelv browser, Passive TeX, REXP
• XSL stylesheet editors
• Style sheets and transformation sheets

News Feed
What’s in a feed?
A feed contains a list of items or entries, each of which is identified by a link. Each item can have any
amount of other metadata associated with it as well.
The most basic metadata for an entry includes a title for the link and a description of it; when
syndicating news headlines, these fields might be used for the story title and the first paragraph or a
summary, for example. For example, a simple entry might look like:

<title>Earth Invaded</title>
<link>http://news.example.com/2004/12/17/invasion</link>
<description>The earth was attacked by an invasion fleet
from halfway across the galaxy; luckily, a fatal
6.9 News Feed 191

miscalculation of scale resulted in the entire armada


being eaten by a small dog.
</description>

Additionally, the feed itself can have metadata associated with it, so that it can be given a title ,
description, and other fields like publisher and copyright terms.
The popular news feeds are RSS and ATOM.

RSS-(Really Simple Syndication)


RSS(Really Simple Syndication) is a family of web feed formats used to publish frequently updated
works—such as blog entries, news headlines, audio, and video—in a standardized format.English:
This icon, known as the "feed ic...
An RSS document which is called a "feed", "news feed", or "channel"’includes full or summa-
rized text, plus metadata such as publishing dates and authorship.RSS feeds benefit publishers by
letting them syndicate content automatically.

Example:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>RSS Title</title>
<description>This is an example of an RSS feed</description>
<link>http://www.someexamplerssdomain.com/main.html</link>;
<lastBuildDate>Mon, 06 Sep 2010 00:01:00 +0000 </lastBuildDate>
<pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
<ttl>1800</ttl>
<item>
<title>Example entry</title>
<description>Here is some text containing an interesting description.</description>
<link>http://www.wikipedia.org/</link>;
<guid>unique string per item</guid>
<pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
</item>
</channel>
</rss>

ATOM
The advent of the ATOM syndication standard was a response to the design flaws of the RSS
standard. The primary advantage of the ATOM is its adaptation as the IETF standard.
The Atom Syndication Format is an XML language used for web feeds, while the Atom
Publishing Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and updating
web resources. ATOM code has been built from the ground with modularity in mind. Therefore, a
great majority of its code is reusable even with other XML vocabularies like RSS.

Example
<?xml version="1.0" encoding="utf-8"?>

<feed xmlns="http://www.w3.org/2005/Atom">

<title>Example Feed</title>
192 Chapter 6. XML- eXternal Markup Language

<subtitle>A subtitle.</subtitle>
<link href="http://example.org/feed/" rel="self" />
<link href="http://example.org/" />
<id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id>
<updated>2003-12-13T18:30:02Z</updated>

<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://example.org/2003/12/13/atom03" />
<link rel="alternate" type="text/html" href="http://example.org/2003/12/13/
<link rel="edit" href="http://example.org/2003/12/13/atom03/edit"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
<author>
<name>John Doe</name>
<email>johndoe@example.com</email>
</author>
</entry></feed>

RSS vs ATOM
Comparing RSS and ATOM.

RSS ATOM
Definition Real Simple Syndication (RSS) is a Atom refers to a pair of standards for
family of web feeds formats that are web feeds.
used to publish frequently updated
works.
Content model RSS 2.0 may contain either plain Atom offers a variety of payload
text or escaped HTML as a payload. types including plain text, escaped
HTML, XHTML, XML, Base64-
encoded binary, and references to
external content such as documents,
video, audio streams, and so forth.
Date formats RSS shows the date timestamps of Atom shows the date timestamp
data when the feed was created and when the website was last updated.
last updated.
Internationalization RSS vocabulary has a mechanism to Atom uses the standard xml:lang at-
indicate a human language for the tribute. Atom also supports charac-
feed. ters outside the US ASCII character
set.
Modularity RSS vocabulary elements are unus- Atom allows the reuse of elements
able in other XML vocabularies. outside the context of an Atom feed
document.
Publishing proto- RSS has two main publishing proto- Atom has one standardized protocol.
cols cols; Blogger protocol and MetaWe-
blog.
Required content RSS has a more loose approach and Atom is more restrictive require
on a feed does not require much data. more data.
6.10 Exercise 193

Distinction be- RSS does not distinguish a partial Atom distinguishes a partial from an
tween partial and from an excerpt. excerpt.
excerpts
Autodiscovery Not a standardized feature. A standardized feature.
Aggregating and ex- RSS has a more complicated aggre- Atom has an easier aggregating and
tracting gating and extracting process. extracting process.

Exercise
1. Differentiate HTML and XML.
2. Explain in detail about XML- DTDs.
3. Explain in detail about XML Schemas with valid examples
4. Explain in detail about XML parsing
5. Explain XSL with examples.
6. What is the importance of News feed? Explain.
7. Differentiate RSS and ATOM.
7. Creating and Using Forms

Understanding Common Form Issues, GET vs. POST, Validating form input, Working with multiple
forms, and Preventing Multiple Submissions of a form. Basic Database Concepts, Connecting to a
MYSQL database, Retrieving and Displaying results, Modifying, Updating and Deleting data.
MVC architecture.

*********************

To create a fully functional web application, you need to be able to interact with your users. The
common way to receive information from web users is through a form. Web forms are merely
Hypertext Markup Language (HTML) elements. PHP 5 is built so that it seamlessly integrates
with form elements. Over the past few versions of PHP, its methodology for dealing with form
information has gradually evolved and is now quite robust.

Understanding Common Form Issues


When dealing with forms, the most important aspect to remember is that you are limited to a certain
variety of fields that can be applied to a form. The fields that have been created are non-negotiable
and work in only the way they were created to work. The < f orm > element bundles together all
the form widgets (also known as controls or fields).
A well-designed form, divides itself into logical chunks using the < f ieldset > element. Each
chunk gets a title, courtesy of the < legend > element.

The following Example demonstrate the forms


registration.html
<html>
<head>
<title>Registration form</title>
</head>
<body>
196 Chapter 7. Creating and Using Forms

Element Description
TEXT INPUT A simple text box
PASSWORD INPUT A text box that hides the characters inputted
HIDDEN INPUT A field that does not show on the form but can contain data
SELECT A drop-down box with options
LIST A select box that can have multiple options selected
CHECKBOX A box that can be checked
RADIO A radio button that can act as a choice
TEXTAREA A larger box that can contain paragraph-style entries
FILE An element that allows you to browse your computer for a file
SUBMIT A button that will submit the form
RESET A button that will reset the form to its original state

Table 7.1: HTML Form Elements

<h1>Registration Form</h1>
<form name='registration' method='' action=''>
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name :<em>*</em></label>
<input type='text' name='name' placeholder="Name As Per SSC"><br>
<label for="fname">Father Name<em>*</em></label>
<input type='text' name='fname' placeholder="Name As Per SSC" required;><br>
<label for="gender">Gender</label>
<select id="gender">
<option value="female">Female</option>
<option value="male">Male</option>
</select><br>
<label for="age">Age<em>*</em></label>
<input id="age" type="number" min="0" max="120"><br>
</fieldset>

<fieldset>
<legend>Contact Details</legend>
<label for="telephone">Telephone</label>
<input id="telephone"><br>
<label for="email">Email <em>*</em></label>
<input type='text' id="email"><br>
</fieldset>

<fieldset>
<legend>Pick Your Favorite Animals</legend>
<label for="zebra"><input id="zebra" type="checkbox"> Zebra</label>
<label for="cat"><input id="cat" type="checkbox"> Cat</label>
<label for="anaconda"><input id="anaconda" type="checkbox"> Anaconda
</label>
<label for="human"><input id="human" type="checkbox"> Human</label><br>
<label for="elephant"><input id="elephant" type="checkbox"> Elephant
</label>
7.1 Understanding Common Form Issues 197

<label for="wildebeest"><input id="wildebeest" type="checkbox">


Wildebeest</label>
<label for="pigeon"><input id="pigeon" type="checkbox"> Pigeon</label>
<label for="crab"><input id="crab" type="checkbox"> Crab</label>
</fieldset>
<p><input type="submit" value="Submit Application"></p>
</form>
</body>
</html>

GET vs. POST


The two ways available to a web developer that the information entered into the form is transmitted
to its destination by using method. the two methods are GET and POST.

GET
When sending data using the GET method, all fields are appended to the Uniform Resource Locator
(URL) of the browser and sent along with the address as data.
Sending data using the GET method means that fields are generally capped at 150 characters,
which is certainly not the most effective means of passing information. It is also not a secure means
of passing data, because many people know how to send information to a script using an address
bar.
PHP’s current methods for dealing with GET variable is the $_GET superglobal. Syntax is
$_GET[’Variable Name’];.

The following Example demonstrate the working of the GET method


File Name: get.php

<html>
<head>
<title>Example for get</title>
</head>
<body>
<form action="get-demo.php" method="GET">
<p>GET Example:</p>
<input type="hidden" name="submitted" value="yes" />
User Name: <input type="text" name="uname" maxlength="150" /><br /><br />
Password: <input type="password" name="pwd" maxlength="150" /><br />
<input type="submit" value="Submit with GET" style="margin-top: 10px;" />
</form>
</body>
</html>

Figure 7.1: Output of get.php

File Name: get-demo.php


198 Chapter 7. Creating and Using Forms

<html>
<head>
<title>Example for GET</title>
</head>
<body>
<?php
if ($_GET['submitted'] == "yes"){
if (trim ($_GET['uname']) != "" && trim ($_GET['pwd']) != ""){
echo "Your User Name (with GET): " . $_GET['uname'];
echo "<br>Your password (with GET) : ". $_GET['pwd'];
} else {
echo "You must submit a value.";
}
?><br /><a href="get.php">Try Again</a><?php
}
?>
</body>
</html>

Figure 7.2: Output aftersubmit get.php (see the addressbar)

when using the GET method, hitting the Refresh button after submitting data the browser will
automatically send the data again.

POST
When sending data using the POST method, values are sent as standard input (the data will be
sended through body not in URL).
Sending data using the POST method is quite a bit more secure (because the method cannot be
altered by appending information to the address bar) and can contain as much information as you
choose to send. Therefore, whenever possible, use the POST method for sending information and
then adjust your script to handle it.
PHP ’s current methods for dealing with POST variable is the $_POST superglobal. Syntax is
$_POST[’Variable Name’];.

The following Example demonstrate the working of the POST method


File Name: post.php

<html>
<head>
7.1 Understanding Common Form Issues 199

<title>Example for POST</title>


</head>
<body>
<form action="post-demo.php" method="post">
<p>POST Example:</p>
<input type="hidden" name="submitted" value="yes" />
User Name: <input type="text" name="uname" maxlength="150" /><br /><br />
Password: <input type="password" name="pwd" maxlength="150" /><br />
<input type="submit" value="Submit with POST" style="margin-top: 10px;" />
</form>
</body>
</html>

Figure 7.3: Output of post.php

File Name: post-demo.php


<html>
<head>
<title>Example for POST</title>
</head>
<body>
<?php
if ($_POST['submitted'] == "yes"){
if (trim ($_POST['uname']) != "" && trim ($_POST['pwd']) != ""){
echo "Your User Name (with POST): " . $_POST['uname'];
echo "<br> Your password(with POST) :". $_POST['pwd'] ;
} else {
echo "You must submit a value.";
}
?><br /><a href="post.php">Try Again</a><?php
}
?>
</body>
</html>

Hitting the Refresh button after submitting data using the POST form, the browser will ask you
if you want to resubmit the data that was passed to it previously. If you want to resend the data, you
must select Yes(Resend) to this option.

GET Vs POST
The following are the key Difference and Comparisons between GET and POST methods.

Validating form input


validation —a way to catch mistakes when they happen (or even better, to prevent them from
happening at all).
200 Chapter 7. Creating and Using Forms

Figure 7.4: After submit the post.php (see addressbar)

Figure 7.5: Refresh after submitting the form it asks above msg

GET POST
1 Parameters remain in browser history because Parameters are not saved in browser history.
they are part of the URL.
2 Can be bookmarked. Can not be bookmarked.
3 GET requests are re-executed but may not be re- The browser usually alerts the user that data will
submitted to server if the HTML is stored in the need to be re-submitted.
browser cache.
4 Easier to hack for script kiddies More difficult to hack
5 Only ASCII characters allowed. No restrictions. Binary data is also allowed.
6 GET is less secure compared to POST because POST is a little safer than GET because the pa-
data sent is part of the URL. So it’s saved in rameters are not stored in browser history or in
browser history and server logs in plaintext. web server logs.
7 Restrictions on form data length No restrictions on form length.
8 GET method should not be used when sending POST method used when sending passwords or
passwords or other sensitive information. other sensitive information.
7.1 Understanding Common Form Issues 201

Client-side validation: These are the checks that happen in the browser, before a form is
submitted. The goal here is to make life easier for the people filling out the form.
Examples: HTML5, JavaScript etc.,
Server-side validation: These are the checks that happen after a form is sent back to the web
server. At this point, it’s up to your server-side code to review the details and make sure everything
is kosher before continuing. No matter what the browser does, serverside validation is essential.

The following example shows a few examples of form validation using PHP.
<html>
<head>
<title>
Validatrion DEMO
</title>

<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
if($_POST["uname"]==""){
echo "<font color=red>Please Enter valid User name</font><br>";
}
else if(strlen($_POST["uname"])<6){
echo "<font color=red>Please Enter valid User name with more than 6 chatrecters<br></font>"
}

if($_POST["pwd"]==""){
echo "<font color=red>Please Enter valid Password</font><br>";
}
else if(strlen($_POST["pwd"])<6){
echo "<font color=red>Please Enter valid Password with more than 6 chatrecters<br></font>";
}

}
?>
</head>
<body>
<form method=POST action="<?$_SERVER['PHP_SELF']?>" >
<table>
<tr><td>NAME:</td>
<td><input type=text name="uname" /></td>
</tr>

<tr><td>PASSWORD:</td>
<td><input type=password name="pwd" /></td>
</tr>

<tr><td></td>
<td><input type=hidden name="type" value="Admin" /></td>
</tr>
<tr><td><input type=reset value=CLEAR /></td>
<td><input type=submit value=NEXT /></td>
</tr>
202 Chapter 7. Creating and Using Forms

</table>
</form>

<?php

if($_SERVER["REQUEST_METHOD"]=="POST"){

if($_POST["uname"]!="" && strlen($_POST["uname"])>=6 && $_POST["pwd"]!=""


&& strlen($_POST["pwd"])>=6){

echo "Name:<font color=green>".$_POST['uname']."<br></font>";


echo "Password: <font color=green>".$_POST['pwd']."<br></font>";
}
}
?>
</body>
</html>

Figure 7.6: Output of validation.php after submitting empty values

In the above script:


$_SERVER[“PHP_SELF”] The filename of the currently executing script, relative to the
document root.
The above program demonstrates the validation in same page. It is possible to perform the
validations using GET and POST methods into the other pages.

Working with multiple forms


Sometimes you will need to collect values from more than one page. Most developers do this for the
sake of clarity. By providing forms on more than one page, you can separate blocks of information
and thus create an ergonomic experience for the user. The problem, therefore, is how to GET values
from each page onto the next page and finally to the processing script. Being the great developer
that you are, you can solve this problem and use the hidden input form type. When each page loads,
you merely load the values from the previous pages into hidden form elements and submit them.
page1.php

<html>
<head>
<title>Personal information</title>
</head>
<body>
7.1 Understanding Common Form Issues 203

<form method=POST action="page2.php">


<table align=center>
<tr>
<td>NAME</td><td><input type="text" name="name"></td>
</tr><tr>
<td>FATHER NAME</td><td><input type="text" name="fname"></td>
</tr><tr>
<td>MOTHER NAME</td><td><input type="text" name="mname"></td>
</tr><tr>
<td>GENDER</td><td>
<input type="radio" name="gen" Value="MALE">MALE
<input type="radio" name=gen value=Female>FEMALE</td>
</tr><tr>
<td><input type=reset value=clear></td>
<td><input type="submit" value="NEXT>>"></td>
</tr>
</form>
</body>
</html>

Figure 7.7: Output of page1.php

page2.php
<html>
<head>
<title>Contact information</title>
</head>
<body>
<form method=POST action="page3.php">
<table align=center>
<tr>
<td>E-Mail</td><td><input type="text" name="email"></td>
</tr><tr>
<td>Mobile</td><td><input type="text" name="Mobile"></td>
</tr><tr>
<td>ADDRESS</td><td><textarea name=address></textarea></td>
</tr>
<input type=hidden name="name" value="<?echo $_POST["name"];?>" />
<input type=hidden name="fname" value="<?echo $_POST["fname"];?>" />
<input type=hidden name="mname" value="<?echo $_POST["mname"];?>" />
<input type=hidden name="gen" value="<?echo $_POST["gen"];?>" />
<tr>
204 Chapter 7. Creating and Using Forms

<td><input type=reset value=clear></td>


<td><input type="submit" value="NEXT>>"></td>
</tr>
</table>
</form>
</body>
</html>

Figure 7.8: Output of page2.php

page3.php
<html>
<head>
<title>Educational Details</title>
</head>
<body>
<form method=POST action="page4.php">
<table align=center>
<tr>
<td>SSC Percentage</td><td><input type="text" name="ssc"></td>
</tr><tr>
<td>Intermediate/10+2</td><td><input type="text" name="inter"></td>
</tr><tr>
<td>UG </td><td><input type=text name=ug></td>
</tr>
<input type=hidden name="name" value="<?echo $_POST["name"];?>" />
<input type=hidden name="fname" value="<?echo $_POST["fname"];?>" />
<input type=hidden name="mname" value="<?echo $_POST["mname"];?>" />
<input type=hidden name="gen" value="<?echo $_POST["gen"];?>" />
<input type=hidden name="email" value="<?echo $_POST["email"];?>" />
<input type=hidden name="Mobile" value="<?echo $_POST["Mobile"];?>" />
<input type=hidden name="address" value="<?echo $_POST["address"];?>" />
<tr>
<td><input type=reset value=clear></td>
<td><input type="submit" value="NEXT>>"></td>
</tr>
</table>
</form>
</body>
</html>

page4.php
7.1 Understanding Common Form Issues 205

Figure 7.9: Output of page3.php

<html>
<head>
<title>Complete Information</title>
</head>
<body>

<table align=center width=40%>


<tr>
<td colspan=2><h5>Personal Details</h5></td>
</tr><tr>
<td>NAME</td><td><?echo $_POST["name"];?></td>
</tr><tr>
<td>FATHER NAME</td><td><?echo $_POST["fname"];?></td>
</tr><tr>
<td>MOTHER NAME</td><td><?echo $_POST["mname"];?></td>
</tr><tr>
<td>GENDER</td><td><?echo $_POST["gen"];?></td>
</tr><tr>
<td colspan=2><h5>Contact details</h5></td>
</tr><tr>
<td>E-Mail</td><td><?echo $_POST["email"];?></td>
</tr><tr>
<td>Mobile</td><td><?echo $_POST["Mobile"];?></td>
</tr><tr>
<td>ADDRESS</td><td><?echo $_POST["address"];?></td>
</tr><tr>
<td colspan=2><h5>Educational details</h5></td>
</tr><tr>
<td>SSC Percentage</td><td><?echo $_POST["ssc"];?></td>
</tr><tr>
<td>Intermediate/10+2</td><td><?echo $_POST["inter"];?></td>
</tr><tr>
<td>UG </td><td><?echo $_POST["ug"];?></td>
</tr>
</table>
</form>
</body>
</html>

As you can see, by passing the values in the hidden form fields, you can continue to collect
information.
206 Chapter 7. Creating and Using Forms

Figure 7.10: Output of page4.php

Redisplaying Forms with Preserved Information and Error Messages


When receiving information submitted from a user, the information may not be submitted in the
format you need. To ensure that users do not GET frustrated, it is important to inform them of what
they did wrong and clearly tell them how to fix the problem. It is also bad practice to force users
to completely rewrite all the proper information they may have already submitted on the form. If
users are forced to do redundant work, they may become irritated and potentially disregard your
service altogether. Therefore, to keep users happy, it is important to validate properly and clearly
while keeping matters as simple for them as possible.

Example:
<html>
<head>
<title>
Validatrion DEMO
</title>

<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
if($_POST["uname"]==""){
echo "<font color=red>Please Enter valid User name</font><br>";
}
else if(strlen($_POST["uname"])<6){
echo "<font color=red>Please Enter valid User name with more than 6 chatrecters<br></font>"
}

if($_POST["pwd"]==""){
echo "<font color=red>Please Enter valid Password</font><br>";
}
else if(strlen($_POST["pwd"])<6){
echo "<font color=red>Please Enter valid Password with more than 6 chatrecters<br></font>";
}
Understanding Common Form Issues 207

}
?>
</head>
<body>
<form method=POST action="<?$_SERVER['PHP_SELF']?>" >
<table>
<tr><td>NAME:</td>
<td><input type=text name="uname" value="<?if($_SERVER["REQUEST_METHOD"]=="POST")
{echo $_POST['uname'];}?>"/></td>
</tr>

<tr><td>PASSWORD:</td>
<td><input type=password name="pwd" value="<?if($_SERVER["REQUEST_METHOD"]=="POST")
{echo $_POST['pwd'];}?>" /></td>
</tr>

<tr><td></td>
<td><input type=hidden name="type" value="Admin" /></td>
</tr>
<tr><td><input type=reset value=CLEAR /></td>
<td><input type=submit value=NEXT /></td>
</tr>

</table>
</form>

<?php

if($_SERVER["REQUEST_METHOD"]=="POST"){

if($_POST["uname"]!="" && strlen($_POST["uname"])>=6 && $_POST["pwd"]!="" &&


strlen($_POST["pwd"])>=6){
echo "Name:<font color=green>".$_POST['uname']."<br></font>";
echo "Password: <font color=green>".$_POST['pwd']."<br></font>";
}

}
?>
</body>
</html>

Figure 7.11: Name with lessthan 6 characters and with out password
208 Chapter 7. Creating and Using Forms

Figure 7.12: With out password and with name

Figure 7.13: With valid inputs ..

Global & Superglobal variables


GLOBAL
$GLOBALS — References all variables available in global scope An associative array containing
references to all variables which are currently defined in the global scope of the script. The variable
names are the keys of the array.
Example:

<?php
function test() {
$foo = "local content";

echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";


echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Global content";


test();
?>
OUTPUT:
$foo in global scope: Global content
$foo in current scope: local content

Superglobal variables
Superglobals — Superglobals are built-in variables that are always available in all scope. Several
predefined variables in PHP are "superglobals", which means they are available in all scopes
throughout a script. Superglobals were introduced to PHP 4.1. There is no need to do global
$variable; to access them within functions or methods. These superglobal variables are:
The $_SERVER superglobal contains information created by the web server—details regarding the
server and client configuration and the current request environment.
Examples:
• $_SERVER[’HTTP_REFERER’]: The URL of the page that referred the user to the current
location.
Preventing Multiple Submissions of a Form 209

• $_SERVER[’REMOTE_ADDR’]: The client’s IP address.


• The $_GET superglobal contains information pertinent to any parameters passed using the
GET method.
• The $_POST superglobal contains information pertinent to any parameters passed using the
POST method.
• The $_COOKIE superglobal stores information passed into the script through HTTP cookies.
Such cookies are typically set by a previously executed PHP script through the PHP function
setcookie().
Example: Write any script in this chapter(eg: validation/Working with multiple forms etc).

Preventing Multiple Submissions of a Form


One possible occurrence that happens often is that users become impatient when waiting for your
script to do what it is doing, and hence they click the submit button on a form repeatedly. This can
wreak havoc on your script because, while the user may not see anything happening, your script is
probably going ahead with whatever it has been programmed to do.
Of particular danger are credit card number submittals. If a user continually hits the submit
button on a credit card submittal form, their card may be charged multiple times if the developer
has not taken the time to validate against such an eventuality.
You can deal with multiple submittal validation in essentially two ways.
• Server side refers to a script located on the server that is receiving the data
• client side is more browser related

Preventing Multiple Submissions on the Server Side


While you can accomplish this goal in a number of ways from a server-side perspective, we prefer to
use a session-based method. Basically, once the submit button has been clicked, the server logs the
request from the individual user. If the user attempts to resubmit a request, the script notes a
request is already in motion from this user and denies the subsequent request. Once the script has
finished processing, the session is unset, and you have no more worries. The following script
Preventing Multiple Submissions on the Server Side
<html>
<head>
</head>
<body>
<form name="test" onsubmit="return checkandsubmit ()" method="post" action="p2.php">
Name::<input type="text" name="uname"><br>
Password::<input type="password" name="pwd"><br>
<input type="submit" value="SUBMIT" id="submitbut"><br>
</form>
</body>
</html>

p2.php:
<?php
$name=$_POST['uname'];
$pwd=$_POST['pwd'];
session_start();
if(!isset($_SESSION['x'])){
$_SESSION['x']=TRUE;
210 Chapter 7. Creating and Using Forms

}
if($_SESSION['x']==TRUE){
mysql_connect("localhost","root","");
mysql_select_db("TEST");
mysql_query("INSERT INTO login('uname','pwd') VALUES('$name','$pwd')");

$_SESSION['x']=FALSE;

for($i=0;$i<=2000000;$i++);//do nothing
for($i=0;$i<=2000000;$i++);//do nothing
for($i=0;$i<=2000000;$i++);//do nothing
for($i=0;$i<=2000000;$i++);//do nothing
for($i=0;$i<=2000000;$i++);//do nothing
for($i=0;$i<=2000000;$i++);//do nothing
for($i=0;$i<=2000000;$i++);//do nothing
}
echo "Successfully added to database";
session_unset();
?>

Preventing Multiple Submissions on the Client Side


Handling multiple submittals from a client-side perspective is actually much simpler than doing it
on the server side. With well-placed JavaScript, you can ensure that the browser will not let the
submittal go through more than once. The problem with this method, of course, is that JavaScript
is not always foolproof because of the user’s ability to turn it off. The following example uses
JavaScript to cut off multiple submittals from a client-side (browser) level.

<html>
<head>
<script>
function checkandsubmit() {
//Disable the submit button.
document.test.submitbut.disabled = true;
//Then submit the form.
document.test.submit();
}
</script>
</head>
<body>
<form name="test" onsubmit="return checkandsubmit ()" method="post" action="p2.php">
Name::<input type="text" name="uname"><br>
Password::<input type="password" name="pwd"><br>
<input type="submit" value="SUBMIT" id="submitbut"><br>
</form>
</body>
</html>

After submitting the the button will be disabled as follows


7.4 Handling Special Characters 211

Handling Special Characters


An added security feature, particularly when dealing with database submittal, is validating against
special characters being inserted into your script. Be it a database insertion script, a contact form, or
even a mailer system, you always want to ensure that no malicious users are attempting to sabotage
your script with bad (or special) characters. PHP allots a number of functions to use in this regard.

string trim ( string str [, string charlist] )


string htmlspecialchars ( string string [, int quote_style [, string charset]] )
string strip_tags ( string str [, string allowable_tags] )
string addslashes ( string str )

The following script demonstrates above functions


<?php
$msg1=" Welcome to PHP ";//for trim
$msg2="<b>Welcome to php</b>";
$msg3="Welcome \n to \php";

echo "With out using trim(): **".$msg1."**<br>";


echo "Using trim():**".trim($msg1)."**<br><br><br>";

echo "With out using htmlspecialchars(): ".$msg2."<br>";


echo "Using htmlspecialchars(): ".htmlspecialchars($msg2)."<br><br><br>";

echo "Using strip_tags(): ".strip_tags($msg2)."<br><br><br>";

echo "With out Using addslashes(): ".$msg3."<br>";


echo "Using addslashes(): ".addslashes($msg3)."<br><br><br>";
?>
OUTPUT:
With out using trim(): ** Welcome to PHP **
Using trim():**Welcome to PHP**

With out using htmlspecialchars(): Welcome to php


Using htmlspecialchars(): <b>Welcome to php</b>

Using strip_tags(): Welcome to php

With out Using addslashes(): Welcome to \php


Using addslashes(): Welcome to \\php

• The trim() function removes any blank space found at the beginning or end of the submitted
string.
• The htmlspecialchars() function turns attempted HTML into its special character equivalent.
• The strip_tags() function completely removes any characters it sees as being a tag.
212 Chapter 7. Creating and Using Forms

• addslashes(), places a slash in front of any characters that could be harmful to the database
such as apostrophes. The end result is a string that is quite squeaky clean

File Uploads
Handling file uploads in PHP is not exactly difficult from a syntax point of view, but it is important
(extremely important in fact) to ensure that the file being uploaded is within the upload constraints
you lay out for it. The following are the constrains of File :
Size The size of the uploaded file (in bytes). You could easily find your server under some heavy
loads if you are not careful about what size of files are being uploaded.
Type The MIME type of the uploaded file. Ex: .jpeg, .pdf, .doc, etc,.
Name The original filename that was uploaded. It is possible to change file name at the time of
uploading.
tmp_name The temporary name of the file that has been uploaded.
error The error code that may be generated by the file upload.
The following Example demonstrate file uploading using Form

<form action="" method="post" enctype="multipart/form-data">


<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>

<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>

Basic Database Concepts


PHP 5 has the ability to connect to MySQL using some advanced options that have been released
with the latest build of MySQL.

Connecting to a MySQL Database


To do any work with a MySQL database, you must first open a link to the database and connect
to it. Performing such functionality in PHP is quick and efficient. You can use the function
mysql_connect() to connect to a database. The prototype for mysql_connect() is as follows:

resource mysql_connect ( [string server [, string username [, string password


[, bool new_link [, int client_flags]]]]] );
7.6 Basic Database Concepts 213

The following script demonstrate the database connection


<?php
$host="localhost"; // Host name or IP(127.0.0.1)
$username="root"; // Mysql username
$password=""; // Mysql password if exist write password here

if($db=mysql_connect("$host", "$username", "$password")){


echo "<h1>Successfully connected to the database..!!</h1>";
}else{
die("<h1>cannot connect to database..!!</h1>");
}
mysql_close ($db);
?>

::::::::::OUTPUT::::::::::
Successfully connected to the database..!!

In the above script, mysql_connect() pass the connection information like host name, MySQL
database name and it’s password.This gives you access to any databases that are assigned to the
user root.
The mysql_close() function takes care of this handily and can receive the resource handler
that was assigned with the mysql_connect() function as an argument to close. The prototype for
mysql_close() is as follows:
bool mysql_close ( [resource link_identifier] )

Querying the Database


To perform a query in PHP, you can use the function mysql_query(). It allows you to perform a
myriad of SQL functions(such as insert, which allows you to enter data into a row; alter, which
allows you to change the format of a table; select, whichallows you to return a row set from a table in
the database; and delete, which allows you to remove a row in the database;) and is quite simple to
use. The prototype for mysql_query() is as follows:
resource mysql_query ( string query [, resource link_identifier] )

All the examples in this chapter, assume you have a database set up called Text1 that contains a
table called testing with the following structure:

sno INT AUTO_INCREMENT PRIMARY KEY


name VARCHAR(20)
pwd VARCHAR(20)
type VARCHAR(10)

Figure 7.14: Database Table


214 Chapter 7. Creating and Using Forms

The following example demonstrate insert data in to MySQL database.


<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="TEST1"; // Database name
$tbl_name="testING"; // Table name

// Connect to server and select database.


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Assigned values to the variables


$name="PRAVEEN KUMAR";
$pwd="testingphp";
$type="Admin";

// Insert data into mysql


$sql="INSERT INTO $tbl_name(name, pwd, type)VALUES('$name', '$pwd', '$type')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".


if($result){
echo "Data entered Successfully";
echo "<BR>";
//echo "<a href='test.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>

:::::::::: OUTPUT ::::::::::


Data entered Successfully

Figure 7.15: After Exicution of above code Database table

To perform a query on a database table, you must first specify which database (that is assigned
to the current user) you want to perform this action use function mysql_select_db()
Once you have a selected database, it is simply a matter of creating a query and executing it
using the mysql_query() function.

Insert data into above table using forms


reg.html
<html>
7.6 Basic Database Concepts 215

<head>
<title>DATA BASE CONNECTION</title>
</head>
<body>
<form method="post" action="test-db.php">
<table><tr><td colspan='2' align='center'>Registration</td></tr>
<tr>
<td>NAME</td><td><input type="text" name="name" required></td>
</tr><tr>
<td>Password</td><td><input type="password" name="pwd" required></td>
</tr><tr>
<td>User Type</td><td><select name='type'>
<option>Student</option><option>Staff</option>
<option>Non-Teaching</option> </select></td>
</tr>
<tr><td colspan="2"><input type="submit" value="NEXT"></td></tr>
</table>
</form>
</body>
</html>

Figure 7.16: Output of reg.html

test-db.php(Insertion is performed in this file)


<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="TEST1"; // Database name
$tbl_name="testING"; // Table name

// Connect to server and select database.


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Assigned values to the variables


$name=$_POST['name'];
$pwd=$_POST['pwd'];
$type=$_POST['type'];

// Insert data into mysql


216 Chapter 7. Creating and Using Forms

$sql="INSERT INTO $tbl_name(name, pwd, type)VALUES('$name', '$pwd', '$type')";


$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".


if($result){
echo "Data entered Successfully";
echo "<BR>";
echo "<a href='reg.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>

:::::::::: OUTPUT ::::::::::


Data entered Successfully
Back to main page

Figure 7.17: After submitting data using forms database

Retrieving and Displaying Results


In PHP, the most common method to retrieve a row in the database is with the mysql_fetch_array()
function, which puts the results garnered from a row set into an array for ease of use. Its prototype
is as follows:

array mysql_fetch_array ( resource result [, int result_type] )

The following example outputs the results of the current database table.
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="TEST1"; // Database name
$tbl_name="testing"; // Table name

// Connect to server and select databse.


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name ";


$result=mysql_query($sql)or die(mysql_error());
?>

<table border='1' width='50%' align='center'>


7.6 Basic Database Concepts 217

<tr><td colspan='3' align='center'><h2>User's Details</h2></td></tr>


<tr><th>SNO</th><th>Name</th><th>User Type</th></tr>

<?php
while($info = mysql_fetch_array($result)){
Print "<tr><td> ".$info[0] . " </td>";
Print "<td> ".$info[1] . " </td>";
Print "<td> ".$info[3] . " </td></tr>";
}
?>

Figure 7.18: OUTPUT of the above program

Login form validation with database values


You will have plenty of opportunities to build a query on the fly. A fairly common example is
receiving data from a form that will allow you to log into your account. While the functionality
behind this is useful and rather powerful, it is also the preferred method for crackers to gain entry
into your system.
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style>
.error {
font-weight: bold;
color: #FF0000;
}
</style>
</head>
<body>
<div style="width: 500px; text-align: left;">
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="TEST1"; // Database name
$tbl_name="testing"; // Table name

//Function to determine a valid e-mail address.

//Default to showing the form.


$goodtogo = false;
//Handle the incoming data.
if ($_SERVER["REQUEST_METHOD"] == "POST"){
218 Chapter 7. Creating and Using Forms

//Let's declare a submission value that tells you if you are fine.
$goodtogo = true;
//Validate the name.
try {
if (trim ($_POST['name']) == "" || trim ($_POST['pwd'])==""){
$goodtogo = false;
throw new exception ("Sorry, you must enter your name & Password.<br />");
}
else{
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name where name='".$_POST['name']."'
and pwd='".$_POST['pwd']."'";

$result=mysql_query($sql);
if($info = mysql_fetch_array($result)){
$goodtogo = false;
throw new exception ("<h1>User name and password matched</h1>.<br />");
}else{
$goodtogo = false;
throw new exception ("Sorry, you User name password not matched.<br />");
}
}
} catch (exception $e) {
?><span class="error"><?php echo $e->getmessage(); ?></span><?php
}
}

if (!$goodtogo){
?>
<form action="<?php $_SERVER["PHP_SELF"];?>" method="post">
<p>Login form:</p>

User Name: <input type="text" name="name" maxlength="150" value="<?


if ($_SERVER["REQUEST_METHOD"] == "POST"){echo $_POST['name'];}?>"/><br /><br />
Password: <input type="password" name="pwd" maxlength="150" value="<?
if ($_SERVER["REQUEST_METHOD"] == "POST"){echo $_POST['pwd'];}?>" /><br />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
<?php
}
?>
</div>
</body>
</html>

In the above script we collect values from form and validate form values with database values.
7.6 Basic Database Concepts 219

Figure 7.19: Invalid inputs

Figure 7.20: Valid User name and passwords

Deleting Data
Removing data is largely the same as other row or useless data. You will definitely want to specify
which record you are attempting to remove, as you can quite easily lose an entire table if you are
not careful. The following example enables you to remove a record from your table. Should you
want to remove an entire table‘s contents, simply leave out the where clause in the SQL code.

The following script shows the delete a row in a table of MySQL database
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="TEST1"; // Database name
$tbl_name="testing"; // Table name

// Connect to server and select databse.


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="DELETE FROM $tbl_name where sno=2";


$result=mysql_query($sql)or die(mysql_error());

if($result){
echo "Data in 2<sup>ad</sup> row is successfully deleted..";
}
?>
::::::::::: OUTPUT ::::::::::
Data in 2ad row is successfully deleted..
220 Chapter 7. Creating and Using Forms

Figure 7.21: After deletion Database

Modifying Data
Obviously, database functionality would be pretty useless if the data stored in the database itself
could only remain static. Luckily, MySQL provides you with a means to modify certain data using
UPDATE command.

The following script shows the Updatation of MySQL database


<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="TEST1"; // Database name
$tbl_name="testing"; // Table name

// Connect to server and select databse.


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="UPDATE $tbl_name SET name='Praveen' WHERE sno='3'";


$result=mysql_query($sql)or die(mysql_error());

if($result){
echo "Data is successfully updated..";
}
?>
:::::::::: OUTPUT ::::::::::
Data is successfully updated..

Figure 7.22: After Modifying database..

Following example shows the change-password script


<html xmlns="http://www.w3.org/1999/xhtml">
<title>Change password</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style>
.error {
font-weight: bold;
color: #FF0000;
}
Basic Database Concepts 221

</style>
</head>
<body>
<div style="width: 500px; text-align: left;">
<?php
//Default to showing the form.
$goodtogo = false;
//Handle the incoming data.
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//Let's declare a submission value that tells you if you are fine.
$goodtogo = true;

try {
if (trim ($_POST['opwd'])== "" ){
$goodtogo = false;
throw new exception ("Sorry, you must enter your old password.<br />");
}else if (trim ($_POST['pwd']) == "" || trim ($_POST['cpwd']) == "" ){
$goodtogo = false;
throw new exception ("Sorry, you must enter your new password or Confirm password.<br />");
}
else if(trim ($_POST['pwd']) != trim ($_POST['cpwd'])){
$goodtogo = false;
throw new exception ("Sorry, new password or Confirm password Must be same.
<br />");
}
else if(trim ($_POST['opwd'])== "" || trim ($_POST['pwd']) != "" ||
trim ($_POST['cpwd']) != ""){
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="TEST1"; // Database name
$tbl_name="testing"; // Table name

// Connect to server and select databse.


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="UPDATE $tbl_name SET pwd='".$_POST['cpwd']."' WHERE pwd='".$_POST['opwd']."'";


$result=mysql_query($sql)or die(mysql_error());

if($result){
throw new exception ("Password is successfully changed..");
}

}} catch (exception $e) {


?><span class="error"><?php echo $e->getmessage(); ?></span><?php
}
}
//Show the forms only if you do not have all the valid information.
222 Chapter 7. Creating and Using Forms

if (!$goodtogo){
?>
<form action="<?php $_SERVER["PHP_SELF"];?>" method="post">
<p>Fill the following form:</p>

Old password: <input type="password" name="opwd" maxlength="150" value="<?


if ($_SERVER["REQUEST_METHOD"] == "POST"){echo $_POST['opwd'];}?>"/><br /><br />

New password: <input type="password" name="pwd" maxlength="150" value="<?


if ($_SERVER["REQUEST_METHOD"] == "POST"){echo $_POST['pwd'];}?>"/><br /><br />

Re-enter New password: <input type="password" name="cpwd" maxlength="150" value="<?


if ($_SERVER["REQUEST_METHOD"] == "POST"){echo $_POST['cpwd'];}?>"/><br /><br />

<input type="submit" value="Submit" style="margin-top: 10px;" />


</form>
<?php
}
?>
</div>
</body>
</html>
:::::::::: OUTPUT ::::::::::
Password is successfully changed..

Figure 7.23: After changing the password database

MySQL Functions in php


mysql_connect()
Open a connection to a MySQL Server
resource mysql_connect ([ string $server [, string $username [, string
$password [, bool $new_link [, int $client_flags ]]]]] )
server The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a
local socket.
e.g.: localhost, 127.0.0.1:8080 etc.,
username the name of the user that owns the server process is used.
eg: root
password password of the given user. This is optional.
new_link If a second call is made to mysql_connect() with the same arguments, no new link will be
established, but instead, the link identifier of the already opened link will be returned. The
new_link parameter modifies this behavior and makes mysql_connect() always open a new
link, even if mysql_connect() was called before with the same parameters. It is also optional.
Example: $db = mysql_connect(’localhost’, ’mysql_user’, ’mysql_password’);
7.7 MySQL Functions in php 223

mysql_close()
Close MySQL connection

bool mysql_close ([ resource $link_identifier ] )

mysql_close() closes the non-persistent connection to the MySQL server that’s associated with the
specified link identifier.
Using mysql_close() isn’t usually necessary, as non-persistent open links are automatically
closed at the end of the script’s execution.
link_identifier It close the MySQL connection. If the link identifier is not specified, the last
link opened by mysql_connect() is assumed.
Returns TRUE on success or FALSE on failure.
Example: mysql_close($db);

mysql_select_db()
Select a MySQL database

bool mysql_select_db ( string $database_name [, resource $link_identifier ] )

Returns TRUE on success or FALSE on failure.

database_name: The name of the database that is to be selected.


link_identifier If the link identifier is not specified, the last link opened by mysql_connect() is
assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no
arguments. If no connection is found or established, an E_WARNING level error is generated.

mysql_query()
Send a MySQL query

resource mysql_query ( string $query [, resource $link_identifier ] )

mysql_query() sends a unique query (multiple queries are not supported) to the currently active
database on the server that’s associated with the specified link_identifier.
query: An SQL query
The query string should not end with a semicolon. Data inside the query should be properly
escaped.
link_identifier If the link identifier is not specified, the last link opened by mysql_connect() is
assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no
arguments. If no connection is found or established, an E_WARNING level error is generated.
• For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset,
mysql_query() returns a resource on success, or FALSE on error.
• For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query()
returns TRUE on success or FALSE on error.
• The returned result resource should be passed to mysql_fetch_array(), and other functions
for dealing with result tables, to access the returned data.
• Use mysql_num_rows() to find out how many rows were returned for a SELECT statement
or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT,
REPLACE, or UPDATE statement.
224 Chapter 7. Creating and Using Forms

mysql_fetch_array()
Fetch a result row as an associative array, a numeric array, or both.
array mysql_fetch_array ( resource $result [, int $result_type] )

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
result: The result resource that is being evaluated. This result comes from a call to mysql_query().
result_type: The type of array that is to be fetched. It’s a constant and can take the following
values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
Note: An important thing to note is that using mysql_fetch_array() is not significantly slower
than using mysql_fetch_row(), while it provides a significant added value.
Example

<?php
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT sno, name FROM testing");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {


printf("ID: %s Name: %s", $row[0], $row[1]);
}
?>

mysql_fetch_row()
GET a result row as an enumerated array
array mysql_fetch_row ( resource $result )

Returns a numerical array that corresponds to the fetched row and moves the internal data pointer
ahead.
• Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there
are no more rows.
• mysql_fetch_row() fetches one row of data from the result associated with the specified result
identifier. The row is returned as an array. Each result column is stored in an array offset,
starting at offset 0.
• The result resource that is being evaluated. This result comes from a call to mysql_query().
Example:
<?php
$result = mysql_query("SELECT * FROM testing");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);

echo $row[0];
echo $row[1];
?>
7.8 Model View Controller(MVC) Architecture 225

mysql_fetch_assoc()
Fetch a result row as an associative array.
array mysql_fetch_assoc ( resource $result )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer
ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for
the optional second parameter. It only returns an associative array.

Note: An important thing to note is that using mysql_fetch_assoc() is not significantly slower
than using mysql_fetch_row(), while it provides a significant added value.

More MySQL functions


The following list of functions for mysql operations in php, the brief description of function names
and it’s usages are listed below.

Function Use
mysql_affected_rows() GET number of affected rows in previous MySQL operation
mysql_client_encoding() Returns the name of the character set
mysql_create_db() Create a MySQL database
mysql_data_seek() Move internal result pointer
mysql_db_name() Retrieves database name from the call to mysql_list_dbs()
mysql_db_query() Selects a database and executes a query on it
mysql_drop_db() Drop (delete) a MySQL database
mysql_errno() Returns the numerical value of the error message from previous
MySQL operation
mysql_error() Returns the text of the error message from previous MySQL oper-
ation
mysql_escape_string() Escapes a string for use in a mysql_query()
mysql_info() get information about the most recent query
mysql_insert_id() get the ID generated in the last query
mysql_list_dbs() List databases available on a MySQL server
mysql_list_fields() List MySQL table fields
mysql_num_fields() get number of fields in result
mysql_num_rows() get number of rows in result

Table 7.2: MySQL Functions

Model View Controller(MVC) Architecture


The model view controller pattern is the most used pattern for today‘s world web applications. It
has been used for the first time in Smalltalk and then adopted and popularized by Java. At present
there are more than a dozen PHP web frameworks based on MVC pattern. Despite the fact that the
MVC pattern is very popular in PHP.
The MVC pattern separates an application in Three modules: Model, View and Controller.
Model The model is responsible to manage both the data and it’s behavior.The model is responsible
for defining the formula’s used to perform such conversionsand when presented with a value
and desired conversion senario, the model carries out the conversion and return the result. It
stores and retrieves entities used by an application, usually from a database, and contains the
logic implemented by the application.
226 Chapter 7. Creating and Using Forms

View (presentation) The view is responsible to display the data provided by the model in a
specific format. It has a similar usage with the template modules present in some popular
web applications.
Controller The controller handles the model and view layers to work together. The controller
receives a request from the client, invokes the model to perform the requested operations and
sends the data to the View. The view formats the data to be presented to the user, in a web
application as an html output.

Figure 7.24: MVC Architecture

A simple way to think of this would be to consider the following:


• A user interacts with the view - by clicking on a link or submitting a form.
• The Controller handles the user input, and transfers the information to the model
• The Model receives the information and updates it’s state (adds data to a database, for
example, or calculates todays date)
• The View checks the state of the Model and responds accordingly (listing the newly entered
data, maybe)
• The View waits for another interaction from the user.

Exercise
1. List and describe the different form elements associated with common form issues.
2. Differentiate GET and POST methods.
3. Explain with example how the validatation of forms is done using PHP.
4. What is the advantage of super globals, explain with example?
5. Write a PHP program to submit values using super globals and globals.
6. How can we prevent multiple submissions of a form on server side? Explain with example.
7.
8. What is the advantage of Superglobals? Explain with example.
9. Write a program to differentiate GET and POST methods.
10. Explain briefly about the POST method with example.
11. Differentiate Superglobals versus Globals.
12. Explain briefly about the GET method with example.
13. Differentiate GET and POST methods.
14. What are the disadvantages of redisplaying forms without previous information and error
messages?
15. Write a PHP program for redisplaying forms with previous information and error messages.
16. How to perform a query in PHP? Explain with PHP code.
7.9 Exercise 227

17. Briefly explain about the MVC architecture.


18. Explain the function used to connect to a MySQL database.
19. How to perform a query in PHP? Explain with PHP code.
20. Explain the function used to connect to a MySQL database.
21. Explain mysql_select_db () function with example.
22. Explain the function used to connect to a MySQL database with example.
23. Explain about the most common method to retrieve the row from database in PHP.
24. Explain the following functions with examples.
(a) Mysql_connect()
(b) mysql_close()
(c) mysql_query()
(d) mysql_select_db().
25. Explain briefly the three components of MVC architecture.
26. How to perform querying the database? Explain with a PHP script.
8. AJAX-Asynchronous JavaScript And XML

AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related tech-
nologies like JavaScript, DOM, XML, HTML, CSS etc. AJAX allows you to send and receive data
asynchronously without reloading the web page. So it is fast. AJAX allows you to send only
important information to the server not the entire page. So only valuable data from the client side is
routed to the server side. It makes your application interactive and faster.
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XML-
HttpRequest object to communicate with servers. It can send and receive information in various
formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is
its "asynchronous" nature, which means it can communicate with the server, exchange data, and
update the page without having to refresh the page.
The two major features of AJAX allow you to do the following:
• Make requests to the server without reloading the page
• Receive and work with data from the server
Question: Is Ajax just another name for XMLHttpRequest?
Answer. No. XMLHttpRequest is only part of the Ajax equation. XMLHttpRequest is the
technical component that makes the asynchronous server communication possible; Ajax is our
name for the overall approach described in the article, which relies not only on XMLHttpRequest,
but on CSS, DOM, and other technologies.

How to make an HTTP request


In order to make an HTTP request to the server with JavaScript, you need an instance of an
object with the necessary functionality. This is where XMLHttpRequest comes in. Its predecessor
originated in Internet Explorer as an ActiveX object called XMLHTTP. Then, Mozilla, Safari,
and other browsers followed, implementing an XMLHttpRequest object that supported the meth-
ods and properties of Microsoft’s original ActiveX object. Meanwhile, Microsoft implemented
XMLHttpRequest as well.
// Old compatibility code, no longer needed.
230 Chapter 8. AJAX-Asynchronous JavaScript And XML

if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...


httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

After making a request, you will receive a response back. At this stage, you need to tell the XMLHttp
request object which JavaScript function will handle the response, by setting the onreadystatechange
property of the object and naming it after the function to call when the request changes state, like
this:

httpRequest.onreadystatechange = nameOfTheFunction;

Note that there are no parentheses or parameters after the function name, because you’re assigning
a reference to the function, rather than actually calling it. Alternatively, instead of giving a function
name, you can use the JavaScript technique of defining functions on the fly (called "anonymous
functions") to define the actions that will process the response, like this:

httpRequest.onreadystatechange = function(){
// Process the server response here.
};

Next, after declaring what happens when you receive the response, you need to actually make the
request, by calling the open() and send() methods of the HTTP request object, like this:

httpRequest.open('GET', 'http://www.example.org/some.file', true);


httpRequest.send();

• The first parameter of the call to open() is the HTTP request method - GET, POST, HEAD,
or another method supported by your server. Keep the method all-capitals as per the HTTP
standard, otherwise some browsers (like Firefox) might not process the request. For more
information on the possible HTTP request methods
• The second parameter is the URL you’re sending the request to. As a security feature, you
cannot call URLs on 3rd-party domains by default. Be sure to use the exact domain name on
all of your pages or you will get a "permission denied" error when you call open(). A common
pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld. If
you really need to send a request to another domain
• The optional third parameter sets whether the request is asynchronous. If true (the default),
JavaScript execution will continue and the user can interact with the page while the server
response has yet to arrive. This is the first A in AJAX.
The parameter to the send() method can be any data you want to send to the server if POST-ing the
request. Form data should be sent in a format that the server can parse, like a query string:

"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"

or other formats, like multipart/form-data, JSON, XML, and so on.


Note that if you want to POST data, you may have to set the MIME type of the request. For
example, use the following before calling send() for form data sent as a query string:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Handling the server response 231

Handling the server response


When you sent the request, you provided the name of a JavaScript function to handle the response:

httpRequest.onreadystatechange = nameOfTheFunction;

What should this function do? First, the function needs to check the request’s state. If the state has
the value of XMLHttpRequest.DONE (corresponding to 4), that means that the full server response was
received and it’s OK for you to continue processing it.

if (httpRequest.readyState === XMLHttpRequest.DONE) {


// Everything is good, the response was received.
} else {
// Not ready yet.
}

The full list of the readyState values is documented at XMLHTTPRequest.readyState and is as


follows:
• 0 (uninitialized) or (request not initialized)
• 1 (loading) or (server connection established)
• 2 (loaded) or (request received)
• 3 (interactive) or (processing request)
• 4 (complete) or (request finished and response is ready) (Source)
Next, check the response code of the HTTP response. The possible codes are listed at the W3C.
In the following example, we differentiate between a successful and unsuccessful AJAX call by
checking for a 200 OK response code.

if (httpRequest.status === 200) {


// Perfect!
} else {
// There was a problem with the request.
// For example, the response may have a 404 (Not Found)
// or 500 (Internal Server Error) response code.
}

After checking the state of the request and the HTTP status code of the response, you can do
whatever you want with the data the server sent. You have two options to access that data:
httpRequest.responseText - returns the server response as a string of text
httpRequest.responseXML - returns the response as an XMLDocument object you can traverse
with JavaScript DOM functions
Note that the steps above are valid only if you used an asynchronous request (the third parameter of
open() was unspecified or set to true). If you used a synchronous request you don’t need to specify
a function, but this is highly discouraged as it makes for an awful user experience.

Working with the XML response


In the previous example, after receiving the response to the HTTP request we used the request
object’s responseText property , which contained the contents of the test.html file. Now let’s try the
responseXML property.
First off, let’s create a valid XML document that we’ll request later on. The document (test.xml)
contains the following:
232 Chapter 8. AJAX-Asynchronous JavaScript And XML

<?xml version="1.0" ?>


<root>
I'm a test.
</root>

In the script we only need to change the request line to:

...
onclick="makeRequest('test.xml')">
...

Then in alertContents(), we need to replace the line alert(httpRequest.responseText); with:

var xmldoc = httpRequest.responseXML;


var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);

This code takes the XMLDocument object given by responseXML and uses DOM methods to
access some of the data contained in the XML document. text.xml is as follows:
<root>I'm a test.</root>

AJAX-Call Back
What is callback
Let’s say we have a function F1 which calls F2. F2 is doing some async operation like AJAX. F1
would like to know the result of the ajax call. Now F1 will pass another function say C1 as an
additional parameter to F2 which F2 will call after it process the ajax request completely. Think of it
as F1 is taking service from F2 by giving the service details along with C1. When F2 is done with
service, it informs F1 by calling C1 with some additional data.

Why do we need callback


We need callback because we don’t want to duplicate the ajax code every time we need. We want to
create a generic ajax function which takes ajax details as input along with callback reference. After
completing the call, it calls the callback so that caller can resume with the result of the ajax call.
In the example above, we used makeAjaxCall to get the user details. Now lets say we want to
show all the repositories of that user. For that, we need to make another kind of server call to get
the repositories list. Clearly we don’t want to write another makeAjaxCall look alike function to
perform the server call. We want to use the makeAjaxCall. For Ex
function makeAjaxCall(url, methodType, callback){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
console.log("xhr done successfully");
var resp = xhr.responseText;
var respJson = JSON.parse(resp);
callback(respJson);
} else {
Exercise 233

console.log("xhr failed");
}
} else {
console.log("xhr processing going on");
}
}
console.log("request sent succesfully");
}
document.getElementById("userDetails").addEventListener("click", function(){
//git hub url to get a user details
var userId = document.getElementById("userId").value;
var URL = "https://api.github.com/users/"+userId;
makeAjaxCall(URL, "GET", processUserDetailsResponse);
});
document.getElementById("repoList").addEventListener("click", function(){
// git hub url to get btford details
var userId = document.getElementById("userId").value;
var URL = "https://api.github.com/users/"+userId+"/repos";
makeAjaxCall(URL, "GET", processRepoListResponse);
});
function processUserDetailsResponse(userData){
console.log("render user details", userData);
}
function processRepoListResponse(repoList){
console.log("render repo list", repoList);
}

In the above example, you can see that there are two places where makeAjaxCall function is
called and handling of server response is different for the both the scenario. makeAjaxCall is a
kind of service function here which takes the ajax details along with callback reference. When it
completes the ajax call, it informs the caller by calling its callback reference. Using the callback
reference, we can create a reusable independent function which can just focus on making ajax call.
In the callback function, we can process the data such as show the user details or listing down the
repositories list.
We can use the ajax service function at n number of places by passing ajax call details like URL,
method and callback reference. Callbacks are great way to separate the core logic of ajax with the
rest of the application. But unfortunately, it becomes very difficult to handle callback when we do
series of ajax calls where one call is dependent on previous call. We might encounter difficulty
in maintaining multiple callback references and handling multiple success and error conditions.
Promise is a better way to manage multiple ajax calls.

Exercise
1. Explain AJAX and its advantages.
2. Is Ajax just another name for XMLHttpRequest? Explain.
3. Explain about Call backs in AJAX.
4. Explain How to make an HTTP request in AJAX.
5. Explain Working of the XML response in detail.
6. Explain how AJAX Handling the server response.
9. Web services

A Web Service is a standards-based, language-agnostic software entity, that accepts specially


formatted requests from other software entities on remote machines via vendor and transport neutral
communication protocols, producing application specific responses.

Advantages of Web services


• Loosely Coupled Each service exists independently of the other services that make up the
application. Individual pieces of the application to be modified without impacting unrelated
areas.
• Ease of Integration Data is isolated between applications creating ’silos’. Web Services act
as glue between these and enable easier communications within and across organisations.
• Service Reuse Takes code reuse a step further. A specific function within the domain is only
ever coded once and used over and over again by consuming applications.

Web service Architecture


Every framework needs some sort of architecture to make sure the entire framework works as
desired. Similarly, in web services, there is an architecture which consists of three distinct roles as
given below
• Provider - The provider creates the web service and makes it available to client application
who want to use it.
• Requestor - A requestor is nothing but the client application that needs to contact a web
service. The client application can be a .Net, Java, or any other language based application
which looks for some sort of functionality via a web service.
• Broker - The broker is nothing but the application which provides access to the UDDI.
The UDDI, as discussed in the earlier topic enables the client application to locate the web
service.
The diagram below showcases how the Service provider, the Service requestor and Service registry
interact with each other.
236 Chapter 9. Web services
Types of Web services 237

1. Publish - A provider informs the broker (service registry) about the existence of the web
service by using the broker’s publish interface to make the service accessible to clients
2. Find - The requestor consults the broker to locate a published web service
3. Bind - With the information it gained from the broker(service registry) about the web service,
the requestor is able to bind, or invoke, the web service.

Types of Web services


There are two types of web services.
1. SOAP: SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry
standard protocol for designing and developing web services. Since it’s XML based, it’s
platform and language independent. So our server can be based on JAVA and client can be
on .NET, PHP etc. and vice versa.
2. REST: REST is an architectural style for developing web services. It’s getting popularity
recently because it has small learning curve when compared to SOAP. Resources are core
concepts of Restful web services and they are uniquely identified by their URIs.

Java Web Services


Java provides it’s own API to create both SOAP as well as REST web services.
1. JAX-WS: JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based
Java API to build web services server and client application.
2. JAX-RS: Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST
web services. JAX-RS uses annotations to simplify the development and deployment of web
services.
Both of these APIs are part of standard JDK installation, so we don’t need to add any jars to work
with them. Both of these APIs use annotations very heavily.

9.3.1 Example: Hello World JAX-WS Application


TestService.java

package com.journaldev.jaxws.service;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Endpoint;

@WebService
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
public class TestService {

@WebMethod
public String sayHello(String msg){
return "Hello "+msg;
}

public static void main(String[] args){


Endpoint.publish("http://localhost:8888/testWS", new TestService());
}
238 Chapter 9. Web services

WSDL – Web services description language


A WSDL document is used to describe a web service. This description is required so that client
applications are able to understand what the web service actually does.
• The WSDL file contains the location of the web service and
• The methods which are exposed by the web service.
The WSDL file itself can look very complex to any user, but it contains all the necessary information that
any client application would require to use the relevant web service.

9.4.1 WSDL Creation


The WSDL file gets created whenever a web service is built in any programming language.
Since the WSDL file is pretty complicated to be generated from plain scratch, all editors such
as Visual Studio for .Net and Eclipse for Java automatically create the WSDL file.

Example
<?xml version="1.0"?>
<definitions name="Tutorial"
targetNamespace=http://Guru99.com/Tutorial.wsdl
xmlns:tns=http://Guru99.com/Tutorial.wsdl
xmlns:xsd1=http://Guru99.com/Tutorial.xsd
xmlns:soap=http://schemas.xmlsoap.org/wsdl/soap/
xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<schema targetNamespace=http://Guru99.com/Tutorial.xsd
xmlns="http://www.w3.org/2000/10/XMLSchema">

<element name="TutorialNameRequest">
<complexType>
<all>
<element name="TutorialName" type="string"/>
</all>
</complexType>
</element>
<element name="TutorialIDRequest">
<complexType>
<all>
<element name="TutorialID" type="number"/>
</all>
</complexType>
</element>
</schema>
</types>
<message name="GetTutorialNameInput">
<part name="body" element="xsd1:TutorialIDRequest"/>
</message>
<message name="GetTutorialNameOutput">
<part name="body" element="xsd1:TutorialNameRequest"/>
</message>
9.5 SOAP Introduction 239

<portType name="TutorialPortType">
<operation name="GetTutorialName">
<input message="tns:GetTutorialNameInput"/>
<output message="tns:GetTutorialNameOutput"/>
</operation>
</portType>
<binding name="TutorialSoapBinding" type="tns:TutorialPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetTutorialName">
<soap:operation soapAction="http://Guru99.com/GetTutorialName"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>

<service name="TutorialService">
<documentation>TutorialService</documentation>
<port name="TutorialPort" binding="tns:TutorialSoapBinding">
<soap:address location="http://Guru99.com/Tutorial"/>
</port>
</service>
</definitions>

SOAP Introduction
In today’s world, there are huge number of applications which are built on different programming
languages. For example, there could be a web application designed in Java, another in .Net and
another in PHP.
Exchanging data between applications is crucial in today’s networked world. But data exchange
between these heterogeneous applications would be complex. So will be the complexity of the code
to accomplish this data exchange.
One of the methods used to combat this complexity is to use XML (Extensible Markup
Language) as the intermediate language for exchanging data between applications.
Every programming language has the capability to understand the XML markup language.
Hence, XML was used as the underlying medium for data exchange.
But there are no standard specifications on use of XML across all programming languages for
data exchange. That is where SOAP comes in.
SOAP was designed to work with XML over HTTP and have some sort of specification which
could be used across all applications.

Exercise
1. What is Web services? What is the Importance of it?
2. What are the different types of Web services? Explain.
3. Differentiate WSDL and SOAP.
4. Explain Java Web services in detail with example.
A. Sample Source Codes for Projects

Sample Source Codes


Config.php
<?php
$host="localhost"; //HOSTNAME
$duname="root"; //Database Username
$dpwd="password";
$dbname="database_name";
mysql_connect($host,$duname,$dpwd) or die("Connection fail !!");
mysql_select_db($dbname) or die("Database not selected");
}

login.php
<?php
session_start();
if($_SERVER["REQUEST_METHOD"]=="POST"){
include("config.php");

$uname=$_POST["Username"];
$pwd=$_POST["Password"];

$result=mysql_query("SELECT * from login where uname='$uname' and pwd='$pwd'");


if($info=mysql_fetch_array($result)){
$uid=$info["uid"];
$unmae=$info["uname"];
$_SESSION["uid"]=$uid;
$type=$info["role"];
$_SESSION['type']=$type;
$_SESSION['status']="Login Successful<br> Welcome";
242 Chapter A. Sample Source Codes for Projects

if($type==1){
header ("Location: admin_home.php");
}else if($type==2){
header ("Location: faculty_home.php");
}else if($type==3){
header ("Location: student_home.php")
}
}
}
<form method="POST" action="<?php $_SERVER['PHP_SELF']?>">
<h3>Login</h3>
<input placeholder="Username *" autofocus required type="text" name="Username">
<input placeholder="Password *" required="" type="password" name="Password">
<input type="submit" value="Login"/>
</form>
?>

logout.php
<?php
session_destroy();
header ("Location: index.php");
?>

Sorting array
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sorting PHP Indexed Array in Ascending Order</title>
</head>
<body>

<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");

// Sorting and printing array


sort($colors);
print_r($colors);
?>

</body>
</html>

Registration form
<?php
// Include config file
require_once 'config.php';

// Define variables and initialize with empty values


A.1 Sample Source Codes 243

$username = $password = $confirm_password = "";


$username_err = $password_err = $confirm_password_err = "";

// Processing form data when form is submitted


if($_SERVER["REQUEST_METHOD"] == "POST"){

// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = ?";

if($stmt = mysqli_prepare($link, $sql)){


// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);

// Set parameters
$param_username = trim($_POST["username"]);

// Attempt to execute the prepared statement


if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);

if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}

// Close statement
mysqli_stmt_close($stmt);
}

// Validate password
if(empty(trim($_POST['password']))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST['password'])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST['password']);
}

// Validate confirm password


244 Chapter A. Sample Source Codes for Projects

if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = 'Please confirm password.';
} else{
$confirm_password = trim($_POST['confirm_password']);
if($password != $confirm_password){
$confirm_password_err = 'Password did not match.';
}
}

// Check input errors before inserting in database


if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){

// Prepare an insert statement


$sql = "INSERT INTO users (username, password) VALUES (?, ?)";

if($stmt = mysqli_prepare($link, $sql)){


// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);

// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a pass

// Attempt to execute the prepared statement


if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}

// Close statement
mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootst
<style type="text/css">
body{ font: 14px sans-serif; }
A.1 Sample Source Codes 245

.wrapper{ width: 350px; padding: 20px; }


</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : '';
<label>Username:<sup>*</sup></label>
<input type="text" name="username"class="form-control" value="<?php echo
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : '';
<label>Password:<sup>*</sup></label>
<input type="password" name="password" class="form-control" value="<?php ec
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error'
<label>Confirm Password:<sup>*</sup></label>
<input type="password" name="confirm_password" class="form-control" value="
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? <a href="login.php">Login here</a>.</p>
</form>
</div>
</body>
</html>
B. Interview Questions

There is given PHP interview questions and answers that has been asked in many companies. Let’s
see the list of top PHP interview questions.
1. What is PHP?
PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language
that is widely used for web development. It supports many databases like MySQL, Oracle,
Sybase, Solid, PostgreSQL, generic ODBC etc.
2. What is PEAR in PHP?
PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP
Extension and Application Repository. It contains all types of PHP code snippets and libraries.
It also provide a command line interface to install "packages" automatically.
3. Who is known as the father of PHP?
Rasmus Lerdorf
4. What was the old name of PHP?
Personal Home Page.
5. Explain the difference b/w static and dynamic websites?
In static websites, content can’t be changed after running the script. You can’t change
anything in the site. It is predefined.
In dynamic websites, content of script can be changed at the run time. Its content regenerated
every time the user visit or reload. Google, yahoo and every search engine is the example of
dynamic website.
6. What is the use of "echo" in php?
It is used to print a data in the webpage, Example: <?phpechojCarinsurancej; ? > , The
following code print the text in the webpage.
7. How to include a file to a php page?
We can include a file using "include() " or "require()" function with file path as its parameter.
8. What’s the difference between include and require?
If the file is not found by require(), it will cause a fatal error and halt the execution of the
script. If the file is not found by include(), a warning will be issued, but execution will
248 Chapter B. Interview Questions

continue.
9. require_once(), require(), include().What is difference between them?
require() includes and evaluates a specific file, while require_once() does that only if it has
not been included before (on the same page). So, require_once() is recommended to use when
you want to include a file where you have a lot of functions for example. This way you make
sure you don’t include the file more times and you will not get the "function re-declared"
error.
10. Differences between GET and POST methods ?
We can send 1024 bytes using GET method but POST method can transfer large amount of
data and POST is the secure method than GET method .
11. How to declare an array in php?

Eg : var $arr = array('apple', 'grape', 'lemon');

12. What is the use of ’print’ in php?


This is not actually a real function, It is a language construct. So you can use with out
parentheses with its argument list. Example

print('PHP Interview questions');


print('Job Interview ');

13. What is use of in_array() function in php ?


in_array used to checks if a value exists in an array
14. What is use of count() function in php ?
count() is used to count all elements in an array, or something in an object
15. What’s the difference between include and require?
It’s how they handle failures. If the file is not found by require(), it will cause a fatal error
and halt the execution of the script. If the file is not found by include(), a warning will be
issued, but execution will continue.
16. What is the difference between Session and Cookie?
The main difference between sessions and cookies is that sessions are stored on the server,
and cookies are stored on the user’s computers in the text file format. Cookies can not hold
multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The
session only remains active as long as the browser is open.Users do not have access to the data
you stored in Session,Since it is stored in the server.Session is mainly used for login/logout
purpose while cookies using for user activity tracking
17. How to set cookies in PHP?

Setcookie("sample", "ram", time()+3600);

18. How to Retrieve a Cookie Value?

echo $_COOKIE["user"];

19. How to create a session? How to set a value in session ? How to Remove data from a
session?

Create session : session_start();


Set value into session : $_SESSION['USER_ID']=1;
Remove data from a session : unset($_SESSION['USER_ID'];
249

20. what types of loops exist in php?


for,while,do while and foreach (NB: You should learn its usage)
21. How to create a mysql connection?
mysql_connect(servername,username,password);
22. How to select a database?
mysql_select_db($db_name);
How to execute an sql query? How to fetch its result ?
$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; ");
$result = mysql_fetch_array($my_qry);
echo $result['First_name'];

23. Write a program using while loop

$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; ");


while($result = mysql_fetch_array($my_qry))
{
echo $result['First_name'.]."<br/>";
}

24. How we can retrieve the data in the result set of MySQL using PHP?

(a) mysql_fetch_row
(b) mysql_fetch_array
(c) mysql_fetch_object
(d) mysql_fetch_assoc
25. What is the use of explode() function ?
Syntax :
array explode ( string $delimiter , string $string [, int $limit ] );

This function breaks a string into an array. Each of the array elements is a substring of string
formed by splitting it on boundaries formed by the string delimiter.
26. What is the difference between explode() and split() functions?
Split function splits string into array by regular expression. Explode splits a string into array
by string.
27. What is the use of mysql_real_escape_string() function?
It is used to escapes special characters in a string for use in an SQL statement
28. Write down the code for save an uploaded file in php.
if ($_FILES["file"]["error"] == 0)
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}

29. How to create a text file in php?

$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
250 Chapter B. Interview Questions

if( $file == false )


{
echo ( "Error in opening new file" ); exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );

30. How to strip whitespace (or other characters) from the beginning and end of a string ?
The trim() function removes white spaces or other predefined characters from both sides of a
string.
31. What is the use of header() function in php ?
The header() function sends a raw HTTP header to a client browser.Remember that this
function must be called before sending the actual out put.For example, You do not print any
HTML element before using this function.
32. How to redirect a page in php?
The following code can be used for it, header("Location:index.php");
33. How stop the execution of a php scrip ?
exit() function is used to stop the execution of a page
34. How to set a page as a home page in a php based site ?
index.php is the default name of the home page in php based sites
35. How to find the length of a string?
strlen() function used to find the length of a string
36. what is the use of rand() in php?
It is used to generate random numbers.If called without the arguments it returns a pseudo-
random integer between 0 and getrandmax(). If you want a random number between 6 and
12 (inclusive), for example, use rand(6, 12).This function does not generate cryptographically
safe values, and should not be used for cryptographic uses. If you want a cryptographically
secure value, consider using openssl_random_pseudo_bytes() instead.
37. what is the use of isset() in php?
This function is used to determine if a variable is set and is not NULL
38. What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ? mysql_fetch_assoc
function Fetch a result row as an associative array, While mysql_fetch_array() fetches an
associative array, a numeric array, or both
39. What is mean by an associative array?
Associative arrays are arrays that use string keys is called associative arrays.
40. What is the importance of "method" attribute in a html form?
"method" attribute determines how to send the form-data into the server.There are two
methods, get and post. The default method is get.This sends the form information by
appending it on the URL.Information sent from a form with the POST method is invisible to
others and has no limits on the amount of information to send.
41. What is the importance of "action" attribute in a html form?
The action attribute determines where to send the form-data in the form submission.
42. What is the use of "enctype" attribute in a html form?
The enctype attribute determines how the form-data should be encoded when submitting it to
the server. We need to set enctype as "multipart/form-data" when we are using a form for
uploading files
43. How to create an array of a group of items inside an HTML form ?
We can create input fields with same name for "name" attribute with squire bracket at the end
of the name of the name attribute, It passes data as an array to PHP.
For instance :
251

<input name="MyArray[]" /> <input name="MyArray[]" /> <input name="MyArray[]" /> <i

44. Define Object-Oriented Methodology


Object orientation is a software/Web development methodology that is based on the modeling
a real world system.An object is the core concept involved in the object orientation. An
object is the copy of the real world enity.An object oriented model is a collection of objects
and its inter-relationships
45. How do you define a constant?
Using define() directive, like define ("MYCONSTANT",150)
46. How send email using php?
To send email using PHP, you use the mail() function.This mail() function accepts 5 param-
eters as follows (the last 2 are optional). You need webserver, you can’t send email from
localhost. eg :
mail($to,$subject,$message,$headers);

47. How to find current date and time?


The date() function provides you with a means of retrieving the current date and time,
applying the format integer parameters indicated in your script to the timestamp provided or
the current local time if no timestamp is given. In simplified terms, passing a time parameter
is optional - if you don’t, the current timestamp will be used.
48. Difference between mysql_connect and mysql_pconnect?
There is a good page in the php manual on the subject, in short mysql_pconnect() makes a
persistent connection to the database which means a SQL link that do not close when the
execution of your script ends. mysql_connect()provides only for the databasenewconnection
while using mysql_pconnect , the function would first try to find a (persistent) link that’s
already open with the same host, username and password. If one is found, an identifier for it
will be returned instead of opening a new connection... the connection to the SQL server will
not be closed when the execution of the script ends. Instead, the link will remain open for
future use.
49. What is the use of "ksort" in php?
It is used for sort an array by key in reverse order.
50. What is the difference between $var and $$var?
They are both variables. But $var is a variable with a fixed name. $$var is a variable who’s
name is stored in $var. For example, if $var contains "message", $$var is the same as
$message.
51. What are the encryption techniques in PHP
MD5 PHP implements the MD5 hash algorithm using the md5 function, eg :
$encrypted_text = md5 ($msg);

mcrypt_encrypt :- string mcrypt_encrypt ( string $cipher , string $key , string $data

Encrypts plaintext with given parameters


52. What is the use of the function htmlentities?
htmlentities Convert all applicable characters to HTML entities This function is identical to
htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML
character entity equivalents are translated into these entities.
53. How to delete a file from the system
Unlink() deletes the given file from the file system.
54. How to get the value of current session id?
session_id() function returns the session id for the current session.
252 Chapter B. Interview Questions

55. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

• Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both.


• mysql_fetch_object ( resource result ) Returns an object with properties that correspond
to the fetched row and moves the internal data pointer ahead. Returns an object with
properties that correspond to the fetched row, or FALSE if there are no more rows
mysql_fetch_row() fetches one row of data from the result associated with the specified

result identifier. The row is returned as an array.
Each result column is stored in an array offset, starting at offset 0.
56. What are the different types of errors in PHP ?
Here are three basic types of runtime errors in PHP:
• Notices: These are trivial, non-critical errors that PHP encounters while executing a
script - for example, accessing a variable that has not yet been defined. By default,
such errors are not displayed to the user at all - although you can change this default
behavior.
• Warnings: These are more serious errors - for example, attempting to include() a file
which does not exist. By default, these errors are displayed to the user, but they do
not result in script termination. Fatal errors: These are critical errors - for example,
instantiating an object of a non-existent class, or calling a non-existent function. These
errors cause the immediate termination of the script, and PHP’s default behavior is to
display them to the user when they take place.
57. what is sql injection ?
SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in
Web applications
58. What is x+ mode in fopen() used for?
Read/Write. Creates a new file. Returns FALSE and an error if file already exists
59. How to find the position of the first occurrence of a substring in a string
strpos() is used to find the position of the first occurrence of a substring in a string
60. Distinguish between urlencode and urldecode?
This method is best when encode a string to used in a query part of a url. it returns a string in
which all non-alphanumeric characters except -_. have replece with a percentege(%) sign .
the urldecode −>Decodes url to encode string as any %and other symbole are decode by the
use of the urldecode() function.
61. How can we know the number of days between two given dates using PHP?
The start date and end date can be first found as shown below:
$date1= strotime($start_date);
$date2= strotime($end_date);
$date_diff = (($date1)- ($date2)) / (60*60*24)

62. Write the statements that are used to connect PHP with MySQL
The statements that can be used to connect PHP wil MySQL is:
<?
$conn = mysql_connect('localhost');
echo $conn;
?>
This statement gets the resource of the localhost. There are other different ways with
<?
mysql_connect('db.domain.com:33306','root','user');
mysql_connect('localhost:/tmp/mysql.sock');
253

mysql_connect('localhost','rasmus','foobar',
true,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
?>

Вам также может понравиться