Amazon_kindle -wt Textbook As Per Jntua R15.pdf

  • Uploaded by: Janardhan Madugula
  • 0
  • 0
  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Amazon_kindle -wt Textbook As Per Jntua R15.pdf as PDF for free.

More details

  • Words: 65,840
  • Pages: 254
Web and Internet Technologies (As per the Syllabus of JNTUA, JNTUH, and JNTUK)

Sreedhar Jinka | Praveen Kumar Donta | BaijNath Kaushik

2

3

About Authors Dr. Sreedhar JinkaCurrently working as a Associate Professor in the Department of Computer Science 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 Technological University Kakinada which is a largest technical university in India. Worked as Principal, Vice Principal, HoD, Professor, Associate Professor, Assistant Professor in various premier institutions. He completed Master of Technology in Andhra University College of Engineering Vizag, Andhra Pradesh, India. He is a member of Computer Society of India, IAENG and GSRD. He is a Convener for National Conference and Workshops and Organizer for International Conferences. He has attended good number of workshops on Internet of Things, Big Dat Analytical Tools, Machine Learning Techniques, Python and so on and also he has organized good number of workshops on Big Data with Hadoop and R Programming, Linux Programming and so on. Apart from teaching he was involved in Research and Development activities and as part of this he has published more than 20 research articles in National and International Conferences and Journals. He also published "Cracking The C Interviews" in LAP-LAMBERT Publishing from Germany. Interested subjects are Programming in C, C++, JAVA, Python, PHP & R, Operating Systems, Compiler Design, Formal Languages and Automata Theory, Algorithms, Storage Area Networks and Big Data. Research areas are Big Data Analytics. Praveen Kumar Donta, Currently Ph. D Research scholar (Full-Time) in Indian Institute of Technology(Insian School of Mines), Dhanbad from the Department of Computer Science & Engineering. He is Former Assistant professor at Bapatla Engineering College, Bapatla, AP , Sree Venkateswara College of Engineering, Nellore, AP and Sri Venkatesa Perumal College of Engineering and Technology, Puttur, AP. He received Master in Technology and Bachelor in Technology JNTUA Ananthapuramu. He had certificates like PGDCA from Ministry of HRD recognized institute, Technical Teacher Training from NITTTR, Chennai , Basics of Computer from NIIT, Big Data Analytics With Hadoop and RHadoop. He Published International journal and International conference proceedings in IEEE, ACM and Springer. He also published "Cracking The C Interviews" in LAP-LAMBERT Publishing from Germany. Given FDP and seminars on Big data analytics in various colleges in AP. He also given placement oriented training in various engineering colleges in AP. He is a member of SWIDC, CSTA, UACEE, IAENG and Swecha. Interested subjects are Programming in C, C++, JAVA, Python, PHP & R, Operating Systems, Algorithms, Storage Area Networks and Big Data. Research areas are Big Data Analytics. Dr. BaijNath Kaushik have completed Ph.D. in CSE from Indian Institute of Technology (Indian School of Mines, Dhnabad), March, 2016. He have done Master of Technology (Information Technology) from Guru Gobind Singh Indraprastha University, New Delhi, 2009. He have done B.E. in CSE from Nagpur University, 1997. He proven track record in teaching (19 Years), research (2 Science Citation Index, 6 Scopus and overall, 2 SCI under review, total 32+ publications), sound theoretical and extensive research back ground makes me excellent match for the academic environment. Also, the role excites me because he love to learn new technology and skills to impart knowledge to the students. He know that the students will take benefits from knowledge and wisdom for their successful orientation towards their goal achievements.

Contents

1

Introduction to Web Technologies ...................................................... 13 Working of Internet 13 Client-Server ........................................................................................................................13 World Wide Web(WWW) 14 Hyper Text Markup Language .........................................................................................15 Uniform Resource Locator ................................................................................................15 Hyper Text Transfer Protocol .............................................................................................15 Web Servers 17 Apache Web Server ..........................................................................................................18 Internet Information Server (IIS) .......................................................................................18 XAMPP (Bundle Server) .....................................................................................................19 WAMP (Bundle Server) ......................................................................................................20 Installation of Web Servers 20 Installing Apache and PHP on Windows .......................................................................20 Installing Apache for Linux ...............................................................................................28 Installing IIS and PHP on Windows ...................................................................................29 Installing a XAMPP on Linux ..............................................................................................30 Installing XAMPP on Windows .......................................................................................... 31 Installing WAMP ..............................................................................................................................34 Apache Tomcat.............................................................................................................................39 Install Tomcat 7 ...................................................................................................................40 Hypertext Markup Language

42

HTML5 47 HTML5 Advantages for End User ..................................................................................... 47 New Elements included in HTML5 ................................................................................... 47 New Form Elements in HTML5 ..........................................................................................49

New Input Types introduced in HTML5 ...........................................................................50

XHTML

50

CSS

51

1.9 1.9.1

CSS3 55 New Features in CSS3 ........................................................................................................56

1.10

Exercise

2

Java Script ............................................................................................. 57 JavaScript Datatypes

56

58

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

3

DHTML with JavaScript

75

Exercise

75

Servlets................................................................................................... 77 Common Gateway Interface

78

Servlet Tasks

78

Servlets - Life Cycle Architecture

79 80

Servlet API

80

Reading Servlet Parameters

82

Reading Initialization Parameters

84

HTTP Request 86 Methods to read HTTP Header ........................................................................................ 87 HTTP Header Request Example .......................................................................................88

HTTP Response 89 Methods to Set HTTP Response Header .........................................................................90 Servlets - Cookies Handling 92 The Anatomy of a Cookie ................................................................................................92 Servlet Cookies Methods ..................................................................................................92 Setting Cookies with Servlet .............................................................................................93

4

Servlets - Session Tracking

95

Accessing a Database using Servlet

97

Exercise

98

Java Server Page-JSP ......................................................................... 101 JSP - Architecture

101

JSP Processing

102

JSP Declarations

103

JSP Expression

103

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

5

compare JSP and servlet

119

Exercise

120

Introduction to PHP ............................................................................. 121 Server Side Programming 121 Introduction to PHP 123 Difference between HTML & PHP..................................................................................124 Features of PHP.................................................................................................................124 The anatomy of a PHP Page 125 Embedding PHP Code in Your Web Pages .................................................................125

Commenting Your Code ................................................................................................127 Outputting Data to the Browser ....................................................................................128

Identifiers

130

Variables 130 Variable scope .................................................................................................................131 Variable variables ............................................................................................................132 Constants

133

Data Types 134 Scalar Data Types ............................................................................................................134 Compound Data Types ..................................................................................................135 Expressions

135

Operators 136 Arithmetic Operators.......................................................................................................136 Assignment Operators ....................................................................................................136 Bitwise Operators .............................................................................................................137 Comparison Operators ...................................................................................................138 Error Control Operators ...................................................................................................138 Execution Operators........................................................................................................138 Incrementing/Decrementing Operators .....................................................................139 String Operators................................................................................................................139 Logical Operators ............................................................................................................139 Array Operators ................................................................................................................139 Operator Precedence ....................................................................................................140 Operator Associativity .....................................................................................................140 Statements 141 Conditional Statements ..................................................................................................141 Looping Statements ........................................................................................................143 return ..................................................................................................................................148 require ................................................................................................................................148 include ...............................................................................................................................148 Arrays 149 Creating Arrays.................................................................................................................149 Accessing Array Elements ..............................................................................................150 Outputting an Array ........................................................................................................151 Adding and Removing Array Elements .......................................................................151 Searching an Array ..........................................................................................................152 Sorting an Array ................................................................................................................153 Reversing Array Element Order .....................................................................................153 Strings 153 Single-Quoted Strings ......................................................................................................154 Double-Quoted Strings ...................................................................................................154 Here Documents (heredocs) .........................................................................................154 String Manipulation Functions........................................................................................155 Regular Expressions 156 Character Classes............................................................................................................156 Functions 157 Pre-define Functions ........................................................................................................157

User-Defined Functions ...................................................................................................157

Programming Exercise

160

Using Cookies 162 Setting Cookies.................................................................................................................162 Reading Cookies..............................................................................................................163 Deleting Cookies ..............................................................................................................163 Using HTTP Headers 164 Redirecting to a Different Location ..............................................................................164 Sending Content Types Other Than HTML ...................................................................166 Forcing File “Save As” Downloads ................................................................................166 Using Sessions 167 Setting Sessions .................................................................................................................167 Reading Sessions ..............................................................................................................168 Deleting Sessions ..............................................................................................................168 Storing Simple Data Types in Sessions...........................................................................168 Storing Complex Data Types in Sessions ......................................................................169 Authenticating Your Users

170

Using Environment and Configuration Variables 171 Reading Environment Variables....................................................................................171 Reading Configuration Variables .................................................................................171 Setting Environment Variables.......................................................................................171 Setting Configuration Variables ....................................................................................172 Working with Date and Time 172 5.21.1 time() ..................................................................................................................................172 5.21.2 date() .................................................................................................................................172 checkdate()......................................................................................................................173 mktime().............................................................................................................................173 strtotime() ..........................................................................................................................174 getdate() ...........................................................................................................................174 strptime()............................................................................................................................174

6

Programming Exercise

175

Exercise

175

XML- eXternal Markup Language..................................................... 177 XML Syntax 178 XML Declaration ...............................................................................................................178 Tags and Elements ...........................................................................................................179 Syntax Rules for Tags and Elements ..............................................................................179 Element Syntax: ................................................................................................................179 Nesting of elements: ........................................................................................................179 Attributes

180

Syntax Rules for XML Attributes 180 Attribute Types ..................................................................................................................181 XML Document Type Declaration 181 Internal DTD .......................................................................................................................182

External DTD ......................................................................................................................183

XML-Schemas 184 Definition Types.................................................................................................................185 Document Object Model

186

XML - Parsers

187

Extensible Stylesheet Language (XSL) 188 XSL Transformations..........................................................................................................189 News Feed 190 RSS-(Really Simple Syndication) ....................................................................................191 ATOM .............................................................................................................................................. 191 RSS vs ATOM.................................................................................................................................. 192 Exercise

7

193

Creating and Using Forms.................................................................. 195 Understanding Common Form Issues 195 GET vs. POST ......................................................................................................................197 Validating form input .......................................................................................................199 Working with multiple forms ...........................................................................................202 Redisplaying Forms with Preserved Information and Error Messages ....................206 Global & Superglobal variables

208

Preventing Multiple Submissions of a Form 209 Preventing Multiple Submissions on the Server Side ..................................................209 Preventing Multiple Submissions on the Client Side...................................................210 Handling Special Characters

211

File Uploads

212

Basic Database Concepts 212 Connecting to a MySQL Database..............................................................................212 Querying the Database..................................................................................................213 Retrieving and Displaying Results..................................................................................216 Deleting Data ...................................................................................................................219 Modifying Data ................................................................................................................220 MySQL Functions in php 222 mysql_connect() ..............................................................................................................222 mysql_close() ....................................................................................................................223 mysql_select_db() ............................................................................................................223 mysql_query() ...................................................................................................................223 mysql_fetch_array() .........................................................................................................224 mysql_fetch_row() ...........................................................................................................224 mysql_fetch_assoc() ........................................................................................................225 More MySQL functions ....................................................................................................225 Model View Controller(MVC) Architecture

225

Exercise

226

8

AJAX-Asynchronous JavaScript And XML . . . . . . . . . . . . . . . . . . . . . 229

8.1

How to make an HTTP request

229

8.2

Handling the server response

231

8.3

Working with the XML response

231

8.4

AJAX-Call Back

232

8.5

Exercise

233

9

Web services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

235

9.1

Web service Architecture

235

9.2

Types of Web services

237

9.3 9.3.1

Java Web Services Example: Hello World JAX-WS Application . . . . . . . . . . . . . . . . . . . . . . . . . . .

237 237

9.4 9.4.1

WSDL – Web services description language WSDL Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

238 238

9.5

SOAP Introduction

239

9.6

Exercise

239

A

Sample Source Codes for Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . .

241

A.1 A.1.1 A.1.2 A.1.3

Sample Source Codes Config.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . login.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . logout.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

241 241 241 242

B

Interview Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

247

1. Introduction to Web Technologies

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

Working of Internet Although the physical network connections, the hardware communication devices and the software communication protocols are required for communication across the Internet, the application software provide useful functionality. In a network application, two application programs participate in any communication: one application initiates communication and the other accepts it. This is known as the Client-Server interaction. This is the methodology used for internet communication. Client-Server Client and Server are two applications involved in communication. These components work together over a network. It involves the client requesting serve from the server. The Server provides the requested service. The typical features of the Client are: • It is front-end of an application. It • manages user-interface portion. • It validates data entered by the user. • It dispatches requests to server program. The typical features of the Server are: • Performs a back-end task. • Receives requests from clients. • Executes database retrievals and updates. • Manages data integrity.

14

Chapter 1. Introduction to Web Technologies • Dispatches response to clients.

Web Browsers A Web browser is a software program that is used to access the World Wide Web(WWW). It allows users to view Web pages and navigate between them. Examples of Web Browsers are : Mozilla, Microsoft Internet Explorer, Opera, Crome, Netscape etc,. Web Browsers are known as Universal Clients because they act as the common Client for all Web-based applications. They are the Web Clients that request services from a Web Server, Which is located some where on the Internet or Intranet. Server Program & Server System Genrally, the term ‘Server’ refers to a program that waits for a request and provides service. However, a Computer that runs many such Server programs is also known as a Server. Computers that have fast CPUs, large memories and powerful operating systems are also called Server Machines(or Server Systems or Server Computers). “A Server is the program that provides Service to a client”. Working of Server A server offers one or more Services to clients. By default, it does not do any processing until a client sends in a request. It waits for a client to make a request. This is known as ‘listening’ mode of the server. A typical client server interaction happens as follows: 1. The client sends a request for a server. 2. On receiving a request, the service assigns one of the threads in the pool to process the task and continues to wait for further request. 3. The thread executes the code for the requested service. 4. After execution, it sends the response back to the client. 5. It then returns to the thread pool.

Figure 1.1: Working of Server

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

1.2 World Wide Web(WWW)

15

A Web Site is resides on Server computers that are located in around the world. Information on the WWW is always accessible, from anywhere in the world. The basic architecture is characterized by a Web Browser that displays information content and a Web Server that transfer’s information to the client. This architecture depends on three key standards for creating, publishing and finding Web documents on the Web: HTML: Hyper Text Markup Language For creating and editing document content. URL: Uniform Resource Locator For locating resource on the Internet. HTTP: Hyper Text Transfer Protocol For transfer the data. HTML: Hyper Text Markup Language HTML is the authoring language used to create documents on the WWW. HTML makes documents readable across variety of computing platforms. More refer section1.5 URL: Uniform Resource Locator URL is the unique address that identifies each web page or a resource on the Internet. It indicates where the web pages is stored on the Internet. URL is the standard way of addressing resources on the Internet that are part of WWW. It supplies the Internet Address of a resource on the WWW, alone with protocol by which the resource is accessed. URLs are used by Web Browsers to connect to a specific server and to get a specific document or page on the Web. The URL looks like

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

16

Chapter 1. Introduction to Web Technologies • Stateless protocol • Does not define how network connection is initiated or managed • Standardized.

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

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

Web Servers

17

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

HTTP/1.0 200 OK Client. The HTTP error codes are standardized. Some of the commonly found error codes: The error or success code of the HTTP response are standardized in the following manner: HTTP/1.0 404 Page Not Found HTTP/1.0 500 Internal Server Error

1XX 2XX 3XX 4XX 5XX

Indicates informational message only. Indicates success of some kinds. Redirects the Client to another URL. Indicates an error on Client’s port. Indicates an error on Server’s port

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

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

18

Chapter 1. Introduction to Web Technologies

Web Server program. Examples of Web Servers: 1. Apache Web Server 2. Microsoft Internet Information Server (IIS) 3. XAMPP (Bundle server) 4. WAMP (Bundle server) Apache HTTP Server The Apache HTTP Server, commonly referred to as Apache, is a web server program notable for playing a key role in the initial growth of the World Wide Web (WWW). It became the first web server software to exceed the 100 million web site mile stone. Typically Apache is run on a Unix-like Operating system, and was developed for use on Linux. Apache is developed and maintained by an Open community of developers under the support and approval of the Apache Software Foundation (ASF). The application is available for wide variety of operating system, including Unix, Free BDS, Solaris, Linux, Novel Netware, OSX, Microsoft Windows, OS/2 etc., Released under the Apache license, Apache is open-source software. The main design goal of Apache is not to be the fastest Web server, Apache does have performance similar to other “high-performance” Web Servers. Instead of implementing a single architecture Apache provide a variety of Multi Processing Modules (MPMs) which allow Apache to run process-based, where compromises in performance need to be made, the design of Apache is to reduce latency and increase throughput, relative to simply handling more requests, thus ensuring consistent and reliable processing or requests within reasonable time frames. Features of Apache • It implemented as compiled modules which extend the core functionality, thus the range from server-side programming support to authentication scheme. • Password-protected pages for a multitude of users(It supports password authentication and digital certificate authentication). • Customized error pages. • Display of code in numerous levels of HTML, and the capability to determine at what level the browser can accept the content. • Virtual hosting allows one Apache installation to serve many different actual Websites. • Usage and error logs in multiple and customizable formats • DirectoryIndex directives to multiple files.

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

1.3 Web Servers

19

Features:

IIS has a modular architecture. Modules, also called extensions, can be added or removed individually 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 requestingprocessing pipeline (Such as compression responses, performing pre-compression of static content.) • Caching Module: Used to perform tasks related to caching in the requesting-processing pipeline (Such as storing processed information in the memory on the server and using cached content in subsequent request for the same resource.) • Logging and Diagnostics Module: Used to perform tasks related to Logging and Diagnostics in the requesting-processing pipeline (Such as passing information and processing status to HTTP.sys for logging, reporting events, and tracking requests currently executing in worker processes.) • IIS 7.5 includes additional security features: Client-certificate mapping, IP security, Request filtering, URL authentication. XAMPP (Bundle Server) XAMPP is a free and open-source cross platform Web Server Solution stack package, consisting mainly of Apache HTTP Server, MySQL database, and interpreter for scripts written in the PHP and Perl programming languages. X: Cross-Platform A: Apache M: MySQL P: PHP P: Perl Officially, XAMPP’s designers intended it for use only as a development tool, to allow Web site designers and programmers to test their work on their own computer without any access to the Internet. To make this as easy as possible many important security features are disabled by default. XAMPP sometimes used to actually Server Web Pages on the World Wide Web. Note: XAMPP is also provided support for creating and manipulating databases in MySQL and SQL Lite among others. Benifits

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

20

Chapter 1. Introduction to Web Technologies

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

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

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

1.4 Installation of Web Servers

Figure 1.4: Apache license terms and conditions for use

Figure 1.5: Apache HTTP Server information

21

22

Chapter 1. Introduction to Web Technologies

Figure 1.6: Server Network Information dialog

Figure 1.7: Selecting a setup type

1.4 Installation of Web Servers

Figure 1.8: Destination Folder dialog for the Apache installation files

Figure 1.9: “Ready to Install” dialog

23

24

Chapter 1. Introduction to Web Technologies

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

Figure 1.10: Apache’s default index page after installation

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

Figure 1.11: The PHP MSI installer 3. Click Next. The License Terms dialog appears as shown in Figure 1-12.

1.4 Installation of Web Servers

25

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

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

26

Chapter 1. Introduction to Web Technologies

Figure 1.14: The Web Server Setup dialog

Figure 1.15: Selecting the Apache install path

1.4 Installation of Web Servers

27

Figure 1.16: The Installation Options dialog

9. Click Install on the “Ready to install” screen to confirm the installation. 10. Click Yes to confirmconfiguring Apache when the dialog shown in Figure 1-17 appears.

Figure 1.17: Dialog confirming that the installer will configure Apache

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

28

Chapter 1. Introduction to Web Technologies

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

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

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

You do not want it to look like this: #ServerName somehost.somedomain.com

3. Save the file.

Installation of Web Servers

29

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

The configuration script will run through its process of checking your configuration and creating makefiles and then will put you back at the prompt. 8. Type make and press Enter. This second step of the installation process will produce many lines of output on your screen. When it is finished, you will be back at the prompt. 9. Type make install and press Enter. This final step of the installation process will produce many lines of output on your screen. When it is finished, you will be back at the prompt. Now, to get a basic version of PHP working with Apache, all you need to do is to make a few modifications to the httpd.conf file. Configuring Apache to Use PHP The installation process will have placed a module in the proper place within the Apache directory structure. Now you must make some modifications to the httpd.conf file before starting up Apache with PHP enabled. 1. Open the httpd.conf file in your text editor of choice. 2. Look for the following line, which will have been inserted into the file by the installation process: LoadModule php6_module modules/libphp6.so

