Академический Документы
Профессиональный Документы
Культура Документы
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
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
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
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.
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.
• 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.
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 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
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
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 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
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.8: Destination Folder dialog for the Apache installation files
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.
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.
3. Click Next. The License Terms dialog appears as shown in Figure 1-12.
1.4 Installation of Web Servers 25
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.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
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.
ServerName somehost.somedomain.com
#ServerName somehost.somedomain.com
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.
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.
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):
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
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.23: The Control Panel starts and stops the components
34 Chapter 1. Introduction to Web Technologies
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)
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
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)
9. WampServer installation has completed now and setup will guide you for Apache configura-
tions in the next steps.(Figure 1-32)
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
• SMTP: localhost
• Email: Your email address.
Click “Next” after putting the above values for the installation final dialog.(Figure 1-34)
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
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 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\").
<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>
Locate the following lines (around Line 69) that define the HTTP connector, and change
port="8080" to port="9999".
<Context reloadable="true">
......
......
</Context>
<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.
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>
<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>
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:
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
<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>
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.
Attributes:
Example:
Following is the example of inline CSS based on above syntax:
Attributes:
Attributes associated with < style > elements are:
Example:
Following is the example of embed CSS based on above syntax:
<head>
<style type="text/css" media="all">
h1{
color: #36C;
}
</style>
</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
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:
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>
<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>
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.
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
*********************
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.
<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>
local
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>
<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>
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>
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>
<html>
<head>
<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
64 Chapter 2. Java Script
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
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
Here is how you can create a Date object for each of the ways above:
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)
<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>
<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>
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
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
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.
[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,.
Symbol Description
() Grouping characters together to cre-
ate a clause. May be nested.
72 Chapter 2. Java Script
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+$)/
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
}
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>
<!--
// 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>
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
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.
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.
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.
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
}
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.
• 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)
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.
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>
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
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 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.
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
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.
• 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.
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
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
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>");
}
}
Exercise
1. Explain Java Servlet Architecture.
2. Explain in detail about servlet life cycle.
3.13 Exercise 99
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.
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 -
You can write the XML equivalent of the above syntax as follows -
<jsp:declaration>
code fragment
</jsp:declaration>
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 -
You can write the XML equivalent of the above syntax as follows -
<jsp:expression>
expression
</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 -
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
You can write the XML equivalent of the above syntax as follows -
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 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" />
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 -
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>
<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
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
Keep in mind, neither the name nor the value should contain white space or any of the following
characters -
[ ] ( ) = , " / ? @ : ;
cookie.setMaxAge(60*60*24);
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>
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
<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.
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.
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 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-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.
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’
C:\>
C:\>cd Program Files\MY SQL\bin
C:\>Program Files\MySql\bin>
4.10 JSP Database Connection 115
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.
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
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>
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>
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"
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.
*********************
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
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
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.
<h3>Welcome!</h3>
<?php
echo "<p>Welcome to PHP !</p>";
?>
126 Chapter 5. Introduction to PHP
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 !";
?>
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>
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.";
%>
<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>
<?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.
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:
To use echo(), just provide it with an argument just as was done with print():
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.
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);
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
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
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.
Valid Invalid
name,_name 2name
x_y x&y
xnoty x!y
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.”
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;
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
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.
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);
Data Types
PHP supports eight primitive data types with three classifications.
$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.
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"
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
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.
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.
<?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.
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
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
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;
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
$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
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
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.
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;
?>
<?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 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.
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.
<?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
<?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";
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))
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");
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 />";
}
print_r( $array );
Example:
print_r($student);
The following example adds two branches to the branch of the $branchs array:
The following example adds two more branchs onto the $branchs array:
The following example removes the first branch from the $branchs array:
The following example removes the last branch from the $branchs array:
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:
$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:
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.
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:
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;
?>
<?php
$uname = "dontap";
if (strlen($uname) <= 10)
echo "uname is too short!";
else
echo "Uname is valid!";
?>
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:
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:
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:
<?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.
<?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');
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));
?>
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
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 ]]]]]] )
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'];
?>
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
$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;
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.
header("Content-Disposition:attachment;filename=".$output.".pdf");
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();
?>
:::::: 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.
(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 )
<?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
<?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();
?>
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
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
<?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.
?>
<?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());
?>
<?php
echo $_ENV['COMPUTERNAME'] . "<br />"; // Echoes COMPUTER-2339.
$_ENV['COMPUTERNAME'] = "dp";
echo $_ENV['COMPUTERNAME'] . "<br />"; //Echoes the new COMPUTERNAME.
?>
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() ] )
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 )
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:
<?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.
<?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.
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()).
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).
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:
Where version is the XML version and encoding specifies the character encoding used in the
document.
XML Syntax 179
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>
• 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>
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.
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.
Syntax
Basic syntax of a DTD is as follows:
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>
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>
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:
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:
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:
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>
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:
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
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.
• 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.
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
<xsl:template match="Title">
<H1>
<xsl:apply-templates/>
</H1>
</xsl:template>
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>
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
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.
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.
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
<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
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’];.
<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>
<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>
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’];.
<html>
<head>
7.1 Understanding Common Form Issues 199
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.
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"){
<html>
<head>
<title>Personal information</title>
</head>
<body>
7.1 Understanding Common Form Issues 203
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
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
<html>
<head>
<title>Complete Information</title>
</head>
<body>
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
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"){
}
?>
</body>
</html>
Figure 7.11: Name with lessthan 6 characters and with out password
208 Chapter 7. Creating and Using Forms
<?php
function test() {
$foo = "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
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();
?>
<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>
• 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
<?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");
}
}
?>
::::::::::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] )
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:
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.
<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>
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
<?php
while($info = mysql_fetch_array($result)){
Print "<tr><td> ".$info[0] . " </td>";
Print "<td> ".$info[1] . " </td>";
Print "<td> ".$info[3] . " </td></tr>";
}
?>
//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>
In the above script we collect values from form and validate form values with database values.
7.6 Basic Database Concepts 219
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
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
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.
if($result){
echo "Data is successfully updated..";
}
?>
:::::::::: OUTPUT ::::::::::
Data is successfully updated..
</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
if($result){
throw new exception ("Password is successfully changed..");
}
if (!$goodtogo){
?>
<form action="<?php $_SERVER["PHP_SELF"];?>" method="post">
<p>Fill the following form:</p>
mysql_close()
Close MySQL connection
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
mysql_query()
Send a MySQL query
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");
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.
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
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.
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
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.
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:
• 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"
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Handling the server response 231
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.
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.
...
onclick="makeRequest('test.xml')">
...
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.
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
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.
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;
}
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
login.php
<?php
session_start();
if($_SERVER["REQUEST_METHOD"]=="POST"){
include("config.php");
$uname=$_POST["Username"];
$pwd=$_POST["Password"];
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");
</body>
</html>
Registration form
<?php
// Include config file
require_once 'config.php';
// 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 = ?";
// Set parameters
$param_username = trim($_POST["username"]);
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']);
}
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.';
}
}
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a pass
// 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
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?
echo $_COOKIE["user"];
19. How to create a session? How to set a value in session ? How to Remove data from a
session?
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"];
}
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
250 Chapter B. Interview Questions
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
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);
?>