You want this line to be uncommented, so ensure that it is (as shown). 3. Look for the following lines: # AddType allows you to add to or override the MIME configuration # file mime.types for specific file types. #AddType application/x-tar .tgz

4. Add to these lines the following: AddType application/x-httpd-php .phtml .php

5. Save and close the httpd.conf file. Installing IIS and PHP on Windows Microsoft took another major step towards the seamless operation of PHP and IIS by launching the Microsoft Web Platform Installer. This installation solution makes it easy to install a wide variety of web development stacks, IIS and PHP included. To install PHP and IIS on your Windows 7,

30

Chapter 1. Introduction to Web Technologies

Vista, Server 2003, or Server 2008 machines, head over to http://php.iis.net and click the giant Install PHP button. Presuming you haven’t already installed the Microsoft Web Platform Installer, you’ll next be prompted to do so. Per usual, you’ll need administrative privileges in order to run this installer. Once downloaded, you’ll be prompted to install PHP. The version at the time of this writing was a bit behind the curve (5.2.14), but it should nonetheless suffice for you to work through the vast majority of examples found in this book. Click the Install button and then read and agree to the license terms to complete the process. Believe it or not, once the installation process is complete, PHP has been successfully configured to run on your machine. At the time of this writing the Web Platform Installer console is unable to uninstall PHP, meaning you’ll need to use Windows’ native program management tool to do so manually. On Windows 7, this tool can be accessed by clicking the Uninstall a program option within the control panel. Installing a XAMPP on Linux If you know much about Linux, you may have already set up and installed PHP and MySQL. If not, your best bet is probably to look at XAMPP for Linux, which is available at http://apachefriends.org/en/xampplinux.html. The process is relatively simple. After downloading, go to a Linux shell and log in as the system administrator (root) by typing: su

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

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

You should now see something like this on your screen: Starting XAMPP 1.6.8a... LAMPP: Starting Apache... LAMPP: Starting MySQL... LAMPP started. Ready. Apache and MySQL are running.

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

1.4 Installation of Web Servers

31

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

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

32

Chapter 1. Introduction to Web Technologies

Figure 1.20: The Xampp Setup Wizard

Figure 1.21: Select the installation directory

1.4 Installation of Web Servers

Figure 1.22: Choose your installation options

Figure 1.23: The Control Panel starts and stops the components

33

34

Chapter 1. Introduction to Web Technologies the services, as well as aid in their configuration.

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

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

1.4 Installation of Web Servers

Figure 1.25: WampServer 2 Setup Wizard

Figure 1.26: License Agreement

35

36

Chapter 1. Introduction to Web Technologies

Figure 1.27: Select Destination Location of WampServer

Figure 1.28: Select Additional Tasks

1.4 Installation of Web Servers

Figure 1.29: WampServer 2.1d Ready to Install

Figure 1.30: WampServer Installing

37

38

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

Figure 1.31: Choice of Default Browser 9. WampServer installation has completed now and setup will guide you for Apache configurations in the next steps.(Figure 1-32)

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

1.4 Installation of Web Servers

39

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

Figure 1.34: PHP Mail Parameters 12. You have successfully installed WampServer 2.1 d along with Apache, MySql, PHP, phpMyAdmin and SqlBuddy at your computer. Click “Finish” to start WampServer along with other services. Leave “Launch WampServer 2 now” check-box checked to start WampServer automatically after installation.(Figure 1-35) Apache Tomcat It is an application server or web server or servlet container developed by the Apache Software Foundation (ASF) and released under the Apache License version 2. HTTP web servers provide an environment for Java code to run in. It includes tools for configuration

40

Chapter 1. Introduction to Web Technologies

Figure 1.35: WampServer 2 Setup Wizard Completion and management, but can also be configured by editing XML configuration files. Most of the modern Java web frameworks are based on servlets and Java Server Pages and can run on Apache Tomcat, for example Struts, Java Server Faces(JSF), Spring, etc. Install Tomcat 7 There are certain steps we must follow for configuring Apache Tomcat 7. Step 1: Download and Install Tomcat (a) Go to http://tomcat.apache.org/download-70.cgi then go to the Binary Distribution/Core/ and download the "zip" package (for example "apache-tomcat-7.0.40.zip", about 8MB). (b) Now unzip the downloaded file into a directory of our choice. Don’t unzip onto the dekstop (since its path is hard to locate). I suggest using "e:\myserver". Tomcat will be unzipped into the directory "e:\myserver\tomcat-7.0.40". Step 2: Check the installed directory to ensure it contains the following sub-directories: • bin folder • logs folder • webapps folder • work folder • temp folder • conf folder • lib folder Step 3 Now, we need to create an Environment Variable JAVA_HOME. We need to create an environment variable called "JAVA_HOME" and set it to our JDK installed directory. (a) To create the JAVA_HOME environment variable in Windows XP/Vista/7 we need to push the "Start" button then select "Control Panel" / "System" / "Advanced system

Installation of Web Servers

41

settings". Then switch to the "Advanced" tab and select "Environment Variables" / "System Variables" then select "New" (or "Edit" for modification). In "Variable Name", enter "JAVA_HOME". In "Variable Value", enter your JDK installed directory (e.g., "c:\Program Files\Java\jdk1.7.0_xx"). (b) For ensuring that it is set correctly, we need to start a command shell (to refresh the environment) and issue: set JAVA_HOME JAVA_HOME=c:\Program Files\Java\jdk1.7.0_{xx} ⇐ Check that this is OUR JDK installed directory (c) Sometimes we need to set JRE_HOME also. So for creating JRE_HOME we need to use the same procedure. Push the "Start" button then select "Control Panel" / "System" / "Advanced system settings". Then switch to the "Advanced" tab and select "Environment Variables" / "System Variables" then select "New" (or "Edit" for modification). In "Variable Name", enter "JRE_HOME". In "Variable Value", enter your JRE installed directory (e.g., "C:\Program Files\Java\jre7\"). Step 4: Configure Tomcat Server The configuration files of the Apache Tomcat Server are located in the "conf" sub-directory of our Tomcat installed directory, for example "E:\myserver\tomcat7.0.40\conf". There are 4 configuration XML files: (a) context.xml file (b) tomcat-users.xml file (c) server.xml file (d) web.xml file Before proceeding, make a BACKUP of the configuration files. Step 4(a) "conf\web.xml"; Enabling a Directory Listing Again, use a programming text editor to open the configuration file "web.xml", under the "conf" sub-directory of Tomcat installed directory. We shall enable directory listing by changing "listings" from "false" to "true" for the "default" servlet. This is handy for test system, but not for production system for security reasons. Locate the following lines (around Line 103) that define the "default" servlet; and change the "listings" from "false" to "true". <servlet> <servlet-name>default <servlet-class>org.apache.catalina.servlets.DefaultServlet <param-name>debug <param-value>0 <param-name>listings <param-value>true 1 Step 4(b) "conf\server.xml file"; set the TCP Port Number The default TCP port number configured in Tomcat is 8080, you may choose any number between 1024 and 65535, which is not used by an existing application. We shall choose 9999 in this article. (For production server, you should use port 80, which is pre-assigned to HTTP server as the default port number.)

42

Chapter 1. Introduction to Web Technologies Locate the following lines (around Line 69) that define the HTTP connector, and change port="8080" to port="9999". Step 4(c) "conf\context.xml"; Enabling Automatic Reload We shall add the attribute reloadable="true" to the < Context > element to enable automatic reload after code changes. Again, this is handy for test system but not for production, due to the overhead of detecting changes. Locate the < Context > start element (around Line 19), and change it to . ...... ...... Step 4(d) (Optional) "conf\tomcat-users.xml" Enable the Tomcat’s manager by adding the highlighted lines, inside the < tomcat elements:

− users >

<user username="manager" password="xxxx" roles="manager-gui"/>

This enables the manager GUI app for managing Tomcat server. Step 5: Start Server Launch a CMD shell. Set the current directory to "\bin", and run "startup.bat" as follows: // Change the current directory to Tomcat's "bin" // Assume that Tomcat is installed in "d:\myProject\tomcat" d: // Change the current drive cd \myProject\tomcat\bin // Change Directory to YOUR Tomcat's "bin" directory // Start Tomcat Server startup

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

1.5 Hypertext Markup Language

43

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

Here 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

Heading 1

Heading 2

Heading 3

Heading 4



44

Chapter 1. Introduction to Web Technologies
Heading 5
Heading 6


Paragraph

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:

......

Break
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
is an Empty Element, meaning that it may contain attributes but it does not contain content. The
element does not have a closing tag. Horizontal Rule
The
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
element are size, width, noshade, align and color. Ex:
Formatting Elements • Two sizes bigger Bold < /B > • < I > Italic < /I > • Underline • <EM> Emphasis browsers usually display this as italics. • <STRONG> STRONG browsers display this as bold. • <STRIKE>strike-through text • places text in a big font • <SMALL> places text in a small font <SMALL> • <SUB> places text in subscript position • <SUP> places text in superscript style position Lists HTML supplies several list elements. Most list elements are composed of one or more
  • (list item) elements. Unordered List
      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:
      • List item...
      • List item...
      • List item...


      Ordered List
        Items in this list are numbered automatically by the browser.
        1. List item...
        2. List item...
        3. List item...


        Hypertext Markup Language

        45

        You have the choice of setting the TYPE Attribute to one of five numbering styles. 1 a A i I

        Arabic numbers Lower alpha Upper alpha Lower roman Upper roman

        1, 2, 3, . . . a, b, c, . . . A, B, C, . . . i, ii, iii, . . . 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).
        HTML
        Hyper Text Markup Language
        Dog
        A human's best friend!


        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 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:
        Column 1 Header Column 2 Header
        Row 1 - Col 1 Row 1 - Col 2
        Row 2 - Col 1 Row 2 - Col 2
        Row 3 - Col 1 Row 3 - Col 2


        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. <TITLE>Framed Page<TITLE>

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

        HTML5

        47

        Attributes of < Frame > SRC: Required, as it provides the URL for the page that will be displayed in the frame. NAME: Required for frames that will allow tarGETing by other HTML documents. SCROLLING: Displays a scroll bar(s) in the frame. Possible values are: NORESIZE:(Optional) Prevents viewers from resizing the frame. Forms HTML forms are used to pass the data to server. An HTML form can contain input elements like text fields, check boxes, Radio buttons, Submit button and more. A form can also contain select lists, text area, field set, legend and label elements. < INPU T > The < INPU T > element is used to select user information. An < INPU T > element can very in many ways, depending on type attribute. Types are TextField, Check box, Password, radio button, submit and more. < INPU T TY PE = T EX T > < INPU T TY PE = Radio > < INPU T TY PE = Password > < INPU T TY PE = Checkbox > < INPU T TY PE = submit > < T EX TAREA >< /T EX TAREA > It defines multi line input. < select > .. < /select > Defines a drop down list. The < Option > is sub-element in < SELECT > . This tag is used to put list in dropdown. eg: <select>

        HTML5 HTML5 was the latest version of HTML with many updates over time on HTML. The major diference between HTML and HTML5 are: HTML5 Advantages for End User HTML5 brought about a paradigm shift for both the developers and the end users. Some of the many advantages that it provides the end users are: • Mobile web development support provided by HTML5. • responsive websites. • The eradication of the need to use Adobe Flash allows developers to provide an aesthetic graphic-rich user experience. The use of JavaScript and MPEG4 in conjunction with HTML5 has made life a lot better for users. • The ability to support native audio and video elements means that the users won’t have to download additional plugins to view multimedia on your website. New Elements included in HTML5 • < article > Defines an article in a document • < aside > Defines content aside from the page content • < bdi > Isolates a part of text that might be formatted in a different direction from other text outside it

        48

        1.

        2.

        3. 4.

        Chapter 1. Introduction to Web Technologies

        Html Html5 Doctype declaration in Html is too DOCTYPE declaration in Html5 is very simple ” longer character encoding in Html is also character encoding (charset) declaration is also very simple < metacharset = ”U T F − 8” > longer Audio and Videos are integral part of HTML5 Audio and Video are not part of HTML4 e.g.
        Enter First Number
        Enter Second Number


        The HTML source code for sum.html defines a table that contains two labels and two text fields. One of the labels is Enter First Number,and the other is Enter Second Number. There is also a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to process the HTTP POST request. Add.java import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Add extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get print writer. response.getContentType("text/html"); PrintWriter pw = response.getWriter(); // Get enumeration of parameter names. Enumeration e = request.getParameterNames(); // Display parameter names and values. int sum=0; while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); sum+=Integer.parseInt(pvalue);

        84

        Chapter 3. Servlets

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

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

        Reading Initialization Parameters Syntax to provide the initialization parameter for a servlet The init-param sub-element of servlet is used to specify the initialization parameter for a servlet. <web-app> <servlet> ...... <param-name>parametername <param-value>parametervalue ...... Example of ServletConfig to get initialization parameter In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the servlet. DemoServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ServletConfig config=getServletConfig(); String driver=config.getInitParameter("driver"); out.print("Driver is: "+driver); out.close(); } }

        web.xml <web-app> <servlet>

        Reading Initialization Parameters

        85

        <servlet-name>DemoServlet <servlet-class>DemoServlet <param-name>driver <param-value>sun.jdbc.odbc.JdbcOdbcDriver <servlet-mapping> <servlet-name>DemoServlet /servlet1 Example of ServletConfig to get all the initialization parameters In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet. DemoServlet.java import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ServletConfig config=getServletConfig(); Enumeration<String> e=config.getInitParameterNames(); String str=""; while(e.hasMoreElements()){ str=e.nextElement(); out.print("
        Name: "+str); out.print(" value: "+config.getInitParameter(str)); } out.close(); } }

        web.xml <web-app> <servlet> <servlet-name>DemoServlet <servlet-class>DemoServlet <param-name>username

        86

        Chapter 3. Servlets

        <param-value>system
        <param-name>password <param-value>oracle <servlet-mapping> <servlet-name>DemoServlet /servlet1

        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 passwordprotected Web pages. Connection This header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alive means that persistent connections should be used • Content-Length This header is applicable only to POST requests and gives the size of the POST data in bytes. • Cookie This header returns cookies to servers that previously sent them to the browser. • Host This header specifies the host and port as given in the original URL. • If-Modified-Since This header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available. • If-Unmodified-Since This header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date. • Referer This header indicates the URL of the referring Web page. For example, if you are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referer header when the browser requests Web page 2. • User-Agent This header identifies the browser or other client making the request and can be used to return different content to different types of browsers.

        3.8 HTTP Request

        87

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

        88

        Chapter 3. Servlets • • • •

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

        HTTP Header Request Example Following is the example which uses getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class DisplayHeader extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "HTTP Header Request Example"; String docType = "\n"; out.println(docType + "\n" + "" + title + "\n"+ "\n" + "

        " + title + "

        \n" + "\n" + "\n" + "\n"+ "\n"); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String paramName = (String)headerNames.nextElement(); out.print("\n"); String paramValue = request.getHeader(paramName); out.println("\n"); } out.println("
        Header NameHeader Value(s)
        " + paramName + " " + paramValue + "
        \n"); }

        3.9 HTTP Response

        89

        // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

        HTTP Response A Web server responds to a HTTP request to the browser, the response typically consists of a status line, some response headers, a blank line, and the document. A typical response looks like this: HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) ... ...

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

        90

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

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

        HTTP Response

        91

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

        " + title + "

        \n" + "

        Current Time is: " + CT + "

        \n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

        92

        Chapter 3. Servlets

        Servlets - Cookies Handling Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies. There are three steps involved in identifying returning users: • Server script sends a set of cookies to the browser. For example name, age, or identification number etc. • Browser stores this information on local machine for future use. • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. The Anatomy of a Cookie Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this: HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html

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

        A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects. Servlet Cookies Methods Following is the list of useful methods which you can use while manipulating cookies in servlet. • public void setDomain(String pattern) This method sets the domain to which cookie applies, for example tutorialspoint.com. • public String getDomain() This method gets the domain to which cookie applies, for example tutorialspoint.com. • public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don’t set this, the cookie will last only for the current session.

        3.10 Servlets - Cookies Handling

        93

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

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

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

        3. Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows: response.addCookie(cookie); Example Let us modify our Form Example to set the cookies for first and last name. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        94

        Chapter 3. Servlets

        // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies Example"; String docType = "\n"; out.println(docType + "\n" + "" + title + "\n" + "\n" + "

        " + title + "

        \n" + "
          \n" + "
        • First Name: " + request.getParameter("first_name") + "\n" + "
        • Last Name: " + request.getParameter("last_name") + "\n" + "
        \n" + ""); } }

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


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

        3.11 Servlets - Session Tracking

        95

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

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

        " + title + "

        \n" + "

        Session Infomation

        \n" + "\n" + "\n" + " \n" + "\n" + " \n" + " \n" + "\n" + " \n" + " \n" + "\n" + " \n" + " \n" +

        Accessing a Database using Servlet "\n" + " \n" + " \n" + "\n" + " \n" + " \n" + "
        Session infovalue
        id" + session.getId() + "
        Creation Time" + createTime + "
        Time of Last Access" + lastAccessTime + "
        User ID" + userID + "
        Number of visits" + visitCount + "
        \n" + ""); } }

        Accessing a Database using Servlet Here is an example which shows how to access TEST database using Servlet. // Loading required libraries import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class DatabaseAccess extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // JDBC driver name and database URL static final String JDBC_DRIVER="com.mysql.jdbc.Driver"; static final String DB_URL="jdbc:mysql://localhost/TEST"; // Database credentials static final String USER = "root"; static final String PASS = "password"; // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Database Result"; String docType = "\n"; out.println(docType + "\n" + "" + title + "\n" + "\n" + "

        " + title + "

        \n"); try{ // Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Open a connection Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

        97

        98

        Chapter 3. Servlets

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

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

        3.13 Exercise 3. Explain about Request and Response in Servlet. 4. Explain session handling in Servlets with example. 5. Explain Cookie management in servlets with example.

        99

        4. Java Server Page-JSP

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

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

        102

        Chapter 4. Java Server Page-JSP

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

        Figure 4.1: Architecture of JSP

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

        JSP Declarations

        103

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

        JSP Declarations A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Following is the syntax for JSP Declarations <%! declaration; [ declaration; ]+ ... %>

        You can write the XML equivalent of the above syntax as follows <jsp:declaration> code fragment

        Following is an example for JSP Declarations <%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>

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

        You can write the XML equivalent of the above syntax as follows <jsp:expression> expression

        Following example shows a JSP Expression A Comment Test

        Today's date: <%= (new java.util.Date()).toLocaleString()%>



        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 A Comment Test

        A Test of Comments

        <%-- This comment will not be visible in the page source --%>

        A Test of Comments There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here’s a summary Syntax & Purpose 1. <%-- comment --%> A JSP comment. Ignored by the JSP engine. 2. An HTML comment. Ignored by the browser. 3. <% Represents static <% literal. 4. %> Represents static %> literal. 5. \' A single quote in an attribute that uses single quotes. 6. \" A double quote in an attribute that uses double quotes.

        JSP - Directives In this chapter, we will discuss Directives in JSP. These directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form <%@ directive attribute = "value" %>

        Directives can have a number of attributes which you can list down as key-value pairs and separated by commas. There are three types of directive tag 1. <%@ page ... %> Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. 2. <%@ include ... %> Includes a file during the translation phase. 3. <%@ taglib ... %> Declares a tag library, containing custom actions, used in the page

        4.6 JSP - Directives

        105

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

        You can write the XML equivalent of the above syntax as follows <jsp:directive.page attribute = "value" /> Attributes Following table lists out the attributes associated with the page directive 1. buffer: Specifies a buffering model for the output stream. 2. autoFlush Controls the behavior of the servlet output buffer. 3. contentType Defines the character encoding scheme. 4. errorPage Defines the URL of another JSP that reports on Java unchecked runtime exceptions. 5. isErrorPage Indicates if this JSP page is a URL specified by another JSP page’s errorPage attribute. 6. extends Specifies a superclass that the generated servlet must extend. 7. import Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes. 8. info Defines a string that can be accessed with the servlet’s getServletInfo() method. 9. isThreadSafe Defines the threading model for the generated servlet. 10. language Defines the programming language used in the JSP page. 11. session Specifies whether or not the JSP page participates in HTTP sessions 12. isELIgnored Specifies whether or not the EL expression within the JSP page will be ignored. 13. isScriptingEnabled Determines if the scripting elements are allowed for use. The include Directive The include directive is used to include a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code the include directives anywhere in your JSP page. The general usage form of this directive is as follows <%@ include file = "relative url" >

        The filename in the include directive is actually a relative URL. If you just specify a filename with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP. You can write the XML equivalent of the above syntax as follows <jsp:directive.include file = "relative url" /> The taglib Directive The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior. The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides means for identifying the custom tags in your JSP page. The taglib directive follows the syntax given below <%@ taglib uri="uri" prefix = "prefixOfTag" >

        106

        Chapter 4. Java Server Page-JSP

        Here, the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions. You can write the XML equivalent of the above syntax as follows <jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />

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

        Here values for the scope attribute can be a page, request, session or application based on your requirement. The value of the id attribute may be any value as a long as it is a unique name among other useBean declarations in the same JSP. Following example shows how to use the useBean action useBean Example <jsp:useBean id = "date" class = "java.util.Date" />

        The date/time is <%= date %>

        You will receive the following result– The date/time is Thu Sep 30 11:18:11 GST 2010

        Accessing JavaBeans Properties Along with < jsp : useBean :::> action, you can use the < jsp : getProperty =>action to access the get methods and the < jsp : setProperty => action to access the set methods. Here is the full syntax -

        <jsp:useBean id = "id" class = "bean's class" scope = "bean's scope"> <jsp:setProperty name = "bean's id" property = "property name" value = "value"/> <jsp:getProperty name = "bean's id" property = "property name"/> ........... The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean action. The property attribute is the name of the get or the set methods that shoul invoked. Following example shows how to access the data using the above syntax get and set properties Example

        4.8 JSP - Cookies Handling <jsp:useBean id = "students" class <jsp:setProperty name = "students" <jsp:setProperty name = "students" <jsp:setProperty name = "students"

        Student First Name: <jsp:getProperty name = "students"

        Student Last Name: <jsp:getProperty name = "students"

        Student Age: <jsp:getProperty name = "students"



        107 = "com.tutorialspoint.StudentsBean"> property = "firstName" value = "Zara"/> property = "lastName" value = "Ali"/> property = "age" value = "10"/>

        property = "firstName"/>

        property = "lastName"/>

        property = "age"/>

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

        JSP - Cookies Handling Cookies are text files stored on the client computer and they are kept for various information tracking purposes. JSP transparently supports HTTP cookies using underlying servlet technology.There are three steps involved in identifying and returning users • Server script sends a set of cookies to the browser. For example, name, age, or identification number, etc. • Browser stores this information on the local machine for future use. • When the next time the browser sends any request to the web server then it sends those cookies information to the server and server uses that information to identify the user or may be for some other purpose as well. The Anatomy of a Cookie Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A JSP that sets a cookie might send headers that look something like this HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html

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

        108

        Chapter 4. Java Server Page-JSP

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

        A JSP script will then have access to the cookies through the request method request.getCookies() which returns an array of Cookie objects. subsectionSetting Cookies with JSP Setting cookies with JSP involves three steps Step 1: Creating a Cookie object You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. Cookie cookie = new Cookie("key","value");

        Keep in mind, neither the name nor the value should contain white space or any of the following characters [ ] ( ) = , " / ? @ : ; Step 2: Setting the maximum age You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code will set up a cookie for 24 hours. cookie.setMaxAge(60*60*24); Step 3: Sending the Cookie into the HTTP response headers You use response.addCookie to add cookies in the HTTP response header as follows response.addCookie(cookie); Example: <% // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); %>

        4.8 JSP - Cookies Handling

        109

        Setting Cookies

        Setting Cookies

        • First Name: <%= request.getParameter("first_name")%>

        • Last Name: <%= request.getParameter("last_name")%>

        Let us put the above code in main.jsp file and use it in the following HTML page
        First Name:
        Last Name:


        Reading Cookies with JSP To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value. Example Let us now read cookies that were set in the previous example : Reading Cookies

        Reading Cookies

        <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with the this domain cookies = request.getCookies();

        110

        Chapter 4. Java Server Page-JSP

        if( cookies != null ) { out.println("

        Found Cookies Name and Value

        "); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+"
        "); } } else { out.println("

        No cookies founds

        "); } %>

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

        Reading Cookies

        <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with the this domain cookies = request.getCookies(); if( cookies != null ) { out.println("

        Found Cookies Name and Value

        "); 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( ) + "
        "); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+"
        ");

        4.9 JSP - Session

        111

        } } else { out.println( "

        No cookies founds

        "); } %>

        JSP - Session HTTP is a "stateless" protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request. Maintaining Session Between Web Client And Server Let us now discuss a few options to maintain the session between the Web Client and the Web Server: Cookies A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. This may not be an effective way as the browser at times does not support a cookie. It is not recommended to use this procedure to maintain the sessions. Hidden Form Fields A web server can send a hidden HTML form field along with a unique session ID as follows :

        This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers. This can be an effective way of keeping track of the session but clicking on a regular (< AHREF... >) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking. URL Rewriting You can append some extra data at the end of each URL. This data identifies the session; the server can associate that session identifier with the data it has stored about that session. For example, with http://skillsubsist.in/file.htm;sessionid=12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client. URL rewriting is a better way to maintain sessions and works for the browsers when they don’t support cookies. The drawback here is that you will have to generate every URL dynamically to assign a session ID though page is a simple static HTML page.

        The session Object Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across. • a one page request or • visit to a website or

        112

        Chapter 4. Java Server Page-JSP

        • store information about that user By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows<%@ page session = "false" %>

        The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession(). Here is a summary of important methods available through the session object 1. public Object getAttribute(String name): This method returns the object bound with the specified name in this session, or null if no object is bound under the name. 2. public Enumeration getAttributeNames(): This method returns an Enumeration of String objects containing the names of all the objects bound to this session. 3. public long getCreationTime(): This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. 4. public String getId(): This method returns a string containing the unique identifier assigned to this session. 5. public long getLastAccessedTime(): This method returns the last time the client sent a request associated with the this session, as the number of milliseconds since midnight January 1, 1970 GMT. 6. public int getMaxInactiveInterval(): This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. 7. public void invalidate(): This method invalidates this session and unbinds any objects bound to it. 8. public boolean isNew(): This method returns true if the client does not yet know about the session or if the client chooses not to join the session. 9. public void removeAttribute(String name): This method removes the object bound with the specified name from this session. 10. public void setAttribute(String name, Object value): This method binds an object to this session, using the name specified. 11. public void setMaxInactiveInterval(int interval): This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. Session Tracking Example This example describes how to use the HttpSession object to find out the creation time and the lastaccessed time for a session. We would associate a new session with the request if one does not already exist. <%@ page import = "java.io.*,java.util.*" %> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this Webpage. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID");

        4.9 JSP - Session String userID = new String("ABCD"); // Check if this is new comer on your Webpage. if (session.isNew() ){ title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %> Session Tracking

        Session Tracking

        Session info Value
        id <% out.print( session.getId()); %>
        Creation Time <% out.print(createTime); %>
        Time of Last Access <% out.print(lastAccessTime); %>
        User ID <% out.print(userID); %>
        Number of visits <% out.print(visitCount); %>


        113

        114

        Chapter 4. Java Server Page-JSP

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

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

        JSP Database Connection The database is used for storing various types of data which are huge and has storing capacity in gigabytes. JSP can connect with such databases to create and manage the records. Create Table In MYSQL database, we can create a table in the database with any MYSQL client. Here we are using PHPMyadminclient, and there we have an option "new" to create a new table using below screenshot. In this, we have to provide table name as guru_test, and we will create two fields’

        emp_id and emp_name. Emp_id is havingdatatype as int Emp_name is havingdatatype as varchar Another option is by using command prompt and changes to MYSQL directory: C:\> C:\>cd Program Files\MY SQL\bin C:\>Program Files\MySql\bin>

        4.10 JSP Database Connection

        115

        We can login to database as follows: C:\Program Files\MYSQL\bin>mysql -u gururoot -p Enter Password: ******* Mysql>

        Create table guru_testin the database named as GuruTestas the following on MYSQL prompt: Mysql> use GuruTest; MySql> create table guru_test( Emp_idint NOT NULL, Emp_namevarchar(11), ); Once you execute this you get the following: Query OK, 0 rows affected(0.10 sec) MySQl> select * from guru_test; Query OK, 0 rows affected(0.10 sec)

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

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

        116

        Chapter 4. Java Server Page-JSP

        Select The Select operation is used to select the records from the table. Example In this example, we are going to learn about the select operation of fetching records from guru_test table which was created in the above section. <%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> Guru Database JSP1 <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/GuruTest" user="gururoot" password="guru"/> <sql:query dataSource="${snapshot}" var="result"> SELECT * from guru_test;
        Guru ID Name
        Explanation of the code: Code Line 1: Here we are importing io, uti and SQL libraries of java. Code Line 3: Here we are importing core library of JSTL and giving its prefix as gurucore which will help to get output. Code Line 4: Here we are importing SQL library of jstl and giving its prefix as gurusql which will help to do the SQL operations. Code Line 15-17: Here using gurusql, we are connecting data source by naming variable as "guru" and driver as a JDBC driver. Also adding username and password with "gururoot" and "guru". Code Line 19-21: Here we are using sql query of the select query.

        4.10 JSP Database Connection

        117

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

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

        In this example, we are going to learn about inserting the records in the table guru_test <%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> Guru Database JSP1 INSERT INTO guru_test VALUES (3, 'emp emp3'); Explanation of the code: Code Line 19-20: Here we are inserting records into the table guru_test of GuruTestdatabase.The records inserted are: empID - 3 and empname - emp emp3.These records will be inserted in the table When you execute the code, the records are inserted into the table as guru_test ,with value 3 and emp emp3. Note: Here we are not showing the output as we are just inserting the record in the table. We can get the record using select query as ’select * from guru_test’. If the record was inserted then, we would get the value as 3 and emp3.If the record is not inserted then, 3 will not be seen in records in the table.

        Delete This is delete operation where we delete the records from the table guru_test.

        118

        Chapter 4. Java Server Page-JSP

        Example: Here we will delete query to delete the record from the table guru_test. The record which has to be deleted has to be set in variable "guruid", and the corresponding record is deleted from the database. <%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> Guru Database JSP1 DELETE FROM guru_test WHERE emp_id = ? Explanation of the code: Code Line 18: We are setting a variable guruid whose value is 3, which has to be deleted from the database. This is always a primary key of the table. In this case, the primary key is the emp_id. Code Line 19-22: Here we are using a delete query which is setting a parameter in the where clause.Here parameter is guruid which is set in code line 18. The corresponding record is deleted. Output: When you execute the above code, the record with emp_id as 3 is deleted. Note: In this example, we cannot show the output as we are deleting the record from the table.To check whether that record is deleted, we need to use select query "select * from guru_test". In that case, if we get 3 as emp id then delete query has failed else the record has been deleted successfully.

        Update The update is used to edit the records in the table. Example: <%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
        4.11 compare JSP and servlet

        119

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> Guru Database JSP1 UPDATE guru_test SET emp_name='emp guru99' Explanation of the code: Code Line 18: Here we are setting a variable guruid as 2. This is the ID where we want to update the record. Code Line 19-22: Here we are using an update query to update the record in the table guru_test of the record, which is set in point 18.Here emp guru2 is replaced by emp guru99 Output: When you execute the above code the record with emp_id 2 is changed to 99. So, now the output will show emp"guru99" instead of emp "guru2"

        compare JSP and servlet Following are the comparisons of JSP and servlets.

        1

        2

        3 4

        Servlet Servlet is faster than jsp

        In Servlet, if we modify the code then we need recompilation, reloading, restarting the server> It means it is time consuming process. Servlet is a java code. In Servlet, there is no such method for running JavaScript at client side.

        5

        To run a Servlet you have to make an entry of Servlet mapping into the deployment descriptor file i.e. web.xml file externally.

        6

        Coding of Servlet is harden than jsp.

        JSP JSP is slower than Servlet because it first translate into java code then compile. In JSP, if we do any modifications then just we need to click on refresh button and recompilation, reloading, restart the server is not required. JSP is tag based approach. In JSP, we can use the client side validations using running the JavaScript at client side. For running a JSP there is no need to make an entry of Servlet mapping into the web.xml file externally, you may or not make an entry for JSP file as welcome file list. Coding of jsp is easier than Servlet because it is tag based.

        120

        Chapter 4. Java Server Page-JSP 7 8 9 10

        11

        12

        13

        In MVC pattern, Servlet plays a controller role. Servlet accept all protocol request. In Servlet, aervice() method need to override. In Servlet, by default session management is not enabled we need to enable explicitly. In Servlet we do not have implicit object. It means if we want to use an object then we need to get object explicitly form the servlet. In Servlet, we need to implement business logic, presentation logic combined. In Servlet, all package must be imported on top of the servlet.

        Exercise 1. 2. 3. 4. 5. 6.

        Explain the Advantages and drawbacks of JSP. Explain the JDBC with examples. Explain JSP-sessions. Explain JSP Cookie concepts. Write a HTML forms by embedding JSP code. Differentiate JSP and Servlets.

        In MVC pattern, JSP is used for showing output data i.e. in MVC it is a view. JSP will accept only http protocol request. In JSP no need to override service() method. In JSP, session management is automatically enabled. In JSP, we have implicit object support.

        In JSP, we can separate the business logic from the presentation logic by uses javaBean technology. In JSP, package imported anywhere top, middle and bottom.

        5. Introduction to PHP

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

        Server Side Programming It is a technique used in Web design which involves embedded scripts in an HTML source code which results in a Client’s request to the Server website being handled by a script/program running Server-Side before the Server responds to the client request. Advantages of Server Side Programs: • All programs reside in one machine called the Server. Any number of Clients can access the server programs. • New functionalities to existing programs can be added at the server side. • Migrating to new versions, architectures, design patterns, switching to new databases can be done at the Server side without having to bother about Clients. • Issues relating to enter price applications like resource management, concurrency, session management, security and performance are managed by Server side applications.

        • They are portable and possess the capability to generate dynamic and user-based content. Some of the Server side programming Languages ASP (Active Server Pages): This venerable Microsoft technology has been around since 1997, and was one of the first Web application technologies to integrate closely with the Web server, resulting in fast performance. ASP scripts are usually written in VBScript, a language derived from BASIC. This contrasts with PHP’s more C - like syntax. Although both languages have

        122

        Chapter 5. Introduction to PHP

        their fans, I personally find that it’s easier to write structured, modular code in PHP than in VBScript. ASP.NET: This is the latest incarnation of ASP, though in fact it’s been rebuilt from the ground up. It’s actually a framework of libraries that you can use to build Web sites, and you have a choice of languages to use, including C#, VB.NET (Visual Basic), and J# (Java). Because ASP.NET gives you a large library of code for doing things like creating HTML forms and accessing database tables, you can get a Web application up and running very quickly. PHP, although it has a very rich standard library of functions, doesn’t give you a structured framework to the extent that ASP.NET does. Perl: Perl was one of the first languages used for creating dynamic Web pages, initially through the use of CGI scripting and, later, integrating tightly into Web servers with technologies like the Apache mod_perl module and ActivePerl for IIS. Though Perl is a powerful scripting language, it’s harder to learn than PHP. It’s also more of a general - purpose language than PHP, although Perl’s CPAN library includes some excellent modules for Web development. Java: Like Perl, Java is another general - purpose language that is commonly used for Web application development. Thanks to technologies like JSP (JavaServer Pages) and servlets, Java is a great platform for building large - scale, robust Web applications. With software such as Apache Tomcat, you can easily build and deploy Java - based Web sites on virtually any server platform, including Windows, Linux, and FreeBSD. Disadvantages of Servlets: • Servlet is a mixture of Java skills and web related HTML skills, because you have to write the business logic in Java and the presentation you should use the HTML, so the role based development is missing in pure Servlet. The developer who is writing Servlet should know Java and HTML. • If your application is build on using Servlet technology, it very difficult for enhancement 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 allows 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 programming language architectures like Vastly improved object-oriented capabilities, Try/catch exception handling, Improved XML and Web Services support and Native support for SQLite. PHP 5.3 is actually the most significant upgrade to the language since the release of 5.0. Heralding a powerful array of new features including namespaces, late static binding, lambda functions and closures, a new MySQL driver, and a variety of syntactical additions such as NOWDOC syntax, version 5.3 represents a serious step forward in PHP’s evolution. A new major version of PHP known as PHP 6 has been concurrently developed alongside PHP 5.X for several years, with the primary goal of adding Unicode support to the language. Although PHP 6 beta releases had previously been made available at http://snaps.php.net Difference between HTML & PHP Sno 1. 2. 3. 4. 5.

        HTML Hyper Text Markup Language It is a Markup Language It is used to design a Static Web pages This code is executed in Client Machine (i.e Web Browser) No additional software is used to execute.

        6.

        It does’t converted to any language

        7. 8. 9.

        HTML is very easy and forgiving of mistakes HTML easier than php HTML where anything you put in creates an output Extension .html

        10.

        PHP Hypertext Preprocessor (Personal Home Page) It is a Scripting Language It is used to design a Dynamic Web pages This code is executed in Server machine Additionally PHP and Any server is needed to execute the code After execution of php code is converted to html code. Compare to html php is complex. learning time of PHP is longer than HTML PHP would not give you an output if something is wrong with your code Extension .php

        Table 5.1: Difference between HTML and PHP

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

        • Create and manipulate Adobe Flash and Portable Document Format (PDF) files.

        The anatomy of a PHP Page

        125

        • Evaluate a password for guessability by comparing it to language dictionaries and easily broken patterns. • Parse even the most complex of strings using the POSIX and Perl-based regular expression libraries. • Authenticate users against login credentials stored in flat files, databases, and even Microsoft’s Active Directory. • Communicate with a wide variety of protocols, including LDAP, IMAP, POP3, NNTP, and DNS, among others. • Tightly integrate with a wide array of credit-card processing solutions. Possibility • PHP developers are rarely bound to any single implementation solution. On the contrary, a user is typically fraught with choices offered by the language. • PHP’s flexible string-parsing capabilities offer users of differing skill sets the opportunity to not only immediately begin performing complex string operations but also to quickly port programs of similar functionality over to PHP. • PHP offers comprehensive support for both procedural programming and object-oriented paradigm. • The recurring theme here is that PHP allows you to quickly capitalize on your current skill set with very little time investment. Price PHP is available free of charge! Since its inception, PHP has been without usage, modification, and redistribution restrictions. In recent years, software meeting such open licensing qualifications has been referred to as open source software. • Free of licensing restrictions imposed by most commercial products: Open source software 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 organization. Anyone who has the interest and the ability is free to join the project. The absence of member restrictions greatly enhances the talent pool for a given project, ultimately contributing to a higher-quality product.

        The anatomy of a PHP Page PHP documents end with the extension .php. When a web server encounters this extension in a requested file, it automatically passes it to the PHP processor. It need some syntactical rules for parsing PHP code. Embedding PHP Code in Your Web Pages Default Syntax The default delimiter syntax satrts with , like this

        Welcome!

        Welcome to PHP !

        "; ?>

        126

        Chapter 5. Introduction to PHP

        Some static output here!

        :::::::::: OUTPUT :::::::::: Welcome to PHP ! Some static output here!

        “” 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: :::::::::: OUTPUT :::::::::: Welcome to PHP !

        When short-tags syntax is enabled and you want to quickly escape to and from PHP to output a bit of dynamic text, you can omit these statements using an output variation known as short-circuit syntax: 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."; :::::::::: OUTPUT :::::::::: This is another PHP example. ASP Style Microsoft ASP pages employ a delimiting strategy similar to that used by PHP, delimiting static from dynamic syntax by using a predefined character pattern: opening dynamic syntax with < %, and concluding with %>. If you’re coming from an ASP background and prefer to continue using this escape syntax, PHP supports it. Here’s an example: <% print "This is another PHP example."; %> :::::::::: OUTPUT :::::::::: This is another PHP example.

        Keep in mind that just because you can do something doesn’t mean you should. The ASP Style and Script delimiting variants are rarely used and should be avoided unless you have ample reason for doing so.

        5.3 The anatomy of a PHP Page

        127

        Embedding Multiple Code blocks You can escape to and from PHP as many times as required within a given page. For instance, the following example is perfectly acceptable: <?php echo "Welcome to PHP!";?>

        Today's date is

        :::::::::: OUTPUT :::::::::: Today's date is Jan 1, 2014

        Commenting Your Code Whether for your own benefit or for that of somebody tasked with maintaining your code, the importance of thoroughly commenting your code cannot be overstated. PHP offers several syntactical variations for documenting your code. Single-Line C++ Syntax Comments often require no more than a single line. Because of its brevity, there is no need to delimit the comment’s conclusion because the newline ( \ n) character fills this need quite nicely. PHP supports C++ single-line comment syntax, which is prefaced with a double slash (), like this: 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: 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



        Output of above three programs are same i.e This is a PHP program. Outputting Data to the Browser print() statement The print() statement outputs data passed to it . Its prototype looks like this: int print(argument)

        All of the following are plausible print() statements: PHP was created by Rasmus Lerdorf.

        "); ?> PHP was created by $str.

        "; ?> PHP was created by Rasmus Lerdorf.

        "; ?>

        All these statements produce identical output:PHP was created by Rasmus Lerdorf. The print() statement’s return value is misleading because it will always return 1 regardless of outcome. echo() statement Alternatively, you could use the echo() statement for the same purposes as print(). While there are technical differences between echo() and print(), they’ll be irrelevant to most readers and therefore aren’t discussed here. echo()’s prototype looks like this: void echo(string argument1 [, ...string argumentN])

        To use echo(), just provide it with an argument just as was done with print(): echo "PHP was created by Rasmus Lerdorf.";

        As you can see from the prototype, echo() is capable of outputting multiple strings. The utility of this particular trait is questionable; using it seems to be a matter of preference more than anything else. Nonetheless, it’s available should you feel the need. Here’s an example:

        The anatomy of a PHP Page

        129

        This code produces the following: Lennox Lewis and Floyd Mayweather are great fighters. The key difference between echo() and print() are 1. print() returns integer value echo() returns boolean(i.e TRUE or FALSE) value. 2. Through print() we pass only one string, in echo() we pass multiple strings. printf() statement The printf() statement is ideal when you want to output a blend of static text and dynamic information stored within one or several variables. It’s ideal for two reasons. First, it neatly separates the static and dynamic data into two distinct sections, allowing for easy maintenance. Second, printf() allows you to wield considerable control over how the dynamic information is rendered to the screen in terms of its type, precision, alignment, and position. Its prototype looks like this: integer printf(string format [, mixed args])

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

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

        Description Argument considered an integer; presented as a binary number Argument considered an integer Argument considered an integer; presented as a signed decimal number Argument considered a floating-point number; presented as a floating-point number Argument considered an integer; presented as an octal number Argument considered a string; presented as a string Argument considered an integer; presented as an unsigned decimal number Argument considered an integer; presented as a lowercase hexadecimal number Argument considered an integer; presented as an uppercase hexadecimal number Table 5.2: Commonly Used Type Specifiers

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

        An example follows:

        130

        Chapter 5. Introduction to PHP

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

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

        Identifiers Identifiers are names made up by the programmer to refer to variables, functions, or types. An identifier can consist of one or more characters and must begin with a letter or an underscore. Furthermore, identifiers can consist of only letters, numbers, underscore characters, and other ASCII characters from 127 through 255. Rules for naming Identifiers • Identifiers are case sensitive. Therefore, a variable named $recipe is different from a variable named $Recipe, $rEciPe, or $recipE. • Identifiers can be any length. • An identifier name can’t be identical to any of PHP’s predefined keywords. • The same identifier can be used in different scopes to refer to different elements. • The first character must be a letter or an underscore(_). • Identifier does’t starts with Numbers. • Identifiers does’t contains any special characters except underscore(_). Valid and Invalid Identifiers Examples

        Valid name,_name x_y xnoty

        Invalid 2name x&y x!y

        Table 5.3: Valid and Invalid Identifiers

        Variables Variables are a fundamental part of any programming language. A variable is simply a container that holds a certain value. Variables get their name because that certain value can change throughout the execution of the script. It’s this ability to contain changing values that make variables so useful. “A variable is a named memory location that contains data and may be manipulated throughout the execution of the program.” Rules for naming a variable • Variable names begin with a dollar sign ( $ ). • The first character after the dollar sign must be a letter or an underscore. • The remaining characters in the name may be letters, numbers, or underscores without a fixed limit • An Variable name can’t be identical to any of PHP’s predefined keywords. • Variables are case sensitive. Therefore, a variable named $recipe is different from a variable named $Recipe, $rEciPe, or $recipE. Declaring a variable is as simple as using its name in your script: $my_ f irst_variable;

        5.5 Variables

        131

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

        Invalid Variables color $2variable $%variable (or) varia%ble

        Variable scope The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. Local Variables A variable declared in a function is considered local. That is, it can be referenced only in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function. $x = 4; function assignx () { $x = 0; printf("\$x inside function is %d
        ", $x); } assignx(); printf("\$x outside of function is %d
        ", $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.
        132

        Chapter 5. Introduction to PHP

        echo "Inside the sum() function= $b"; } Sum(); echo "
        Outside sum() function= $b"; ?> :::::::::: OUTPUT :::::::::: Inside the sum() function= 3 Outside sum() function= 3

        The above script will output 3. By declaring aandb global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. static variables Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example

        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:

        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.

        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



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

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

        If the optional parameter case_insensitive is included and assigned TRUE, subsequent references to the constant will be case insensitive. Consider the following example in which the mathematical constant Pi is defined: define("PI", 3.141592); Example: Valid and invalid constant names
        names "something"); "something else"); "something more");

        // Invalid constant names define("2FOO", "something"); // This is valid, but should be avoided: // PHP may one day provide a magical constant // that will break your script define("__FOO__", "something"); ?>

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

        134

        Chapter 5. Introduction to PHP Scalar Data types Compound data types Special data types

        Boolean, integer, float, and string array and object resource and NULL

        Table 5.4: Data Types in PHP

        Data Types PHP supports eight primitive data types with three classifications. Scalar Data Types Boolean This is the simplest type. A boolean expresses a truth(TRUE/FALSE) value. It can be either TRUE or FALSE. Alternatively, you can use zero to represent FALSE, and any nonzero(1,-1,8 etc.,) value to represent TRUE. Examples $a $a $a $a $a

        = = = = =

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

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

        Example 542 -987600 0542 0xA1F6 0b010101

        Number System decimal decimal octal hexadecimal binary

        Table 5.5: Examples for valid Integers The size of an integer is platform-dependent. although this is typically positive or negative 231 for PHP version 5 and earlier. PHP 6 introduced a 64-bit integer value, meaning PHP will support integer values up to positive or negative 263 in size float Floating point numbers also known as floats, doubles, or real numbers, allow you to specify numbers that contain fractional parts. Floats are used to represent monetary values, weights, distances, and a whole host of other representations in which a simple integer value won’t suffice. PHP’s floats can be specified in a variety of ways, several of which are demonstrated here:

        5.8 Expressions

        135

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

        Compound Data Types Compound data types allow for multiple items of the same type to be aggregated under a single representative entity. Arrays An array, is formally defined as an indexed collection of data values. Each member of the array index (also known as the key) references a corresponding value and can be a simple numerical reference to the value’s position in the series, or it could have some direct correlation to the value. branch[0]="CSE"; branch[1]="ECE"; branch[2]="EEE"; . . . branch[0]="MECH"; Object The other compound datatype supported by PHP is the object. The object is a central concept of the object-oriented programming paradigm. Unlike the other data types contained in the PHP language, an object must be explicitly declared. This declaration of an object’s characteristics and behavior takes place within something called a class. class Appliance { private $_power; function setPower($status) { $this->_power = $status; } } ... $blender = new Appliance;

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

        136

        Chapter 5. Introduction to PHP

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

        Operators An operator is a symbol that specifies a particular action in an expression. Arithmetic Operators The arithmetic operators, perform various mathematical operations and will probably be used frequently in many of your PHP programs. The division operator (“/”) returns a float value unless Example $a + $b $a - $b $a * $b $a / $b $a % $b

        Name Addition Subtraction Multiplication Division Modulus

        Result Sum of $a and $b. Difference of $a and $b. Product of $a and $b. Quotient of $a and $b. Remainder of $a divided by $b.

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

        // // // //

        prints prints prints prints

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

        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:

        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.

        Bitwise Operators Bitwise operators allow evaluation and manipulation of specific bits within an integer. Example $a & $b $a | $b $a $b ˆ $˜ a $a << $b

        Name And Or (inclusive or) Xor (exclusive or) Not Shift left

        $a >> $b

        Shift right

        Result Bits that are set in both $a and $b are set. Bits that are set in either $a or $b are set. Bits that are set in $a or $b but not both are set. Bits that are set in $a are not set, and vice versa. Shift the bits of $a $b steps to the left (each step means "multiply by two") Shift the bits of $a $b steps to the right (each step means "divide by two") Table 5.7: Bitwise Operators

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

        138

        Chapter 5. Introduction to PHP

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

        Name Is equal to Is not equal to Is identical to

        $a < $b $a >$b $a <= $b $a >= $b ($a == 12) ? 5 : -1

        Less than Greater than Less than or equal to Greater than or equal to Ternary

        Result True if $a and $b are equivalent True if $a is not equal to $b True if $a and $b are equivalent and $a and $b have the same type True if $a is less than $b True if $a is greater than $b True if $a is less than or equal to $b True if $a is greater than or equal to $b If $a equals 12, return value is 5; otherwise, return value is -1

        Table 5.8: Comparison Operators

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

        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(). $output"; ?>

        5.9 Operators

        139

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

        Name Pre-increment Post-increment Pre-decrement Post-decrement

        Result Increments $a by one, then returns $a. Returns $a, then increments $a by one. Decrements $a by one, then returns $a. Returns $a, then decrements $a by one.

        Table 5.9: Increment/decrement Operators

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

        Logical Operators Example $a && $b $a AND $b $a || $b $a OR $b !$a NOT $a $a XOR $b

        Name AND AND OR OR NOT NOT Exclusive OR

        Result True if both $a and $b are true True if both $a and $b are true True if either $a or $b is true True if either $a or $b is true True if $a is not true True if $a is not true True if only $a or only $b is true

        Table 5.10: Logical Operators

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

        Example:
        140

        Chapter 5. Introduction to PHP Example $a + $b $a == $b

        Name Union Equality

        $a === $b

        Identity

        $a != $b $a <> $b $a !== $b

        Inequality Inequality Non-identity

        Result Union of $a and $b. TRUE if $a and $b have the same keyvalue pairs. TRUE if $a and $b have the same keyvalue pairs in the same order and of the same types. TRUE if $a is not equal to $b. TRUE if $a is not equal to $b. TRUE if $a is not identical to $b.

        Table 5.11: Array Operators $a = array("a" => "apple", "b" => "banana"); $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry"); $c = $a + $b; // Union of $a and $b echo "Union of \$a and \$b: \n"; var_dump($c); $c = $b + $a; // Union of $b and $a echo "Union of \$b and \$a: \n"; var_dump($c); ?>

        Operator Precedence The precedence of an operator specifies how “tightly” it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. When operators have equal precedence, their associativity decides whether they are evaluated starting from the right, or starting from the left. Operator Associativity The associativity characteristic of an operator specifies how operations of the same precedence are evaluated as they are executed. Associativity can be performed in two directions, left-to-right or right-to-left. Left-to-right associativity means that the various operations making up the expression are evaluated from left to right. $value = 3 * 4 * 5 * 7 * 2;

        The preceding example is the same as the following: $value = ((((3 * 4) * 5) * 7) * 2);

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

        5.10 Statements

        141

        The preceding example is the same as the following: $c = 5; $value = ($a = ($b = $c));

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

        Statements Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statementgroup 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: $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: $b) { echo "a is bigger than b"; $b = $a; } ?>

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

        142

        Chapter 5. Introduction to PHP

        The else Statement Often you’d want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise:

        > $b) { "a is greater than b"; { "a is NOT greater than b";

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

        $b) { "a is bigger than b"; ($a == $b) { "a is equal to b"; "a is smaller than b";

        There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write ‘else if’ (in two words) and the behavior would be identical to the one of ’elseif’ (in a single word). The syntactic meaning is slightly different (if you’re familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior. The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE. switch The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.
        5.10 Statements

        143

        echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; } switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } ?>

        It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. A special case is the default case. This case matches anything that wasn’t matched by the other cases. For example:

        The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type. Looping Statements Looping mechanisms offer a simple means for accomplishing a commonplace task in programming: repeating a sequence of instructions until a specific condition is satisfied. The while Statement while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

        144

        Chapter 5. Introduction to PHP

        while (expr) statement;

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

        The following examples are identical, and both print the numbers 1 through 10: The do...while Statement do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately). There is just one syntax for do-while loops: 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: The for Statement for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is: for (expr1; expr2; expr3) statement

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

        146

        Chapter 5. Introduction to PHP

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

        Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions. PHP also supports the alternate “colon syntax” for for loops. for (expr1; expr2; expr3): statement ... endfor; The foreach Statement The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement

        The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element). The second form will additionally assign the current element’s key to the $key variable on each iteration. The break Statements break ends execution of the current for, foreach, while, do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. \n"; }

        5.10 Statements

        147

        /* Using the optional argument. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5
        \n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting
        \n"; break 2; /* Exit the switch and the while. */ default: break; } } ?> The goto Statements The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break. An example follows: "; } less: echo "Number less than 10: $randomNumber
        "; ?> The continue Statement continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. Note: PHP the switch statement is considered a looping structure for the purposes of continue. continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.
        148

        Chapter 5. Introduction to PHP do_something_odd($value);

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

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

        return If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file. If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call. If return is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file’s execution is ended. require require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue. include The include statement includes and evaluates the specified file. The documentation below also applies to require. Files are included based on the file path given or, if none is given, the include_path specified. If the file isn’t found in the include_path, include will finally check in the calling script’s own directory

        5.11 Arrays

        149

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

        Arrays An array is a single variable that can hold more than one value at once. You can think of an array as a list of values. Each value within an array is called an element , and each element is referenced by its own index , which is unique to that array. To access an element’s value - whether you’re creating, reading, writing, or deleting the element - you use that element’s index. Note: An array index is often referred to as a key. Typically, a numeric index is called an index and a string index is called a key; however there’s no hard - and - fast rule with this. In PHP, There are three kinds of Arrays:• Numeric Array:- An Array with numeric Key(index). • Associative Array:- An array where each key is associated with a value. • Multi-dimentional Array:- An array containing one or more arrays. Creating Arrays Individual elements of a PHP array are referenced by denoting the element between a pair of square brackets. Because there is no size limitation on the array, you can create the array simply by making reference to it, like this: $branch[0] = "CSE";

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

        Interestingly, if you intend for the index value to be numerical and ascending, you can omit the index value at creation time: $branch[] = "CSE"; $branch[] = "ECE"; ... $branch[] = "EEE"; Creating Arrays with array() The simplest way to create a new array variable is to use PHP’s built - in array() construct. This takes a list of values and creates an array containing those values, which you can then assign to a variable:

        150

        Chapter 5. Introduction to PHP

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

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

        This creates an array with three elements: “ PRAVEEN ” , which has an index of “ Name “ ; “ CSE ”, which has an index of “ branch “ ; and “Male” , which has an index of “ Gender ”. Multidimentional arrays In Multi-dimentional array elements in the array can be an array, and each element in the sub-array can be an arrya and so on. Example:- In this example we create multidimentional array, with automatically assigned keys. array("CSE","ECE","EEE","MECH"), "PG"=>array("M.Tech(CSE)","M.Tech(CS)","M.Tech(VLSI)"), "Dip"=>array("DCME","DECE","DEEE")); ?>

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

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

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

        5.11 Arrays

        151

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

        Outputting an Array The most common way to output an array’s contents is by iterating over each key and echoing the corresponding value. For instance, a foreach statement does the trick nicely: $branchs = array("CSE", "ECE", "EEE"); foreach ($branchs AS $branch) { echo "{$branch}
        "; } Outputting an Entire Array with print_r() You can’t just print an array with print() or echo() , like you can with regular variables, because these functions can work with only one value at a time. However, PHP does give you a function called print_r() that you can use to output the contents of an array for debugging. Using print_r() is easy - just pass it the array you want to output: print_r( $array );

        Example: print_r($student); :::::::::: OUTPUT :::::::::: array( "Name" = > "PRAVEEN","branch" = > "CSE","Gender" => "Male")

        Adding and Removing Array Elements PHP provides a number of functions for both growing and shrinking an array. Adding a Value to the Front of an Array The array_unshift() function adds elements to the front of the array. All preexisting numerical keys are modified to reflect their new position in the array, but associative keys aren’t affected. Its prototype follows: int array_unshift(array array, mixed variable [, mixed variable...])

        The following example adds two branches to the branch of the $branchs array: $branchs = array("IT", "EEE", "MECH"); array_unshift($branchs, "CSE", "ECE"); // $branchs = array("CSE", "ECE", "IT", "EEE", "MECH"); Adding a Value to the End of an Array The array_push() function adds a value to the end of an array, returning the total count of elements in the array after the new value has been added. You can push multiple variables onto the array simultaneously by passing these variables into the function as input parameters. Its prototype follows:

        152

        Chapter 5. Introduction to PHP

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

        The following example adds two more branchs onto the $branchs array: $branchs = array("IT", "EEE", "MECH"); array_push($branchs, "CSE", "ECE"); // $branchs = array("IT", "EEE", "MECH", "CSE", "ECE"); Removing a Value from the Front of an Array The array_shift() function removes and returns the first item found in an array. If numerical keys are used, all corresponding values will be shifted down, whereas arrays using associative keys will not be affected. Its prototype follows: mixed array\_shift(array array)

        The following example removes the first branch from the $branchs array: $branchs = array("IT", "EEE", "MECH", "CSE", "ECE"); $branch = array_shift($branchs); // $branchs = array( "EEE", "MECH", "CSE", "ECE") // $branch = "IT" Removing a Value from the End of an Array The array_pop() function removes and returns the last element from an array. Its prototype follows: mixed array_pop(array array)

        The following example removes the last branch from the $branchs array: $branchs = array( "EEE", "MECH", "CSE", "ECE") $branch = array_pop($branchs); // $branchs = array( "EEE", "MECH", "CSE") // $branch = "ECE"

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

        In the following example, a message is output if a specified branch is found in an array consisting of branchs. $branch = "CSE"; $branchs = array( "EEE", "MECH", "CSE", "ECE"); if(in_array($branch, $branchs)) echo "$branch existed in array";

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

        5.12 Strings

        153

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

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

        Reversing Array Element Order The array_reverse() function reverses an array’s element order. Its prototype follows: array array_reverse(array array [, boolean preserve_keys])

        If the optional preserve_keys parameter is set to TRUE, the key mappings are maintained. Otherwise, each newly rearranged value will assume the key of the value previously presiding at that position: $grades = array(42, 98, 100, 100, 43, 12); print_r(array_reverse($grades)); :::::::::: OUTPUT :::::::::: Array ( [0] => 12 [1] => 43 [2] => 100 [3] => 100 [4] => 98 [5] => 42 )

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

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

        154

        Chapter 5. Introduction to PHP

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

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

        Double-Quoted Strings Strings enclosed in double quotes are the most commonly used in PHP scripts because they offer the most flexibility. Escape sequences are also parsed. Consider this example:

        Here Documents (heredocs) You can easily put multiline strings into your program with a heredoc, as follows: $clerihew = <<< Identifier Sir Humphrey Davy Abominated gravy. He lived in the odium Of having discovered sodium. identifier; echo $clerihew;

        The <<< identifier token tells the PHP parser that you’re writing a heredoc. There must be a space after the <<< and before the identifier. You get to pick the identifier. The next line starts the text being quoted by the heredoc, which continues until it reaches a line that consists of nothing but the identifier. As a special case, you can put a semicolon after the terminating identifier to end the statement, as shown in the previous code. If you are using a heredoc in a more complex expression, you need to continue the expression on the next line, as shown here: printf(<<< Template %s is %d years old. Template , "Fred", 35);

        5.12 Strings

        155

        String Manipulation Functions Length of a String

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

        The following example to check length of user name Comparing two strings

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

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

        PHP has several functions for changing the case of strings: strtolower() and strtoup per() operate on entire strings, ucfirst() operates only on the first character of the string, and ucwords() operates on the first character of each word in the string. Each function takes a string to operate on as an argument and returns a copy of that string, appropriately changed. For example: $string1 = "FRED flintstone"; $string2 = "barney rubble"; print(strtolower($string1)); print(strtoupper($string1)); print(ucfirst($string2)); print(ucwords($string2));

        156

        Chapter 5. Introduction to PHP

        Removing HTML tags from strings The strip_tags() function removes HTML tags from a string. $input = '

        Howdy, "Cowboy"

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

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

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

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

        Regular Expressions Regular expressions provide the foundation for describing or matching data according to defined syntax rules. A regular expression is nothing more than a pattern of characters itself, matched against a certain parcel of text It is used like validations in forms when taking the input from users. The structure of a POSIX (Portable Operating System Interface for Unix) regular expression is similar to that of a typical arithmetic expression: various elements (operators) are combined to form a more complex expression. The meaning of the combined regular expression elements is what makes them so powerful. You can use the syntax to find not only literal expressions, such as a specific word or number, but also a multitude of semantically different but syntactically similar strings, such as all HTML tags in a file. Brackets ([]) are used to represent a list, or range, of characters to be matched. • [0 − 9] matches any decimal digit from 0 through 9. • [a − z] matches any character from lowercase a through lowercase z. • [A − Z] matches any character from uppercase A through uppercase Z. • [A − Za − z] matches any character from uppercase A through lowercase z. Character Classes In PHP, We have several predefined character ranges, also known as character classes. Character classes specify an entire range of characters-for example, the alphabet or an integer set. Standard classes include the following: • [: al pha :]: Lowercase and uppercase alphabetical characters. This can also be specified as [A-Za-z]. • [: alnum :]: Lowercase and uppercase alphabetical characters and numerical digits. This can also be specified as [A-Za-z0-9]. • [: cntrl :]: Control characters such as tab, escape, or backspace. • [: digit :]: Numerical digits 0 through 9. This can also be specified as [0-9]. • [: graph :]: Printable characters found in the range of ASCII 33 to 126. • [: lower :]: Lowercase alphabetical characters. This can also be specified as [a-z]. ˆ ( ) - _ + = { } [ ] : ; ’ <> , . ? and /. • [: punct :]: Punctuation characters, including `! # $ % & • [: 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:

        User-Defined Functions PHP support User-defined functions also. To define a function, use the following syntax: function functionName(parameters) { function-body }

        Example: function myFun() //called function.. { echo "My first Function"; } myFun();//Calling function.. Passing Arguments by Value You’ll often find it useful to pass data into a function. Example $b
        ";

        158

        Chapter 5. Introduction to PHP

        } ?> //Output: 155 & 125

        This function accepts two parameters, aptly named $value and $a, which are used in the calculation. When you pass an argument in this manner, it’s called passing by value. This means that any changes made to those values within the scope of the function are ignored outside of the function. Passing Arguments by Reference We may want any changes made to an argument within a function to be reflected outside of the function’s scope. Passing the argument by reference accomplishes this. Passing an argument by reference is done by appending an ampersand to the front of the argument. Here’s an example: "; echo $a,"
        "; function myFun(&$value,&$a,$c) { $c=$a+$value+$c; echo "
        $c
        "; $value+=10; $a=$a*$a; } ?> //OUTPUT: 155,135,400 Default Argument Values Default values can be assigned to input arguments, which will be automatically assigned to the argument if no other value is provided. Example "; function myFun($a,$c,$value=0.876) { $c=$a+$value+$c; echo "
        $c
        "; $value+=10; $a=$a*$a; echo $value; } ?> //output:30.876, 10.876400 Returning Values from a Function The return Statement The return() statement returns any ensuing value back to the function caller, returning program control back to the caller’s scope in the process. If return() is called from within the global scope, the script execution is terminated. Example:

        Functions

        159

        "; 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. Example: $rno

        Name: $name
        ?> OUTPUT: Roll Number: 08G01A0542 Name: D PRAVEEN KUMAR email: [email protected]

        email: $email";

        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. 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(). "; foreach ($array as $value) { echo $value . ","; } echo "
        "; echo "
        "; for($j = 0; $j < count($array); $j ++) { for($i = 0; $i < count($array)-1; $i ++){ if($array[$i] > $array[$i+1]) { $temp = $array[$i+1]; $array[$i+1]=$array[$i]; $array[$i]=$temp; } } } echo "Sorted Array is: "; echo "
        "; #print_r($array); foreach ($array as $value) { echo $value . ","; } ?>

        2. Write a PHP program to decompose a string into individual elements and store them in an array. Use PHP's explode() function to split a string by delimiter and store the separate segments in a numerically indexed array:

        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)

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

        5. Write a PHP script to protect a publicly-displayed e-mail address from being captured by an e-mail address harvester.
        162

        Chapter 5. Introduction to PHP // perform search and replace operation return str_replace($search, $replace, $email); } // result: "dontap at cst dash a dot acm dot org" print protectEmail("[email protected]"); ?>

        Using Cookies Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. PHP transparently supports HTTP cookies. A cookie lets you store a small amount of data within the user ’ s browser itself. Then, whenever the browser requests a page on your Web site, all the data in the cookie is automatically sent to the server within the request.This means that you can send the data once to the browser, and the data is automatically available to your script from that moment onward. A cookie is sent from the server to the browser as part of the HTTP headers. Setting Cookies We can set cookies using the setcookie() function. setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including < html > and < head > tags as well as any whitespace. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

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

        5.16 Using Cookies

        163

        Example

        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 password from cookie:".$_COOKIE['cookie_pass']; ?> :::::: OUTPUT :::::: User name from cookie:test_uname password from cookie:test_pwd

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

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

        • a user will want to be able to clear the cookies on a site. When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:
        164

        Chapter 5. Introduction to PHP setcookie ("cookie_user", "", time() - 3600); ?> ::::: OUTPUT :::::: After execution of above script it returns null value.

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

        sring: The header string. replace: The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. http_response_code: Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the string is not empty. Redirecting to a Different Location One of the more common uses for HTTP headers is redirecting a script. By using headers inside processing scripts, you can force the browser to return to any page we want. The following program shows the login page. after successful login header() function forwarded to home.php page. Login <style> .error { font-weight: bold; color: #FF0000; }


        5.17 Using HTTP Headers

        165

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

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

        header("Location: home.php"); //this function forward to home.php }else{ $goodtogo = false; throw new exception ("Sorry, your User name password not matched.
        "); } } } catch (exception $e) { ?><span class="error">getmessage(); ?>
        " method="post">

        Login form:

        User Name: "/>

        Password: " />


        home.php

        166

        Chapter 5. Introduction to PHP

        heade

        This is the home page after successful login header function forwarded to this page..

        :::::::::: OUTPUT :::::::::: This is the home page after successful login header function forwarded to this page..

        The header() function is rather nice in that it will redirect you automatically to the appropriate file without a single hiccup in the processing. You will simply find yourself at the appropriate page. Sending Content Types Other Than HTML The Content-Type header field is used to specify the nature of the data in the body of an entity, by giving type and subtype identifiers, and by providing auxiliary information that may be required for certain types. After the type and subtype names, the remainder of the header field is simply a set of parameters, specified in an attribute/value notation. The set of meaningful parameters differs for the different types. The ordering of parameters is not significant. The header function is more than versatile enough to take care of this issue. To make the most out of this function, you can effectively output other file types by simply declaring the content type you want to output. Content Type application/pdf application/msword application/excel image/gif image/png application/octet-stream text/plain

        Application Adobe Portable Document Format (PDF) types Microsoft Word documents Microsoft Excel documents GIF images PNG images Zip files Plain text (text files)

        Table 5.12: Common File Format Content Types Forcing File “Save As” Downloads Because web browsers can output many different file types directly onto the screen, the default when you use headers to output a wide variety of file types is to make them automatically appear on the screen. What if you would rather have the file appear as a download, though? You can use the header()function to force a Save As dialog box to appear for the user to accept a download.
        5.18 Using Sessions

        167

        header("Content-Disposition:attachment;filename=".$output.".pdf"); // The PDF source is in original.pdf readfile("original.pdf"); ?> :::::: OUTPUT ::::::

        Figure 5.1: Output of forcing Save As downloads The key point in this code is showing content-disposition in the header. By making contentdisposition 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 authentication 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:
        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. ".$_SESSION['uname']."

        "; echo "Password in SESSION is ".$_SESSION['pwd'].""; ?> :::::: OUTPUT :::::: Username in SESSION is test_user Password in SESSION is test_pwd

        Deleting Sessions In php we are using three functions to deleate or clear SESSION information. • session_unset() The session_unset() function frees all session variables currently registered. the prototype is as follows: void session_unset ( void ) • session_destroy() The session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called. The prototype is as follows: bool session_destroy ( void ) • unset() unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called. The prototype is as follows: void unset ( mixed $var [, mixed $... ] ) Example: unset($_SESSION[‘uname’]); After executing the above statement only uname will be cleared from session. Storing Simple Data Types in Sessions Sessions have really been useful only for passing simple data types around. Sessions handle simple data types, and they handle them well. Like any PHP variable, however, the data type of a current session is based upon what was last assigned to it and can be changed quite easily. The following example describes this:
        5.18 Using Sessions

        169

        (int)$_SESSION['inumber']=1024; (float)$_SESSION['fnumber']=10.23; (string)$_SESSION['str']="String"; ?> Internally SESSION stores information as follows: Array ( [inumber] => 1024 [fnumber] => 10.23 [str] => String )

        Storing Complex Data Types in Sessions One of the major improvements to PHP is the ability to store complex data types (arrays and objects) within a session. Store & Access Arrays in SESSION The following example demonstrate how to store arrays in Sessions. "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. "; echo "Password:::::::::::".$_SESSION['str']['pwd']."
        "; /?> :::::: OUTPUT :::::: User name:::::::::::Praveen Password:::::::::::password Store & Access Objects in SESSION PHP allows you to store objects within sessions. Using this technique, you can easily store large quantities of data within a single object, use the functionality within the session for these purposes, and then pass the data along to other pages. myvalue = $newvalue; } public function getmyvalue (){ return $this->myvalue;

        170

        Chapter 5. Introduction to PHP

        } } $_SESSION['myclass_value'] = new myclass (); //This function exists for the sole purpose of showing how sessions can be called //from anywhere within the scope of the session state. function outputsessions (){ $_SESSION['myclass_value']->setmyvalue ("Hello World"); echo $_SESSION['myclass_value']->getmyvalue (); } //Then you can call the function from here: outputsessions(); ?>

        Difference between cookies & sessions

        1. 2. 3. 4. 5. 6. 7. 8.

        9.

        Cookies Cookies store data on the Client machine Less secure Stores less amount of data It store only primitive datatypes More amount of time Data stored in cookies No need to require additional space to store data No need to call additional functions Setting and deleting use setcookie()

        Accessing cookie using $_COOKIE[] superglobal array.

        Sessions Sessions store data on the server More Secure than cookies Here we store more amount of data It stores both primitive and Compound datatypes. Less time sessions store the data. Sessions need extra space, unlike cookies to store data Here it need session_start() to create sessions. For setting session use $_SESSION[] superglobal array, and delete session information use unset() or session_destroy(). Accessing sessions using $_SESSION[] superglobal array

        Authenticating Your Users PHP uses two predefined variables to authenticate a user. 1. $_SERVER[’PHP_AUTH_USER’] 2. $_SERVER[’PHP_AUTH_PW’] These two superglobal variables store the Username and password values respectively while authenticating is as simple as comparing the expected username and password to these variables. The isset() function determines whether a variable has been assigned a value. the prototype is as follows: boolean isset(mixed var[,mixed var[,......]])

        It returns TRUE if the variable contains a value and FALSE if it does not.It applied to User authentication, 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.
        Using Environment and Configuration Variables

        171

        header('www-Authenticate: Basic replays="Authentication"); header("HTTP/1.1 401 Unauthorized"); } else{ echo "User Name is $_SERVER['PHP_AUTH_USER']"; echo "password is $_SERVER['PHP_AUTH_PW']"; } ?>

        Using Environment and Configuration Variables PHP provides a means to use and verify the configuration settings and environment variables relative to the server space the script is occupying. A common use of the environment variables in PHP is for dynamic imaging. While Windows systems commonly store their fonts in one folder, Linux-based systems keep theirs in another. By using PHP’s environment variables to determine the current operating system, you can make your code slightly more portable. Using configuration variables can also come in quite handy, particularly with file upload scripts. The base PHP installation leaves only enough processing time to upload files that are generally 2MB or smaller in size. By manipulating the PHP configuration files temporarily, you can increase the limit enough to allow a script to process much larger files. Reading Environment Variables The $_ENV superglobal is PHP’s method for reading a system’s environment variables and has an argument set that is based upon the current environment that is available to it. We can retrieve them using the getenv() function also. "; //Outputs C:\Program Files. echo getenv("ProgramFiles") . "
        "; //Outputs C:\Program Files. echo $_ENV['COMPUTERNAME'] . "
        "; //Outputs COMPUTER-2339. echo getenv("COMPUTERNAME") . "
        "; //Also Outputs COMPUTER-2339. ?>

        Reading Configuration Variables Reading configuration variables, on the other hand, takes place through two functions, ini_get() and ini_get_all(). The function ini_get() will retrieve the value of a specified configuration variable, and the function ini_get_all() will retrieve an array filled with the entire selection of configuration variables that are available. "; //Outputs 8MB. //And you can output the entire listing with this function. print_r (ini_get_all()); ?>

        Setting Environment Variables Setting environment and configuration variables is just as easy as it is to get them. While working with environment variables, you merely need to assign a new value to the $_ENV superglobal to process a temporary change. The change will be in effect for the script’s duration.

        172

        Chapter 5. Introduction to PHP

        "; // Echoes COMPUTER-2339. $_ENV['COMPUTERNAME'] = "dp"; echo $_ENV['COMPUTERNAME'] . "
        "; //Echoes the new COMPUTERNAME. ?>

        Setting Configuration Variables The same applies for configuration variables but with a different approach. To set a configuration variable, you have to use the PHP function ini_set(), which will allow you to set a configuration variable for the script’s duration. Once the script finishes executing, the configuration variable will return to its original state. The prototype for ini_set() is as follows: string ini_set ( string varname, string newvalue )

        Working with Date and Time In the programming world, date and time values formatted in Unix epoch manner. The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z). Literally speaking the epoch is Unix time 0 (midnight 1/1/1970), but ’epoch’ is often used as a synonym for ’Unix time’. Many Unix systems store epoch dates as a signed 32-bit integer, which might cause problems on January 19, 2038 (known as the Year 2038 problem or Y2038). The following are some of the date and time functions. time() It returns the current system date and time as a Unix timestamp. :::::: OUTPUT :::::: 1386331271

        date() Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. The prototype is a s follows: string date ( string $format [, int $timestamp = time() ] )

        The following example demonstrate date() function.
        5.21 Working with Date and Time

        173

        echo "
        ".date("d:M:Y:::H:S:I"); ?> :::::: OUTPUT :::::: Fri, 06 Dec 2013 13:24:49 +0100 06:Dec:2013:::13:49:0

        Character F M m y Y d j D w h g H a A i j s r

        Description Full name of the month (January, February, and so on). Three-letter abbreviation for the month (Jan, Feb, and so on). Numeric representation for the month, with leading zero (two digits). n Numeric representation for the month (no leading zero). Two-digit year. Four-digit year. Day of the month, with leading zeros (two digits). Day of the month (no leading zeros). A textual representation of a day, three letters (Mon, Tue, and so on). Numeric representation of the day of the week (0 = Sunday, 6 = Saturday). Hour in 12-hour format, with leading zero (two digits). Hour in 12-hour format (no leading zero). Hour in 24-hour format, with leading zero (two digits). G Hour in 24-hour format (no leading zero). am/pm (lowercase). AM/PM (uppercase). Minute, with leading zero (two digits). Minute (no leading zero) Second, with leading zero (two digits). RFC-2822 format WWW, DD MMM YYYY HH:MM:SS ± HHMM Table 5.13: Formatting Characters for the date() Function

        checkdate() Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined. The prototype is as follows: bool checkdate ( int $month , int $day , int $year )

        Returns TRUE if the date given is valid; otherwise returns FALSE.

        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 : :::::: OUTPUT :::::: 1354788006

        strtotime() The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied. Each parameter of this function uses the default time zone unless a time zone is specified in that parameter. Be careful not to use different time zones in each parameter unless that is intended. The prototype is as follows: int strtotime ( string $time [, int $now = time() ] )

        Example to demonstrate strtotome()

        getdate() Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given. array getdate ([ int $timestamp = time() ] )

        Example programs demonstrate getdate() :::::: OUTPUT :::::: Array ( [seconds] => 36 [minutes] => 4 [hours] => 14 [mday] => 6 [wday] => 5 [mon] => 12 [year] => 2013 [yday] => 339 [weekday] => Friday [month] => December [0] => 1386335076 )

        strptime() strptime() returns an array with the date parsed, or FALSE on error. array strptime ( string $date , string $format )

        5.22 Programming Exercise Function date_sunrise() date_sunset() gmdate() gmmktime()

        Description Returns time of sunrise for a given day and location (new in PHP 5). Returns time of sunset for a given day and location (new in PHP 5). Formats a GMT/UTC date/time. Uses the same formatting characters as the date() function. Converts a set of GMT date/time values into a Unix timestamp (analogous to mktime()). Table 5.14: More PHP 5 Date/Time Functions

        Programming Exercise 1. Write a PHP program that works on date & time using functions. "; print date("D, F jS",$b) . "
        "; print date("l, F jS Y",$b) . "
        "; print date("g:i A",$b) . "
        "; print date("r",$b) . "
        "; print date("g:i:s A D, F jS Y",$b) . "
        "; ?>

        Exercise 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.

        Explain the anatomy of a PHP page. How it differs from an html page? What is server side programming? Briefly discuss about any two server side programming languages. What makes PHP a choice among the other scripting languages? Where can we use PHP scripts? What is the impact of programming on web environments? Explain with an example. Explain installation, configure of PHP on Windows. Explain installation, configure of PHP on Linux. Explain different types of operators in PHP with examples. Write a PHP program that removes HTML from the given string. Explain about PHP data types in detail. Write a PHP program that uses all the data types. What is ternary operator? Explain with an example. Write a PHP program that works on date & time using functions. Explain about scope of a variable. What is the use of scope resolution operator? Explain. Explain about operator precedence & associativity. Explain different types of operators in PHP. What is the use of scope resolution operator? Explain. Explain in detail about statements in PHP. Explain how arrays are used in PHP. How functions are declare in PHP? Explain recursive functions in PHP with example. List and Explain different array functions in PHP? Explain different ways to print an array?

        175

        176 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46.

        Chapter 5. Introduction to PHP What is the role of associative arrays in PHP? Explain with examples. How to declare and access the multidimentional arrays in PHP? Explain. How to set a cookie on user computer? Explain with an example. Explain Briefly how to redirect the HTTP headers to different locations. What are cookies? What are the advantages of cookies? Briefly explain different parameters available when setting a cookie. What are Cookies? Explain the following: Setting Cookies. Deleting Cookies. Explain briefly how to use the header() function in different ways. Explain the advantages of the PHP functions available for the time and date. What are cookies? What are the advantages of cookies? Briefly explain different parameters available when setting a cookie. Explain briefly how to redirect the HTTP headers to different locations. Explain briefly how to use the header ( ) function in different ways. Explain why cookies are becoming less trusted. What is a session? Explain briefly about sessions. Explain why cookies are becoming less trusted. Explain briefly how to use the header ( ) function in different ways. What are the advantages and disadvantages of cookies? How to set a cookie on user computer? Explain with an example.

        6. XML- eXternal Markup Language

        XML stands for Extensible Markup Language. It is a text-based markup language derived from Standard Generalized Markup Language (SGML). Difference between HTML and XML

        SNo. 1)

        HTML HTML is used to display data and focuses on how data looks.

        2)

        HTML is a markup language itself.

        3) 4)

        HTML is not case sensitive. HTML is a presentation language.

        5)

        HTML has its own predefined tags.

        6)

        In HTML, it is not necessary to use a closing tag. HTML is static because it is used to display data. HTML does not preserve whitespaces.

        7) 8)

        XML XML is a software and hardware independent tool used to transport and store data. It focuses on what data is. XML provides a framework to define markup languages. XML is case sensitive. XML is neither a presentation language nor a programming language. We can define tags according to your need. XML makes it mandatory to use a closing tag. XML is dynamic because it is used to transport data. XML preserve whitespaces.

        XML tags identify the data and are used to store and organize the data, rather than specifying how to display it like HTML tags, which are used to display the data. XML is not going to replace HTML in the near future, but it introduces new possibilities by adopting many successful features of HTML. There are three important characteristics of XML that make it useful in a variety of systems and solutions: • XML is extensible: XML allows you to create your own self-descriptive tags, or language, that suits your application.

        178

        Chapter 6. XML- eXternal Markup Language

        • XML carries the data, does not present it: XML allows you to store the data irrespective of how it will be presented. • XML is a public standard: XML was developed by an organization called the World Wide Web Consortium (W3C) and is available as an open standard. XML Usage A short list of XML usage says it all: • XML can work behind the scene to simplify the creation of HTML documents for large web sites. • XML can be used to exchange the information between organizations and systems. • XML can be used for offloading and reloading of databases. • XML can be used to store and arrange the data, which can customize your data handling needs. • XML can easily be merged with style sheets to create almost any desired output. • Virtually, any type of data can be expressed as an XML document. What is Markup? XML is a markup language that defines set of rules for encoding documents in a format that is both human-readable and machine-readable. So what exactly is a markup language? Markup is information added to a document that enhances its meaning in certain ways, in that it identifies the parts and how they relate to each other. More specifically, a markup language is a set of symbols that can be placed in the text of a document to demarcate and label the parts of that document. Following example shows how XML markup looks, when embedded in a piece of text: <message> Hello, world!

        XML Syntax This chapter takes you through the simple syntax rules to write an XML document. Following is a complete XML document: Web Technologies Amazon Kindle (040) 123-4567

        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

        Syntax Rules for XML declaration • The XML declaration is case sensitive and must begin with "" where "xml" is written in lower-case. • If document contains XML declaration, then it strictly needs to be the first statement of the XML document. • The XML declaration strictly needs be the first statement in the XML document. • An HTTP protocol can override the value of encoding that you put in the XML declaration.

        Tags and Elements An XML file is structured by several XML-elements, also called XML-nodes or XML-tags. XMLelements’ names are enclosed by triangular brackets<>as shown below: <element>

        Syntax Rules for Tags and Elements Element Syntax: Each XML-element needs to be closed either with start or with end elements as shown below: <element>.... or in simple-cases, just this way: <element/>

        Nesting of elements: An XML-element can contain multiple XML-elements as its children, but the children elements must not overlap. i.e., an end tag of an element must have the same name as that of the most recent unmatched start tag. Following example shows incorrect nested tags: Skillsubsist

        Following example shows correct nested tags: Skillsubsist 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>... ...

        The following example shows a correctly formed XML document: <x>... ...

        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 .

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

        Here href is the attribute name and http://www.skillsubsist.in/ is attribute value.

        Syntax Rules for XML Attributes • Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are considered two different XML attributes. • Same attribute cannot have two values in a syntax. The following example shows incorrect syntax because the attribute b is specified twice: ....

        • Attribute names are defined without quotation marks, whereas attribute values must always appear in quotation marks. Following example demonstrates incorrect xml syntax: ....

        • In the above syntax, the attribute value is not defined in quotation marks. Attributes are part of the XML elements. An element can have multiple unique attributes. Attribute gives more information about XML elements. To be more precise, they define properties of elements. An XML attribute is always a name-value pair. Syntax An XML attribute has following syntax: <element-name attribute1 attribute2 > ....content.. < /element-name>

        where attribute1 and attribute2 has the following form: name = "value"

        value has to be in double (" ") or single (’ ’) quotes. Here, attribute1 and attribute2 are unique attribute labels. Attributes are used to add a unique label to an element, place the label in a category, add a Boolean flag, or otherwise associate it with some string of data. Following example demonstrates the use of attributes:

        XML Document Type Declaration

        181

        ]>

        Attributes are used to distinguish among elements of the same name. When you do not want to create a new element for every situation. Hence, use of an attribute can add a little more detail in differentiating two or more similar elements. In the above example, we have categorized the plants by including attribute category and assigning different values to each of the elements. Hence we have two categories of plants, one flowers and other color. Hence we have two plant elements with different attributes. You can also observe that we have declared this attribute at the beginning of the XML. 6.3.1

        Attribute Types StringType

        It takes any literal string as a value. CDATA is a StringType. CDATA is character data. This means, any string of non-markup characters is a legal part of the attribute. TokenizedType

        This is more constrained type. The validity constraints noted in the grammar are applied after the attribute value is normalized. The TokenizedType attributes are given as: • ID : It is used to specify the element as unique. • IDREF : It is used to reference an ID that has been named for another element. • IDREFS : It is used to reference all IDs of an element. • ENTITY : It indicates that the attribute will represent an external entity in the document. • ENTITIES : It indicates that the attribute will represent external entities in the document. • NMTOKEN : It is similar to CDATA with restrictions on what data can be part of the attribute. • NMTOKENS : It is similar to CDATA with restrictions on what data can be part of the attribute. EnumeratedType

        This has a list of predefined values in its declaration. out of which, it must assign one value. There are two types of enumerated attribute: • NotationType : It declares that an element will be referenced to a NOTATION declared somewhere else in the XML document. • Enumeration : Enumeration allows you to define a specific list of values that the attribute value must match.

        XML Document Type Declaration The XML Document Type Declaration, commonly known as DTD, is a way to describe XML language precisely. DTDs check vocabulary and validity of the structure of XML documents against grammatical rules of appropriate XML language. An XML DTD can be either specified inside the document, or it can be kept in a separate document and then liked separately.

        182

        Chapter 6. XML- eXternal Markup Language

        Syntax Basic syntax of a DTD is as follows:

        In the above syntax, The DTD starts with

        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: ]>
        Tanmay Patil TutorialsPoint (011) 123-4567


        Let us go through the above code: Start Declaration- Begin the XML declaration with following statement

        DTD- Immediately after the XML header, the document type declaration follows, commonly referred to as the DOCTYPE:

        XML Document Type Declaration

        183


        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:
        address (name,company,phone)> name (#PCDATA)> company (#PCDATA)> 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:

        where file-name is the file with .dtd extension. Example The following example shows external DTD usage:
        Tanmay Patil TutorialsPoint (011) 123-4567


        The content of the DTD file address.dtd are as shown:
        address (name,company,phone)> name (#PCDATA)> company (#PCDATA)> 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 declarations. 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: <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="contact"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string" /> <xs:element name="company" type="xs:string" /> <xs:element name="phone" type="xs:int" />

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

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

        Now let us use this type in our example as below: <xs:element name="Address1"> <xs:complexType> <xs:sequence>

        186

        Chapter 6. XML- eXternal Markup Language

        <xs:element name="address" type="AddressType" /> <xs:element name="phone1" type="xs:int" /> <xs:element name="Address2"> <xs:complexType> <xs:sequence> <xs:element name="address" type="AddressType" /> <xs:element name="phone2" type="xs:int" />

        Instead of having to define the name and the company twice (once for Address1 and once for Address2), we now have a single definition. This makes maintenance simpler, i.e., if you decide to add "Postcode" elements to the address, you need to add them at just one place. Attributes Attributes in XSD provide extra information within an element. Attributes have name and type property as shown below: <xs:attribute name="x" type="y"/>

        Document Object Model The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them. A DOM Document is a collection of nodes or pieces of information organized in a hierarchy. This hierarchy allows a developer to navigate through the tree looking for specific information. Because it is based on a hierarchy of information, the DOM is said to be tree based. The XML DOM, on the other hand, also provides an API that allows a developer to add, edit, move, or remove nodes in the tree at any point in order to create an application. Example The following example (sample.htm) parses an XML document ("address.xml") into an XML DOM object and then extracts some information from it with JavaScript:

        DOM example

        Name: <span id="name">
        Company: <span id="company">
        Phone: <span id="phone">
        <script> if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari

        XML - Parsers

        187

        xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","/xml/address.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; document.getElementById("name").innerHTML= xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue; document.getElementById("company").innerHTML= xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue; document.getElementById("phone").innerHTML= xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;

        Contents of address.xml are as below: XML Skill subsist (011) 123-4567

        Now let us keep these two files sample.htm and address.xml in the same directory /xml and execute the sample.htm file by opening it in any browser. This should produce an output as shown below: Name: XML Company: Skill subsist phone: (040) 123-4567 Here, you can see how each of the child nodes is extracted to display their values.

        XML - Parsers XML parser is a software library or a package that provides interface for client applications to work with XML documents. It checks for proper format of the XML document and may also validate the XML documents. Modern day browsers have built-in XML parsers. Following diagram shows how XML parser interacts with XML document: • The goal of a parser is to transform XML into a readable code. • To ease the process of parsing, some commercial products are available that facilitate the breakdown of XML document and yield more reliable results. Some commonly used parsers are listed below: • MSXML (Microsoft Core XML Services) : This is a standard set of XML tools from Microsoft that includes a parser. • System.Xml.XmlDocument : This class is part of .NET library, which contains a number of different classes related to working with XML.

        188

        Chapter 6. XML- eXternal Markup Language

        Figure 6.1: XML- Parser Output • Java built-in parser : The Java library has its own parser. The library is designed such that you can replace the built-in parser with an external implementation such as Xerces from Apache or Saxon. • Saxon : Saxon offers tools for parsing, transforming, and querying XML. • Xerces : Xerces is implemented in Java and is developed by the famous open source Apache Software Foundation.

        Extensible Stylesheet Language (XSL) XSL is a language for expressing stylesheets • support for browsing, printing, and aural rendering • formatting highly structured documents (XML) • performing complex publishing tasks: tables of contents, indexes, reports,... • addressing accessibility and internationalization issues • written in XML

        Figure 6.2: XSL Architecture Components XSL is constituted of three main components: • XSLT: a transformation language • XPath: an expression language for addressing parts of XML documents

        6.8 Extensible Stylesheet Language (XSL)

        Figure 6.3: XSL Transformations • FO: a vocabulary of formatting objects with their associated formatting properties XSL uses XSLT which uses XPath 6.8.1 XSL Transformations XSLT - Basic Principle Patterns and Templates • A style sheets describes transformation rules • A transformation rule: a pattern + a template • Pattern: a configuration in the source tree • Template: a structure to be instantiated in the result tree • When a pattern is matched in the source tree, the corresponding pattern is generated in the result tree An Example: Transformation <xsl:template match="Title">

        <xsl:apply-templates/>



        Input : < Title >Introduction< /Title > Output : < H1 >Introduction< /H1 > An Example: Formatting <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" result-ns="fo"> <xsl:template match="/">

        189

        190

        Chapter 6. XML- eXternal Markup Language

        <xsl:apply-templates/> <xsl:template match="para"> <xsl:apply-templates/> XPath: XML Path Language An elementary XPath expression contains • an axis, which specifies the tree relationship: child, descendants, ancestors, siblings, attributes,... • a node test, which specifies the node type • predicates, to further refine the set of nodes selected Example: all para children that have a type attribute with value warning child::para[attribute::type="warning"]

        XSL Usage • Format XML documents by generating FOs • Generate HTML or XHTML pages from XML data/documents • Transform XML documents into other XML documents • Generate some textual representation of an XML document • ...and more XSL may be used server-side or client-side, but is not intended to send FOs over the wire Implementation XSL software include: • XSLT transformation engines: 4XSLT, IE5, iXSLT, LotusXSL, Transformiix, Resin, Sablotron, Saxon, Xalan, XML Parser (Oracle), XT • FO formatters: FOP, FO2PDF, InDelv browser, Passive TeX, REXP • XSL stylesheet editors • Style sheets and transformation sheets

        News Feed What’s in a feed? A feed contains a list of items or entries, each of which is identified by a link. Each item can have any amount of other metadata associated with it as well. The most basic metadata for an entry includes a title for the link and a description of it; when syndicating news headlines, these fields might be used for the story title and the first paragraph or a summary, for example. For example, a simple entry might look like: Earth Invaded http://news.example.com/2004/12/17/invasion <description>The earth was attacked by an invasion fleet from halfway across the galaxy; luckily, a fatal

        6.9 News Feed

        191

        miscalculation of scale resulted in the entire armada being eaten by a small dog.

        Additionally, the feed itself can have metadata associated with it, so that it can be given a title , description, and other fields like publisher and copyright terms. The popular news feeds are RSS and ATOM. RSS-(Really Simple Syndication) RSS(Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format.English: This icon, known as the "feed ic... An RSS document which is called a "feed", "news feed", or "channel"’includes full or summarized text, plus metadata such as publishing dates and authorship.RSS feeds benefit publishers by letting them syndicate content automatically. Example: RSS Title <description>This is an example of an RSS feed http://www.someexamplerssdomain.com/main.html; Mon, 06 Sep 2010 00:01:00 +0000 Mon, 06 Sep 2009 16:45:00 +0000 1800 Example entry <description>Here is some text containing an interesting description. http://www.wikipedia.org/; unique string per item Mon, 06 Sep 2009 16:45:00 +0000

        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 Example Feed

        192

        Chapter 6. XML- eXternal Markup Language <subtitle>A subtitle. urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6 2003-12-13T18:30:02Z <entry>

        Atom-Powered Robots Run Amok urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2003-12-13T18:30:02Z <summary>Some text. John Doe <email>[email protected]


        RSS vs ATOM Comparing RSS and ATOM.

        Definition

        Content model

        Date formats

        Internationalization

        Modularity

        Publishing cols Required on a feed

        RSS Real Simple Syndication (RSS) is a family of web feeds formats that are used to publish frequently updated works. RSS 2.0 may contain either plain text or escaped HTML as a payload.

        ATOM Atom refers to a pair of standards for web feeds.

        RSS shows the date timestamps of data when the feed was created and last updated. RSS vocabulary has a mechanism to indicate a human language for the feed.

        Atom shows the date timestamp when the website was last updated.

        RSS vocabulary elements are unusable in other XML vocabularies. proto-

        content

        RSS has two main publishing protocols; Blogger protocol and MetaWeblog. RSS has a more loose approach and does not require much data.

        Atom offers a variety of payload types including plain text, escaped HTML, XHTML, XML, Base64encoded binary, and references to external content such as documents, video, audio streams, and so forth.

        Atom uses the standard xml:lang attribute. Atom also supports characters outside the US ASCII character set. Atom allows the reuse of elements outside the context of an Atom feed document. Atom has one standardized protocol.

        Atom is more restrictive require more data.

        6.10 Exercise Distinction between partial and excerpts Autodiscovery Aggregating and extracting

        193 RSS does not distinguish a partial from an excerpt.

        Atom distinguishes a partial from an excerpt.

        Not a standardized feature. RSS has a more complicated aggregating and extracting process.

        A standardized feature. Atom has an easier aggregating and extracting process.

        Exercise 1. 2. 3. 4. 5. 6. 7.

        Differentiate HTML and XML. Explain in detail about XML- DTDs. Explain in detail about XML Schemas with valid examples Explain in detail about XML parsing Explain XSL with examples. What is the importance of News feed? Explain. Differentiate RSS and ATOM.

        7. Creating and Using Forms

        Understanding Common Form Issues, GET vs. POST, Validating form input, Working with multiple forms, and Preventing Multiple Submissions of a form. Basic Database Concepts, Connecting to a MYSQL database, Retrieving and Displaying results, Modifying, Updating and Deleting data. MVC architecture. ********************* To create a fully functional web application, you need to be able to interact with your users. The common way to receive information from web users is through a form. Web forms are merely Hypertext Markup Language (HTML) elements. PHP 5 is built so that it seamlessly integrates with form elements. Over the past few versions of PHP, its methodology for dealing with form information has gradually evolved and is now quite robust.

        Understanding Common Form Issues When dealing with forms, the most important aspect to remember is that you are limited to a certain variety of fields that can be applied to a form. The fields that have been created are non-negotiable and work in only the way they were created to work. The < f orm > element bundles together all the form widgets (also known as controls or fields). A well-designed form, divides itself into logical chunks using the < f ieldset > element. Each chunk gets a title, courtesy of the < legend > element. The following Example demonstrate the forms registration.html Registration form

        196 Element TEXT INPUT PASSWORD INPUT HIDDEN INPUT SELECT LIST CHECKBOX RADIO TEXTAREA FILE SUBMIT RESET

        Chapter 7. Creating and Using Forms Description A simple text box A text box that hides the characters inputted A field that does not show on the form but can contain data A drop-down box with options A select box that can have multiple options selected A box that can be checked A radio button that can act as a choice A larger box that can contain paragraph-style entries An element that allows you to browse your computer for a file A button that will submit the form A button that will reset the form to its original state Table 7.1: HTML Form Elements

        Registration Form

        Personal Information

        <select id="gender">

        Contact Details

        Pick Your Favorite Animals


        7.1 Understanding Common Form Issues

        197



        GET vs. POST The two ways available to a web developer that the information entered into the form is transmitted to its destination by using method. the two methods are GET and POST. GET When sending data using the GET method, all fields are appended to the Uniform Resource Locator (URL) of the browser and sent along with the address as data. Sending data using the GET method means that fields are generally capped at 150 characters, which is certainly not the most effective means of passing information. It is also not a secure means of passing data, because many people know how to send information to a script using an address bar. PHP’s current methods for dealing with GET variable is the $_GET superglobal. Syntax is $_GET[’Variable Name’];. The following Example demonstrate the working of the GET method File Name: get.php Example for get

        GET Example:

        User Name:

        Password:


        Figure 7.1: Output of get.php File Name: get-demo.php

        198

        Chapter 7. Creating and Using Forms

        Example for GET Your password (with GET) : ". $_GET['pwd']; } else { echo "You must submit a value."; } ?>
        Try Again

        Figure 7.2: Output aftersubmit get.php (see the addressbar) when using the GET method, hitting the Refresh button after submitting data the browser will automatically send the data again. POST When sending data using the POST method, values are sent as standard input (the data will be sended through body not in URL). Sending data using the POST method is quite a bit more secure (because the method cannot be altered by appending information to the address bar) and can contain as much information as you choose to send. Therefore, whenever possible, use the POST method for sending information and then adjust your script to handle it. PHP ’s current methods for dealing with POST variable is the $_POST superglobal. Syntax is $_POST[’Variable Name’];. The following Example demonstrate the working of the POST method File Name: post.php

        7.1 Understanding Common Form Issues

        199

        Example for POST

        POST Example:

        User Name:

        Password:


        Figure 7.3: Output of post.php File Name: post-demo.php Example for POST Your password(with POST) :". $_POST['pwd'] ; } else { echo "You must submit a value."; } ?>
        Try Again

        Hitting the Refresh button after submitting data using the POST form, the browser will ask you if you want to resubmit the data that was passed to it previously. If you want to resend the data, you must select Yes(Resend) to this option. GET Vs POST The following are the key Difference and Comparisons between GET and POST methods.

        Validating form input validation —a way to catch mistakes when they happen (or even better, to prevent them from happening at all).

        200

        Chapter 7. Creating and Using Forms

        Figure 7.4: After submit the post.php (see addressbar)

        Figure 7.5: Refresh after submitting the form it asks above msg

        1 2 3

        4 5 6

        7 8

        GET Parameters remain in browser history because they are part of the URL. Can be bookmarked. GET requests are re-executed but may not be resubmitted to server if the HTML is stored in the browser cache. Easier to hack for script kiddies Only ASCII characters allowed. GET is less secure compared to POST because data sent is part of the URL. So it’s saved in browser history and server logs in plaintext. Restrictions on form data length GET method should not be used when sending passwords or other sensitive information.

        POST Parameters are not saved in browser history. Can not be bookmarked. The browser usually alerts the user that data will need to be re-submitted. More difficult to hack No restrictions. Binary data is also allowed. POST is a little safer than GET because the parameters are not stored in browser history or in web server logs. No restrictions on form length. POST method used when sending passwords or 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. Validatrion DEMO

        Please Enter valid User name
        "; } else if(strlen($_POST["uname"])<6){ echo "Please Enter valid User name with more than 6 chatrecters
        " }

        if($_POST["pwd"]==""){ echo "Please Enter valid Password
        "; } else if(strlen($_POST["pwd"])<6){ echo "Please Enter valid Password with more than 6 chatrecters
        "; } } ?>


        202

        Chapter 7. Creating and Using Forms

        NAME:
        PASSWORD:
        =6 && $_POST["pwd"]!="" && strlen($_POST["pwd"])>=6){ echo "Name:".$_POST['uname']."
        "; echo "Password: ".$_POST['pwd']."
        "; } } ?>

        Figure 7.6: Output of validation.php after submitting empty values In the above script: $_SERVER[“PHP_SELF”] The filename of the currently executing script, relative to the document root. The above program demonstrates the validation in same page. It is possible to perform the validations using GET and POST methods into the other pages. Working with multiple forms Sometimes you will need to collect values from more than one page. Most developers do this for the sake of clarity. By providing forms on more than one page, you can separate blocks of information and thus create an ergonomic experience for the user. The problem, therefore, is how to GET values from each page onto the next page and finally to the processing script. Being the great developer that you are, you can solve this problem and use the hidden input form type. When each page loads, you merely load the values from the previous pages into hidden form elements and submit them. page1.php Personal information

        7.1 Understanding Common Form Issues


        Figure 7.7: Output of page1.php page2.php Contact information
        NAME
        FATHER NAME
        MOTHER NAME
        GENDER MALE FEMALE
        " /> " /> " /> " />

        203

        204

        Chapter 7. Creating and Using Forms

        E-Mail
        Mobile
        ADDRESS


        Figure 7.8: Output of page2.php page3.php Educational Details
        " /> " /> " /> " /> " /> " /> " />
        SSC Percentage
        Intermediate/10+2
        UG


        page4.php

        7.1 Understanding Common Form Issues

        Figure 7.9: Output of page3.php

        Complete Information
        Personal Details
        NAME
        FATHER NAME
        MOTHER NAME
        GENDER
        Contact details
        E-Mail
        Mobile
        ADDRESS
        Educational details
        SSC Percentage
        Intermediate/10+2
        UG


        As you can see, by passing the values in the hidden form fields, you can continue to collect information.

        205

        206

        Chapter 7. Creating and Using Forms

        Figure 7.10: Output of page4.php Redisplaying Forms with Preserved Information and Error Messages When receiving information submitted from a user, the information may not be submitted in the format you need. To ensure that users do not GET frustrated, it is important to inform them of what they did wrong and clearly tell them how to fix the problem. It is also bad practice to force users to completely rewrite all the proper information they may have already submitted on the form. If users are forced to do redundant work, they may become irritated and potentially disregard your service altogether. Therefore, to keep users happy, it is important to validate properly and clearly while keeping matters as simple for them as possible. Example: Validatrion DEMO

        Please Enter valid User name
        "; } else if(strlen($_POST["uname"])<6){ echo "Please Enter valid User name with more than 6 chatrecters
        " }

        if($_POST["pwd"]==""){ echo "Please Enter valid Password
        "; } else if(strlen($_POST["pwd"])<6){ echo "Please Enter valid Password with more than 6 chatrecters
        "; }

        Understanding Common Form Issues

        207

        } ?>
        NAME: "/>
        PASSWORD: " />
        =6 && $_POST["pwd"]!="" && strlen($_POST["pwd"])>=6){ echo "Name:".$_POST['uname']."
        "; echo "Password: ".$_POST['pwd']."
        "; } } ?>

        Figure 7.11: Name with lessthan 6 characters and with out password

        208

        Chapter 7. Creating and Using Forms

        Figure 7.12: With out password and with name

        Figure 7.13: With valid inputs ..

        Global & Superglobal variables GLOBAL $GLOBALS — References all variables available in global scope An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array. Example: OUTPUT: $foo in global scope: Global content $foo in current scope: local content Superglobal variables Superglobals — Superglobals are built-in variables that are always available in all scope. Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. Superglobals were introduced to PHP 4.1. There is no need to do global $variable; to access them within functions or methods. These superglobal variables are: The $_SERVER superglobal contains information created by the web server—details regarding the server and client configuration and the current request environment. Examples: • $_SERVER[’HTTP_REFERER’]: The URL of the page that referred the user to the current location.

        Preventing Multiple Submissions of a Form

        209

        • $_SERVER[’REMOTE_ADDR’]: The client’s IP address. • The $_GET superglobal contains information pertinent to any parameters passed using the GET method. • The $_POST superglobal contains information pertinent to any parameters passed using the POST method. • The $_COOKIE superglobal stores information passed into the script through HTTP cookies. Such cookies are typically set by a previously executed PHP script through the PHP function setcookie(). Example: Write any script in this chapter(eg: validation/Working with multiple forms etc).

        Preventing Multiple Submissions of a Form One possible occurrence that happens often is that users become impatient when waiting for your script to do what it is doing, and hence they click the submit button on a form repeatedly. This can wreak havoc on your script because, while the user may not see anything happening, your script is probably going ahead with whatever it has been programmed to do. Of particular danger are credit card number submittals. If a user continually hits the submit button on a credit card submittal form, their card may be charged multiple times if the developer has not taken the time to validate against such an eventuality. You can deal with multiple submittal validation in essentially two ways. • Server side refers to a script located on the server that is receiving the data • client side is more browser related Preventing Multiple Submissions on the Server Side While you can accomplish this goal in a number of ways from a server-side perspective, we prefer to use a session-based method. Basically, once the submit button has been clicked, the server logs the request from the individual user. If the user attempts to resubmit a request, the script notes a request is already in motion from this user and denies the subsequent request. Once the script has finished processing, the session is unset, and you have no more worries. The following script Preventing Multiple Submissions on the Server Side
        Name::
        Password::



        p2.php:
        210

        Chapter 7. Creating and Using Forms

        } if($_SESSION['x']==TRUE){ mysql_connect("localhost","root",""); mysql_select_db("TEST"); mysql_query("INSERT INTO login('uname','pwd') VALUES('$name','$pwd')"); $_SESSION['x']=FALSE; for($i=0;$i<=2000000;$i++);//do nothing for($i=0;$i<=2000000;$i++);//do nothing for($i=0;$i<=2000000;$i++);//do nothing for($i=0;$i<=2000000;$i++);//do nothing for($i=0;$i<=2000000;$i++);//do nothing for($i=0;$i<=2000000;$i++);//do nothing for($i=0;$i<=2000000;$i++);//do nothing } echo "Successfully added to database"; session_unset(); ?>

        Preventing Multiple Submissions on the Client Side Handling multiple submittals from a client-side perspective is actually much simpler than doing it on the server side. With well-placed JavaScript, you can ensure that the browser will not let the submittal go through more than once. The problem with this method, of course, is that JavaScript is not always foolproof because of the user’s ability to turn it off. The following example uses JavaScript to cut off multiple submittals from a client-side (browser) level. <script> function checkandsubmit() { //Disable the submit button. document.test.submitbut.disabled = true; //Then submit the form. document.test.submit(); }
        Name::
        Password::



        After submitting the the button will be disabled as follows

        7.4 Handling Special Characters

        211

        Handling Special Characters An added security feature, particularly when dealing with database submittal, is validating against special characters being inserted into your script. Be it a database insertion script, a contact form, or even a mailer system, you always want to ensure that no malicious users are attempting to sabotage your script with bad (or special) characters. PHP allots a number of functions to use in this regard. string string string string

        trim ( string str [, string charlist] ) htmlspecialchars ( string string [, int quote_style [, string charset]] ) strip_tags ( string str [, string allowable_tags] ) addslashes ( string str )

        The following script demonstrates above functions Welcome to php"; $msg3="Welcome \n to \php"; echo "With out using trim(): **".$msg1."**
        "; echo "Using trim():**".trim($msg1)."**


        "; echo "With out using htmlspecialchars(): ".$msg2."
        "; echo "Using htmlspecialchars(): ".htmlspecialchars($msg2)."


        "; echo "Using strip_tags(): ".strip_tags($msg2)."


        "; echo "With out Using addslashes(): ".$msg3."
        "; echo "Using addslashes(): ".addslashes($msg3)."


        "; ?> OUTPUT: With out using trim(): ** Welcome to PHP ** Using trim():**Welcome to PHP** With out using htmlspecialchars(): Welcome to php Using htmlspecialchars(): Welcome to php Using strip_tags(): Welcome to php With out Using addslashes(): Welcome to \php Using addslashes(): Welcome to \\php

        • The trim() function removes any blank space found at the beginning or end of the submitted string. • The htmlspecialchars() function turns attempted HTML into its special character equivalent. • The strip_tags() function completely removes any characters it sees as being a tag.

        212

        Chapter 7. Creating and Using Forms

        • addslashes(), places a slash in front of any characters that could be harmful to the database such as apostrophes. The end result is a string that is quite squeaky clean

        File Uploads Handling file uploads in PHP is not exactly difficult from a syntax point of view, but it is important (extremely important in fact) to ensure that the file being uploaded is within the upload constraints you lay out for it. The following are the constrains of File : Size The size of the uploaded file (in bytes). You could easily find your server under some heavy loads if you are not careful about what size of files are being uploaded. Type The MIME type of the uploaded file. Ex: .jpeg, .pdf, .doc, etc,. Name The original filename that was uploaded. It is possible to change file name at the time of uploading. tmp_name The temporary name of the file that has been uploaded. error The error code that may be generated by the file upload. The following Example demonstrate file uploading using Form

        Pictures:



        $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; $name = $_FILES["pictures"]["name"][$key]; move_uploaded_file($tmp_name, "data/$name"); } } ?>

        Basic Database Concepts PHP 5 has the ability to connect to MySQL using some advanced options that have been released with the latest build of MySQL. Connecting to a MySQL Database To do any work with a MySQL database, you must first open a link to the database and connect to it. Performing such functionality in PHP is quick and efficient. You can use the function mysql_connect() to connect to a database. The prototype for mysql_connect() is as follows: resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]] );

        7.6 Basic Database Concepts

        213

        The following script demonstrate the database connection Successfully connected to the database..!!"; }else{ die("

        cannot connect to database..!!

        "); } mysql_close ($db); ?> ::::::::::OUTPUT:::::::::: Successfully connected to the database..!!

        In the above script, mysql_connect() pass the connection information like host name, MySQL database name and it’s password.This gives you access to any databases that are assigned to the user root. The mysql_close() function takes care of this handily and can receive the resource handler that was assigned with the mysql_connect() function as an argument to close. The prototype for mysql_close() is as follows: bool mysql_close ( [resource link_identifier] )

        Querying the Database To perform a query in PHP, you can use the function mysql_query(). It allows you to perform a myriad of SQL functions(such as insert, which allows you to enter data into a row; alter, which allows you to change the format of a table; select, whichallows you to return a row set from a table in the database; and delete, which allows you to remove a row in the database;) and is quite simple to use. The prototype for mysql_query() is as follows: resource mysql_query ( string query [, resource link_identifier] )

        All the examples in this chapter, assume you have a database set up called Text1 that contains a table called testing with the following structure: sno INT AUTO_INCREMENT PRIMARY KEY name VARCHAR(20) pwd VARCHAR(20) type VARCHAR(10)

        Figure 7.14: Database Table

        214

        Chapter 7. Creating and Using Forms

        The following example demonstrate insert data in to MySQL database. "; //echo "Back to main page"; } else { echo "ERROR"; } ?> :::::::::: OUTPUT :::::::::: Data entered Successfully

        Figure 7.15: After Exicution of above code Database table To perform a query on a database table, you must first specify which database (that is assigned to the current user) you want to perform this action use function mysql_select_db() Once you have a selected database, it is simply a matter of creating a query and executing it using the mysql_query() function. Insert data into above table using forms reg.html

        7.6 Basic Database Concepts

        215

        DATA BASE CONNECTION
        Registration
        NAME
        Password
        User Type<select name='type'>


        Figure 7.16: Output of reg.html test-db.php(Insertion is performed in this file)
        216

        Chapter 7. Creating and Using Forms

        $sql="INSERT INTO $tbl_name(name, pwd, type)VALUES('$name', '$pwd', '$type')"; $result=mysql_query($sql); // if successfully insert data into database, displays message "Successful". if($result){ echo "Data entered Successfully"; echo "
        "; echo "Back to main page"; } else { echo "ERROR"; } ?> :::::::::: OUTPUT :::::::::: Data entered Successfully Back to main page

        Figure 7.17: After submitting data using forms database

        Retrieving and Displaying Results In PHP, the most common method to retrieve a row in the database is with the mysql_fetch_array() function, which puts the results garnered from a row set into an array for ease of use. Its prototype is as follows: array mysql_fetch_array ( resource result [, int result_type] ) The following example outputs the results of the current database table.

        7.6 Basic Database Concepts

        217

        "; Print ""; Print ""; } ?>

        Figure 7.18: OUTPUT of the above program Login form validation with database values You will have plenty of opportunities to build a query on the fly. A fairly common example is receiving data from a form that will allow you to log into your account. While the functionality behind this is useful and rather powerful, it is also the preferred method for crackers to gain entry into your system. Login <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <style> .error { font-weight: bold; color: #FF0000; }

        218

        Chapter 7. Creating and Using Forms

        //Let's declare a submission value that tells you if you are fine. $goodtogo = true; //Validate the name. try { if (trim ($_POST['name']) == "" || trim ($_POST['pwd'])==""){ $goodtogo = false; throw new exception ("Sorry, you must enter your name & Password.
        "); } 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 ("

        User name and password matched

        .
        "); }else{ $goodtogo = false; throw new exception ("Sorry, you User name password not matched.
        "); } } } catch (exception $e) { ?><span class="error">getmessage(); ?>
        " method="post">

        Login form:

        User Name: "/>

        Password: " />


        In the above script we collect values from form and validate form values with database values.

        7.6 Basic Database Concepts

        219

        Figure 7.19: Invalid inputs

        Figure 7.20: Valid User name and passwords Deleting Data Removing data is largely the same as other row or useless data. You will definitely want to specify which record you are attempting to remove, as you can quite easily lose an entire table if you are not careful. The following example enables you to remove a record from your table. Should you want to remove an entire table‘s contents, simply leave out the where clause in the SQL code. The following script shows the delete a row in a table of MySQL database ad row is successfully deleted.."; } ?> ::::::::::: OUTPUT :::::::::: Data in 2ad row is successfully deleted..

        220

        Chapter 7. Creating and Using Forms

        Figure 7.21: After deletion Database Modifying Data Obviously, database functionality would be pretty useless if the data stored in the database itself could only remain static. Luckily, MySQL provides you with a means to modify certain data using UPDATE command. The following script shows the Updatation of MySQL database :::::::::: OUTPUT :::::::::: Data is successfully updated..

        Figure 7.22: After Modifying database.. Following example shows the change-password script Change password <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <style> .error { font-weight: bold; color: #FF0000; }

        Basic Database Concepts

        221


        try { if (trim ($_POST['opwd'])== "" ){ $goodtogo = false; throw new exception ("Sorry, you must enter your old password.
        "); }else if (trim ($_POST['pwd']) == "" || trim ($_POST['cpwd']) == "" ){ $goodtogo = false; throw new exception ("Sorry, you must enter your new password or Confirm password.
        "); } else if(trim ($_POST['pwd']) != trim ($_POST['cpwd'])){ $goodtogo = false; throw new exception ("Sorry, new password or Confirm password Must be same.
        "); } else if(trim ($_POST['opwd'])== "" || trim ($_POST['pwd']) != "" || trim ($_POST['cpwd']) != ""){ $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="TEST1"; // Database name $tbl_name="testing"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="UPDATE $tbl_name SET pwd='".$_POST['cpwd']."' WHERE pwd='".$_POST['opwd']."'"; $result=mysql_query($sql)or die(mysql_error()); if($result){ throw new exception ("Password is successfully changed.."); } }} catch (exception $e) { ?><span class="error">getmessage(); ?>
        222

        Chapter 7. Creating and Using Forms

        if (!$goodtogo){ ?>
        " method="post">

        Fill the following form:

        Old password: "/>

        New password: "/>

        Re-enter New password: "/>

        :::::::::: OUTPUT :::::::::: Password is successfully changed..

        Figure 7.23: After changing the password database

        MySQL Functions in php mysql_connect() Open a connection to a MySQL Server resource mysql_connect ([ string $server [, string $username [, string $password [, bool $new_link [, int $client_flags ]]]]] )

        server The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket. e.g.: localhost, 127.0.0.1:8080 etc., username the name of the user that owns the server process is used. eg: root password password of the given user. This is optional. new_link If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. It is also optional. Example: $db = mysql_connect(’localhost’, ’mysql_user’, ’mysql_password’);

        7.7 MySQL Functions in php

        223

        mysql_close() Close MySQL connection bool mysql_close ([ resource $link_identifier ] )

        mysql_close() closes the non-persistent connection to the MySQL server that’s associated with the specified link identifier. Using mysql_close() isn’t usually necessary, as non-persistent open links are automatically closed at the end of the script’s execution. link_identifier It close the MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. Returns TRUE on success or FALSE on failure. Example: mysql_close($db); mysql_select_db() Select a MySQL database bool mysql_select_db ( string $database_name [, resource $link_identifier ] )

        Returns TRUE on success or FALSE on failure. database_name: The name of the database that is to be selected. link_identifier If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. mysql_query() Send a MySQL query resource mysql_query ( string $query [, resource $link_identifier ] )

        mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that’s associated with the specified link_identifier. query: An SQL query The query string should not end with a semicolon. Data inside the query should be properly escaped. link_identifier If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. • For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. • For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. • The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data. • Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

        224

        Chapter 7. Creating and Using Forms

        mysql_fetch_array() Fetch a result row as an associative array, a numeric array, or both. array mysql_fetch_array ( resource $result [, int $result_type] )

        Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. result: The result resource that is being evaluated. This result comes from a call to mysql_query(). result_type: The type of array that is to be fetched. It’s a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH. Note: An important thing to note is that using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value. Example

        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:

        7.8 Model View Controller(MVC) Architecture

        225

        mysql_fetch_assoc() Fetch a result row as an associative array. array mysql_fetch_assoc ( resource $result )

        Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array. Note: An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value. More MySQL functions The following list of functions for mysql operations in php, the brief description of function names and it’s usages are listed below. Function mysql_affected_rows() mysql_client_encoding() mysql_create_db() mysql_data_seek() mysql_db_name() mysql_db_query() mysql_drop_db() mysql_errno() mysql_error() mysql_escape_string() mysql_info() mysql_insert_id() mysql_list_dbs() mysql_list_fields() mysql_num_fields() mysql_num_rows()

        Use GET number of affected rows in previous MySQL operation Returns the name of the character set Create a MySQL database Move internal result pointer Retrieves database name from the call to mysql_list_dbs() Selects a database and executes a query on it Drop (delete) a MySQL database Returns the numerical value of the error message from previous MySQL operation Returns the text of the error message from previous MySQL operation Escapes a string for use in a mysql_query() get information about the most recent query get the ID generated in the last query List databases available on a MySQL server List MySQL table fields get number of fields in result get number of rows in result Table 7.2: MySQL Functions

        Model View Controller(MVC) Architecture The model view controller pattern is the most used pattern for today‘s world web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there are more than a dozen PHP web frameworks based on MVC pattern. Despite the fact that the MVC pattern is very popular in PHP. The MVC pattern separates an application in Three modules: Model, View and Controller. Model The model is responsible to manage both the data and it’s behavior.The model is responsible for defining the formula’s used to perform such conversionsand when presented with a value and desired conversion senario, the model carries out the conversion and return the result. It stores and retrieves entities used by an application, usually from a database, and contains the logic implemented by the application.

        226

        Chapter 7. Creating and Using Forms

        View (presentation) The view is responsible to display the data provided by the model in a specific format. It has a similar usage with the template modules present in some popular web applications. Controller The controller handles the model and view layers to work together. The controller receives a request from the client, invokes the model to perform the requested operations and sends the data to the View. The view formats the data to be presented to the user, in a web application as an html output.

        Figure 7.24: MVC Architecture A simple way to think of this would be to consider the following: • A user interacts with the view - by clicking on a link or submitting a form. • The Controller handles the user input, and transfers the information to the model • The Model receives the information and updates it’s state (adds data to a database, for example, or calculates todays date) • The View checks the state of the Model and responds accordingly (listing the newly entered data, maybe) • The View waits for another interaction from the user.

        Exercise 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

        List and describe the different form elements associated with common form issues. Differentiate GET and POST methods. Explain with example how the validatation of forms is done using PHP. What is the advantage of super globals, explain with example? Write a PHP program to submit values using super globals and globals. How can we prevent multiple submissions of a form on server side? Explain with example.

        What is the advantage of Superglobals? Explain with example. Write a program to differentiate GET and POST methods. Explain briefly about the POST method with example. Differentiate Superglobals versus Globals. Explain briefly about the GET method with example. Differentiate GET and POST methods. 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 17. 18. 19. 20. 21. 22. 23. 24.

        Briefly explain about the MVC architecture. Explain the function used to connect to a MySQL database. How to perform a query in PHP? Explain with PHP code. Explain the function used to connect to a MySQL database. Explain mysql_select_db () function with example. Explain the function used to connect to a MySQL database with example. Explain about the most common method to retrieve the row from database in PHP. Explain the following functions with examples. (a) Mysql_connect() (b) mysql_close() (c) mysql_query() (d) mysql_select_db(). 25. Explain briefly the three components of MVC architecture. 26. How to perform querying the database? Explain with a PHP script.

        227

        8. AJAX-Asynchronous JavaScript And XML

        AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related technologies 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 XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. The two major features of AJAX allow you to do the following: • Make requests to the server without reloading the page • Receive and work with data from the server Question: Is Ajax just another name for XMLHttpRequest? Answer. No. XMLHttpRequest is only part of the Ajax equation. XMLHttpRequest is the technical component that makes the asynchronous server communication possible; Ajax is our name for the overall approach described in the article, which relies not only on XMLHttpRequest, but on CSS, DOM, and other technologies.

        How to make an HTTP request In order to make an HTTP request to the server with JavaScript, you need an instance of an object with the necessary functionality. This is where XMLHttpRequest comes in. Its predecessor originated in Internet Explorer as an ActiveX object called XMLHTTP. Then, Mozilla, Safari, and other browsers followed, implementing an XMLHttpRequest object that supported the methods and properties of Microsoft’s original ActiveX object. Meanwhile, Microsoft implemented XMLHttpRequest as well. // Old compatibility code, no longer needed.

        230

        Chapter 8. AJAX-Asynchronous JavaScript And XML

        if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ... httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 6 and older httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }

        After making a request, you will receive a response back. At this stage, you need to tell the XMLHttp request object which JavaScript function will handle the response, by setting the onreadystatechange property of the object and naming it after the function to call when the request changes state, like this: httpRequest.onreadystatechange = nameOfTheFunction;

        Note that there are no parentheses or parameters after the function name, because you’re assigning a reference to the function, rather than actually calling it. Alternatively, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous functions") to define the actions that will process the response, like this: httpRequest.onreadystatechange = function(){ // Process the server response here. };

        Next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open() and send() methods of the HTTP request object, like this: httpRequest.open('GET', 'http://www.example.org/some.file', true); httpRequest.send();

        • The first parameter of the call to open() is the HTTP request method - GET, POST, HEAD, or another method supported by your server. Keep the method all-capitals as per the HTTP standard, otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods • The second parameter is the URL you’re sending the request to. As a security feature, you cannot call URLs on 3rd-party domains by default. Be sure to use the exact domain name on all of your pages or you will get a "permission denied" error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld. If you really need to send a request to another domain • The optional third parameter sets whether the request is asynchronous. If true (the default), JavaScript execution will continue and the user can interact with the page while the server response has yet to arrive. This is the first A in AJAX. The parameter to the send() method can be any data you want to send to the server if POST-ing the request. Form data should be sent in a format that the server can parse, like a query string: "name=value&anothername="+encodeURIComponent(myVar)+"&so=on"

        or other formats, like multipart/form-data, JSON, XML, and so on. Note that if you want to POST data, you may have to set the MIME type of the request. For example, use the following before calling send() for form data sent as a query string: httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        Handling the server response

        231

        Handling the server response When you sent the request, you provided the name of a JavaScript function to handle the response: httpRequest.onreadystatechange = nameOfTheFunction;

        What should this function do? First, the function needs to check the request’s state. If the state has the value of XMLHttpRequest.DONE (corresponding to 4), that means that the full server response was received and it’s OK for you to continue processing it. if (httpRequest.readyState === XMLHttpRequest.DONE) { // Everything is good, the response was received. } else { // Not ready yet. }

        The full list of the readyState values is documented at XMLHTTPRequest.readyState and is as follows: • 0 (uninitialized) or (request not initialized) • 1 (loading) or (server connection established) • 2 (loaded) or (request received) • 3 (interactive) or (processing request) • 4 (complete) or (request finished and response is ready) (Source) Next, check the response code of the HTTP response. The possible codes are listed at the W3C. In the following example, we differentiate between a successful and unsuccessful AJAX call by checking for a 200 OK response code. if (httpRequest.status === 200) { // Perfect! } else { // There was a problem with the request. // For example, the response may have a 404 (Not Found) // or 500 (Internal Server Error) response code. }

        After checking the state of the request and the HTTP status code of the response, you can do whatever you want with the data the server sent. You have two options to access that data: httpRequest.responseText - returns the server response as a string of text httpRequest.responseXML - returns the response as an XMLDocument object you can traverse with JavaScript DOM functions Note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true). If you used a synchronous request you don’t need to specify a function, but this is highly discouraged as it makes for an awful user experience.

        Working with the XML response In the previous example, after receiving the response to the HTTP request we used the request object’s responseText property , which contained the contents of the test.html file. Now let’s try the responseXML property. First off, let’s create a valid XML document that we’ll request later on. The document (test.xml) contains the following:

        232

        Chapter 8. AJAX-Asynchronous JavaScript And XML

        I'm a test.

        In the script we only need to change the request line to: ... onclick="makeRequest('test.xml')"> ...

        Then in alertContents(), we need to replace the line alert(httpRequest.responseText); with: var xmldoc = httpRequest.responseXML; var root_node = xmldoc.getElementsByTagName('root').item(0); alert(root_node.firstChild.data);

        This code takes the XMLDocument object given by responseXML and uses DOM methods to access some of the data contained in the XML document. text.xml is as follows: I'm a test.

        AJAX-Call Back What is callback Let’s say we have a function F1 which calls F2. F2 is doing some async operation like AJAX. F1 would like to know the result of the ajax call. Now F1 will pass another function say C1 as an additional parameter to F2 which F2 will call after it process the ajax request completely. Think of it as F1 is taking service from F2 by giving the service details along with C1. When F2 is done with service, it informs F1 by calling C1 with some additional data. Why do we need callback We need callback because we don’t want to duplicate the ajax code every time we need. We want to create a generic ajax function which takes ajax details as input along with callback reference. After completing the call, it calls the callback so that caller can resume with the result of the ajax call. In the example above, we used makeAjaxCall to get the user details. Now lets say we want to show all the repositories of that user. For that, we need to make another kind of server call to get the repositories list. Clearly we don’t want to write another makeAjaxCall look alike function to perform the server call. We want to use the makeAjaxCall. For Ex function makeAjaxCall(url, methodType, callback){ var xhr = new XMLHttpRequest(); xhr.open(methodType, url, true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4){ if (xhr.status === 200){ console.log("xhr done successfully"); var resp = xhr.responseText; var respJson = JSON.parse(resp); callback(respJson); } else {

        Exercise

        233 console.log("xhr failed");

        } } else { console.log("xhr processing going on"); } } console.log("request sent succesfully"); } document.getElementById("userDetails").addEventListener("click", function(){ //git hub url to get a user details var userId = document.getElementById("userId").value; var URL = "https://api.github.com/users/"+userId; makeAjaxCall(URL, "GET", processUserDetailsResponse); }); document.getElementById("repoList").addEventListener("click", function(){ // git hub url to get btford details var userId = document.getElementById("userId").value; var URL = "https://api.github.com/users/"+userId+"/repos"; makeAjaxCall(URL, "GET", processRepoListResponse); }); function processUserDetailsResponse(userData){ console.log("render user details", userData); } function processRepoListResponse(repoList){ console.log("render repo list", repoList); }

        In the above example, you can see that there are two places where makeAjaxCall function is called and handling of server response is different for the both the scenario. makeAjaxCall is a kind of service function here which takes the ajax details along with callback reference. When it completes the ajax call, it informs the caller by calling its callback reference. Using the callback reference, we can create a reusable independent function which can just focus on making ajax call. In the callback function, we can process the data such as show the user details or listing down the repositories list. We can use the ajax service function at n number of places by passing ajax call details like URL, method and callback reference. Callbacks are great way to separate the core logic of ajax with the rest of the application. But unfortunately, it becomes very difficult to handle callback when we do series of ajax calls where one call is dependent on previous call. We might encounter difficulty in maintaining multiple callback references and handling multiple success and error conditions. Promise is a better way to manage multiple ajax calls.

        Exercise 1. 2. 3. 4. 5. 6.

        Explain AJAX and its advantages. Is Ajax just another name for XMLHttpRequest? Explain. Explain about Call backs in AJAX. Explain How to make an HTTP request in AJAX. Explain Working of the XML response in detail. Explain how AJAX Handling the server response.

        9. Web services

        A Web Service is a standards-based, language-agnostic software entity, that accepts specially formatted requests from other software entities on remote machines via vendor and transport neutral communication protocols, producing application specific responses. Advantages of Web services • Loosely Coupled Each service exists independently of the other services that make up the application. Individual pieces of the application to be modified without impacting unrelated areas. • Ease of Integration Data is isolated between applications creating ’silos’. Web Services act as glue between these and enable easier communications within and across organisations. • Service Reuse Takes code reuse a step further. A specific function within the domain is only ever coded once and used over and over again by consuming applications.

        Web service Architecture Every framework needs some sort of architecture to make sure the entire framework works as desired. Similarly, in web services, there is an architecture which consists of three distinct roles as given below • Provider - The provider creates the web service and makes it available to client application who want to use it. • Requestor - A requestor is nothing but the client application that needs to contact a web service. The client application can be a .Net, Java, or any other language based application which looks for some sort of functionality via a web service. • Broker - The broker is nothing but the application which provides access to the UDDI. The UDDI, as discussed in the earlier topic enables the client application to locate the web service. The diagram below showcases how the Service provider, the Service requestor and Service registry interact with each other.

        236

        Chapter 9. Web services

        Types of Web services

        237

        1. Publish - A provider informs the broker (service registry) about the existence of the web service by using the broker’s publish interface to make the service accessible to clients 2. Find - The requestor consults the broker to locate a published web service 3. Bind - With the information it gained from the broker(service registry) about the web service, the requestor is able to bind, or invoke, the web service.

        Types of Web services There are two types of web services. 1. SOAP: SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry standard protocol for designing and developing web services. Since it’s XML based, it’s platform and language independent. So our server can be based on JAVA and client can be on .NET, PHP etc. and vice versa. 2. REST: REST is an architectural style for developing web services. It’s getting popularity recently because it has small learning curve when compared to SOAP. Resources are core concepts of Restful web services and they are uniquely identified by their URIs.

        Java Web Services Java provides it’s own API to create both SOAP as well as REST web services. 1. JAX-WS: JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based Java API to build web services server and client application. 2. JAX-RS: Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST web services. JAX-RS uses annotations to simplify the development and deployment of web services. Both of these APIs are part of standard JDK installation, so we don’t need to add any jars to work with them. Both of these APIs use annotations very heavily. 9.3.1

        Example: Hello World JAX-WS Application TestService.java package com.journaldev.jaxws.service; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.ws.Endpoint; @WebService @SOAPBinding(style = SOAPBinding.Style.DOCUMENT) public class TestService { @WebMethod public String sayHello(String msg){ return "Hello "+msg; } public static void main(String[] args){ Endpoint.publish("http://localhost:8888/testWS", new TestService()); }

        238

        Chapter 9. Web services

        }

        WSDL – Web services description language A WSDL document is used to describe a web service. This description is required so that client applications are able to understand what the web service actually does. • The WSDL file contains the location of the web service and • The methods which are exposed by the web service. The WSDL file itself can look very complex to any user, but it contains all the necessary information that any client application would require to use the relevant web service. 9.4.1

        WSDL Creation The WSDL file gets created whenever a web service is built in any programming language. Since the WSDL file is pretty complicated to be generated from plain scratch, all editors such as Visual Studio for .Net and Eclipse for Java automatically create the WSDL file. Example <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/"> <schema targetNamespace=http://Guru99.com/Tutorial.xsd xmlns="http://www.w3.org/2000/10/XMLSchema"> <element name="TutorialNameRequest"> <element name="TutorialName" type="string"/> <element name="TutorialIDRequest"> <element name="TutorialID" type="number"/> <message name="GetTutorialNameInput"> <part name="body" element="xsd1:TutorialIDRequest"/> <message name="GetTutorialNameOutput"> <part name="body" element="xsd1:TutorialNameRequest"/>

        9.5 SOAP Introduction

        239

        <portType name="TutorialPortType"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <soap:operation soapAction="http://Guru99.com/GetTutorialName"/> <soap:body use="literal"/> <soap:body use="literal"/> <service name="TutorialService"> <documentation>TutorialService <port name="TutorialPort" binding="tns:TutorialSoapBinding"> <soap:address location="http://Guru99.com/Tutorial"/>

        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. 2. 3. 4.

        What is Web services? What is the Importance of it? What are the different types of Web services? Explain. Differentiate WSDL and SOAP. Explain Java Web services in detail with example.

        A. Sample Source Codes for Projects

        Sample Source Codes Config.php Welcome";

        242

        Chapter A. Sample Source Codes for Projects

        if($type==1){ header ("Location: admin_home.php"); }else if($type==2){ header ("Location: faculty_home.php"); }else if($type==3){ header ("Location: student_home.php") } } }

        Login

        ?>

        logout.php Sorting array Sorting PHP Indexed Array in Ascending Order Registration form
        A.1 Sample Source Codes

        243

        $username = $password = $confirm_password = ""; $username_err = $password_err = $confirm_password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Validate username if(empty(trim($_POST["username"]))){ $username_err = "Please enter a username."; } else{ // Prepare a select statement $sql = "SELECT id FROM users WHERE username = ?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "s", $param_username); // Set parameters $param_username = trim($_POST["username"]); // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ /* store result */ mysqli_stmt_store_result($stmt); if(mysqli_stmt_num_rows($stmt) == 1){ $username_err = "This username is already taken."; } else{ $username = trim($_POST["username"]); } } else{ echo "Oops! Something went wrong. Please try again later."; } } // Close statement mysqli_stmt_close($stmt); } // Validate password if(empty(trim($_POST['password']))){ $password_err = "Please enter a password."; } elseif(strlen(trim($_POST['password'])) < 6){ $password_err = "Password must have atleast 6 characters."; } else{ $password = trim($_POST['password']); } // Validate confirm password

        244

        Chapter A. Sample Source Codes for Projects if(empty(trim($_POST["confirm_password"]))){ $confirm_password_err = 'Please confirm password.'; } else{ $confirm_password = trim($_POST['confirm_password']); if($password != $confirm_password){ $confirm_password_err = 'Password did not match.'; } } // Check input errors before inserting in database if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){ // Prepare an insert statement $sql = "INSERT INTO users (username, password) VALUES (?, ?)"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);

        // Set parameters $param_username = $username; $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a pass // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ // Redirect to login page header("location: login.php"); } else{ echo "Something went wrong. Please try again later."; } } // Close statement mysqli_stmt_close($stmt); } // Close connection mysqli_close($link); } ?> <meta charset="UTF-8"> Sign Up body{ font: 14px sans-serif; }

        A.1 Sample Source Codes

        245

        .wrapper{ width: 350px; padding: 20px; }

        Sign Up

        Please fill this form to create an account.

        " method="post">

        Already have an account? Login here.



        B. Interview Questions

        There is given PHP interview questions and answers that has been asked in many companies. Let’s see the list of top PHP interview questions. 1. What is PHP? PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language that is widely used for web development. It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC etc. 2. What is PEAR in PHP? PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries. It also provide a command line interface to install "packages" automatically. 3. Who is known as the father of PHP? Rasmus Lerdorf 4. What was the old name of PHP? Personal Home Page. 5. Explain the difference b/w static and dynamic websites? In static websites, content can’t be changed after running the script. You can’t change anything in the site. It is predefined. In dynamic websites, content of script can be changed at the run time. Its content regenerated every time the user visit or reload. Google, yahoo and every search engine is the example of dynamic website. 6. What is the use of "echo" in php? It is used to print a data in the webpage, Example: , The following code print the text in the webpage. 7. How to include a file to a php page? We can include a file using "include() " or "require()" function with file path as its parameter. 8. What’s the difference between include and require? If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will

        248

        Chapter B. Interview Questions

        continue. 9. require_once(), require(), include().What is difference between them? require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don’t include the file more times and you will not get the "function re-declared" error. 10. Differences between GET and POST methods ? We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method . 11. How to declare an array in php? Eg : var $arr = array('apple', 'grape', 'lemon');

        12. What is the use of ’print’ in php? This is not actually a real function, It is a language construct. So you can use with out parentheses with its argument list. Example print('PHP Interview questions'); print('Job Interview ');

        13. What is use of in_array() function in php ? in_array used to checks if a value exists in an array 14. What is use of count() function in php ? count() is used to count all elements in an array, or something in an object 15. What’s the difference between include and require? It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue. 16. What is the difference between Session and Cookie? The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking 17. How to set cookies in PHP? Setcookie("sample", "ram", time()+3600);

        18. How to Retrieve a Cookie Value? echo $_COOKIE["user"];

        19. How to create a session? How to set a value in session ? How to Remove data from a session? Create session : session_start(); Set value into session : $_SESSION['USER_ID']=1; Remove data from a session : unset($_SESSION['USER_ID'];

        249 20. what types of loops exist in php? for,while,do while and foreach (NB: You should learn its usage) 21. How to create a mysql connection? mysql_connect(servername,username,password); 22. How to select a database? mysql_select_db($db_name); How to execute an sql query? How to fetch its result ? $my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); $result = mysql_fetch_array($my_qry); echo $result['First_name'];

        23. Write a program using while loop $my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); while($result = mysql_fetch_array($my_qry)) { echo $result['First_name'.]."
        "; }

        24. How we can retrieve the data in the result set of MySQL using PHP? (a) mysql_fetch_row (b) mysql_fetch_array (c) mysql_fetch_object (d) mysql_fetch_assoc 25. What is the use of explode() function ? Syntax : array explode ( string $delimiter , string $string [, int $limit ] );

        This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter. 26. What is the difference between explode() and split() functions? Split function splits string into array by regular expression. Explode splits a string into array by string. 27. What is the use of mysql_real_escape_string() function? It is used to escapes special characters in a string for use in an SQL statement 28. Write down the code for save an uploaded file in php. if ($_FILES["file"]["error"] == 0) { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; }

        29. How to create a text file in php? $filename = "/home/user/guest/newfile.txt"; $file = fopen( $filename, "w" );

        250

        Chapter B. Interview Questions if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple test\n" ); fclose( $file );

        30. How to strip whitespace (or other characters) from the beginning and end of a string ? The trim() function removes white spaces or other predefined characters from both sides of a string. 31. What is the use of header() function in php ? The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function. 32. How to redirect a page in php? The following code can be used for it, header("Location:index.php"); 33. How stop the execution of a php scrip ? exit() function is used to stop the execution of a page 34. How to set a page as a home page in a php based site ? index.php is the default name of the home page in php based sites 35. How to find the length of a string? strlen() function used to find the length of a string 36. what is the use of rand() in php? It is used to generate random numbers.If called without the arguments it returns a pseudorandom 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






        44. Define Object-Oriented Methodology Object orientation is a software/Web development methodology that is based on the modeling a real world system.An object is the core concept involved in the object orientation. An object is the copy of the real world enity.An object oriented model is a collection of objects and its inter-relationships 45. How do you define a constant? Using define() directive, like define ("MYCONSTANT",150) 46. How send email using php? To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can’t send email from localhost. eg : mail($to,$subject,$message,$headers);

        47. How to find current date and time? The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional - if you don’t, the current timestamp will be used. 48. Difference between mysql_connect and mysql_pconnect? There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the databasenewconnection while using mysql_pconnect , the function would first try to find a (persistent) link that’s already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection... the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use. 49. What is the use of "ksort" in php? It is used for sort an array by key in reverse order. 50. What is the difference between $var and $$var? They are both variables. But $var is a variable with a fixed name. $$var is a variable who’s name is stored in $var. For example, if $var contains "message", $$var is the same as $message. 51. What are the encryption techniques in PHP MD5 PHP implements the MD5 hash algorithm using the md5 function, eg : $encrypted_text = md5 ($msg); mcrypt_encrypt :- string mcrypt_encrypt ( string $cipher , string $key , string $data

        Encrypts plaintext with given parameters 52. What is the use of the function htmlentities? htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities. 53. How to delete a file from the system Unlink() deletes the given file from the file system. 54. How to get the value of current session id? session_id() function returns the session id for the current session.

        252

        Chapter B. Interview Questions

        55. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

        56.

        57.

        58. 59. 60.

        61.

        • Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both. • mysql_fetch_object ( resource result ) Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows mysql_fetch_row() fetches one row of data from the result associated with the specified • result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0. What are the different types of errors in PHP ? Here are three basic types of runtime errors in PHP: • Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behavior. • Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place. what is sql injection ? SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications What is x+ mode in fopen() used for? Read/Write. Creates a new file. Returns FALSE and an error if file already exists How to find the position of the first occurrence of a substring in a string strpos() is used to find the position of the first occurrence of a substring in a string Distinguish between urlencode and urldecode? This method is best when encode a string to used in a query part of a url. it returns a string in which all non-alphanumeric characters except -_. have replece with a percentege(%) sign . the urldecode −>Decodes url to encode string as any %and other symbole are decode by the use of the urldecode() function. How can we know the number of days between two given dates using PHP? The start date and end date can be first found as shown below: $date1= strotime($start_date); $date2= strotime($end_date); $date_diff = (($date1)- ($date2)) / (60*60*24)

        62. Write the statements that are used to connect PHP with MySQL The statements that can be used to connect PHP wil MySQL is:

        This statement gets the resource of the localhost. There are other different ways with
        253 mysql_connect('localhost','rasmus','foobar', true,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS); ?>

        Related Documents

        Wt
        May 2020 5
        Wt
        June 2020 8
        Textbook
        June 2020 7
        As Per Ram Sir.pdf
        July 2020 5
        Geography As Per Jainism
        November 2019 16

        More Documents from ""

        User's Details

        SNONameUser Type
        ".$info[0] . " ".$info[1] . " ".$info[3] . "