Chapter -1 Internet Basics Introduction Everything has to begin somewhere, so our journey will start with a focused history lesson. Below I am going to give you a brief overview of the creation of the Internet, the World Wide Web, and the web standards that this entire series focuses upon. I think it is useful and interesting to understand how we got to where we are, but it will be short enough so you don’t get overwhelmed, and can get into the details nice and quickly. If any terms are unfamiliar to you, don’t worry; if they’re important for learning web development they’ll be defined in the later articles that go into more depth on each subject, and you can always Google them! If you are already familiar with the history of the Internet or the World Wide Web, feel free to skip to the section on web standards. The article contents are as follows: The Internet’s origins The creation of the world wide web o The browser wars The coming of web standards o The formation of the W3C o The web standards project o The rise of web standards Summary Further reading Exercise questions The Internet’s origins On the fourth of October in 1957 an event occured that would change the world. The Soviet Union successfully launched the first satellite into Earth’s orbit. Called Sputnik 1, it shocked the world—especially the United States of America, who had their own programme of satellite launches underway, but had yet to launch.This event lead directly to the creation of the US Department of Defence ARPA (the Advanced Research Projects Agency), due to a recognised need for an organisation that could research and develop advanced ideas and technology beyond the currently identified needs. Perhaps their most famous project (certainly the most widely used) was the creation of the Internet. In 1960, psychologist and computer scientist Joseph Licklider published a paper entitled ManComputer Symbiosis, which articulated the idea of networked computers providing advanced information storage and retrieval. In 1962, whilst working for ARPA as the head of the information processing office, he formed a group to further computer research, but left the group before any actual work was done on the idea.The plan for this computer network (to be called ARPANET) was presented in October 1967, and in December 1969 the first four-computer network was up and running. The core problem in creating a network was how to connect ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
separate physical networks without tying up network resources for constant links. The technique that solved this problem is known as packet switching and it involves data requests being split into small chunks (packets,) which can be processed quickly without blocking communication from other parties—this principle is still used to run the Internet today. This concept received wider adoption, with several other networks springing up using the same packet switching technique—for example, X.25 (developed by the International Telecommunication Union) formed the basis of the first UK university network JANET (allowing UK universities to send and receive files and emails) and the American public network CompuServe (a commercial enterprise allowing small companies and individuals access to timeshared computer resources, and then later Internet access.) These networks, despite having many connections, were more private networks than the Internet of today.This proliferation of different networking protocols soon became a problem, when trying to get all the separate networks to communicate. There was a solution in sight however—Robert Kahn, whilst working on a satellite packet network project for ARPA, started defining some rules for a more open networking architecture to replace the current protocol used in ARPANET. Later joined by Vinton Cerf from Stanford University, the two created a system that masked the differences between networking protocols using a new standard. In the publication of the draft specification in December 1974, this was called the Internet Transmission Control Program.This specification reduced the role of the network and moved the responsibility of maintaining transmission integrity to the host computer. The end result of this was that it became possible to easily join almost all networks together. ARPA funded development of the software, and in 1977 a successful demonstration of three different networks communicating was conducted. By 1981, the specification was finalised, published and adopted; and in 1982 the ARPANET connections outside of the US were converted to use the new TCP/IP protocol. The Internet as we know it had arrived. The creation of World Wide Web Gopher was an information retrieval system used in the early 1990s, providing a method of delivering menus of links to files, computer resources and other menus. These menus could cross the boundaries of the current computer and use the Internet to fetch menus from other systems. It was very popular with universities looking to provide campus-wide information and large organisations looking to centralise document storage and management.Gopher was created by the University of Minnesota. In February, 1993, they announced that it was going to charge licensing fees for the use of their reference implementation of the Gopher server. As a consequence, many organisations started to look for alternatives to Gopher.The European Council for Nuclear Research (CERN) in Switzerland had such an alternative. Tim Berners-Lee had been working on a information management system, in which text could contain links and references to other works, allowing the reader to quickly jump from document to document. He had created a server for publishing this style of document (called hypertext) as well as a program for reading them, which he had called WorldWideWeb. This software had first been released in 1991, however, it took two events to cause an explosion in popularity and the eventual replacement of Gopher. ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
On the thirtieth of April in 1993 CERN released the source code of WorldWideWeb into the public domain, so anyone could use or build upon the software without charge. Then, later in the same year, the National Center for Supercomputing Applications (NCSA) released a program that was a combined web browser and Gopher client, called Mosaic. This was originally only available on Unix machines and in source code form, but in December 1993 Mosaic provided a new version with installers for both Apple Macintosh and Microsoft Windows. Mosaic rapidly increased in popularity, and with it the Web.The number of available web browsers increased dramatically, many created by research projects at universities and corporations, such as Telenor (a Norwegian communications company,) which created the first version of the Opera browser in 1994. The browser wars The popularisation of the web brought commercial interests. Marc Andreessen left NCSA and together with Jim Clark founded Mosaic Communications, later renamed to Netscape Communications Corporation, and started work on what was to become Netscape Navigator. Version 1.0 of the software was released in December 1994.Spyglass Inc. (the commercial arm of NCSA) licensed their Mosaic technology to Microsoft to form the basis of Internet Explorer. Version 1.0 was released in August 1995.A rapid escalation soon followed, with Netscape and Microsoft each trying to get a competitive edge in terms of the features they support in order to attract developers. This has since become known as the browser wars. Opera maintained a small but steady presence throughout this period, and tried to innovate and support web standards as well as possible in these times. The coming of web standards During the browser wars, Microsoft and Netscape focused on implementing new features rather than on fixing problems with the features they already supported, and adding proprietary features and creating features that were in direct competition with existing features in the other browser, but implemented in an incompatible way.Developers at the time were forced to deal with ever increasing levels of confusion when trying to build web sites, sometimes to the extent of building two different but effectively duplicate sites for the two main browsers, and other times just choosing to support only one browser, and blocking others from using their sites. This was a terrible way of working, and the inevitable backlash from developers was not far away. The formation of the W3C In 1994, Tim Berners-Lee founded the World Wide Web Consortium (W3C) at the Massachusetts Institute of Technology, with support from CERN, DARPA (as ARPA had been renamed to) and the European Commission. The W3C’s vision was to standardize the protocols and technologies used to build the web such that the content would be available to as wide a population of the world as possible.During the next few years, the W3C published several specifications (called recommendations) including HTML 4.0, the format for PNG images, and ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Cascading Style Sheets versions 1 and 2.However, the W3C did not (and still do not) enforce their recommendations. Manufacturers only had to conform to the W3C documents if they wished to label their products as W3C-compliant. In practice, this was not a valuable selling point as almost all users of the web did not know, nor probably care, who the W3C were (this is still the case, to a large extent). Consequently, the browser wars of the nineties continued unabated. The Web Standards Project In 1998, the browser market was dominated by Internet Explorer 4 and Netscape Navigator 4. A beta version of Internet Explorer 5 was released, and it implemented a new and proprietary dynamic HTML. This meant that professional web developers needed to know five different ways of writing JavaScript.As a result, a group of professional web developers and designers banded together. This group called themselves the Web Standards Project (WaSP). The idea was that by calling the W3C documents standards rather than recommendations, they might be able to convince Microsoft and Netscape to support them.The early method of spreading the call to action was to use a traditional advertising technique called a roadblock, where a company would take out an advert on all broadcast channels at the same time, so no matter how a viewer would flick between channels, they would get exactly the same message. The WaSP published an article simultaneously on various web development focused sites including builder.com, Wired online, and some popular mailing lists.Another technique the WaSP used was to ridicule the companies involved with the W3C (and other standards bodies) that focused more on creating new, often self-serving, features rather than working to get the basic existing standards supported correctly in their products to start with (this includes some browser companies that shall remain nameless here). This doesn't mean that the WaSP ridiculed the W3C themselves, rather they ridiculed the companies that became W3C members and then misbehaved. This all sounds a bit negative, but the WaSP didn’t just sit there criticising people—they also helped. Seven members formed the CSS Samurai, who identified the top ten problems with the CSS support in Opera and other browsers (Opera fixed their problems, others did not). The rise of web standards In 2000, Microsoft released Internet Explorer 5 Macintosh Edition. This was a very important milestone, it being the default browser installed with the Mac OS at the time, and having a reasonable level of support for the W3C recommendations too. Along with Opera's decent level of support for CSS and HTML, it contributed to a general positive movement, where web developers and designers felt comfortable designing sites using web standards for the first time.The WaSP persuaded Netscape to postpone the release of the 5.0 version of Netscape Navigator until it was much more compliant (this work formed the basis of what is now Firefox, a very popular browser). The WaSP also created a Dreamweaver Task Force to encourage Macromedia to change their popular web authoring tool to encourage and support the creation of compliant sites.The popular web development site A List Apart was redesigned early in 2001 and in an article describing how and why, stated: ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
In six months, a year, or two years at most, all sites will be designed with these standards. […] We can watch our skills grow obsolete, or start learning standards-based techniques now. That was a little optimistic—not all sites, even in 2008, are built with web standards. But many people listened. Older browsers decreased in market share, and two more very high profile sites redesigned using web standards: Wired magazine in 2002, and ESPN in 2003 became field leaders in supporting web standards and new techniques. Also in 2003, Dave Shea launched a site called the CSS Zen Garden. This was to have more impact on web professionals than anything else, by truly illustrating that the entire design can change just by changing the style of the page; the content could remain identical. Since then in the professional web development community web standards have become de rigeur. And in this series, we will give you an excellent grounding in these techniques so that you can develop websites just as clean, semantic, accessible and standards-compliant as the big companies’. History of the Internet The history of the Internet starts in the 1950s and 1960s with the development of computers. This began with point-to-point communication between mainframe computers and terminals, expanded to point-to-point connections between computers and then early research into packet switching. Packet switched networks such as ARPANET, Mark I at NPL in the UK, CYCLADES, Merit Network, Tymnet, and Telenet, were developed in the late 1960s and early 1970s using a variety of protocols. The ARPANET in particular led to the development of protocols for internetworking, where multiple separate networks could be joined together into a network of networks. In 1982 the Internet Protocol Suite (TCP/IP) was standardized and the concept of a worldwide network of fully interconnected TCP/IP networks called the Internet was introduced. Access to the ARPANET was expanded in 1981 when the National Science Foundation (NSF) developed the Computer Science Network (CSNET) and again in 1986 when NSFNET provided access to supercomputer sites in the United States from research and education organizations. Commercial internet service providers (ISPs) began to emerge in the late 1980s and 1990s. The ARPANET was decommissioned in 1990. The Internet was commercialized in 1995 when NSFNET was decommissioned, removing the last restrictions on the use of the Internet to carry commercial traffic. Since the mid-1990s the Internet has had a drastic impact on culture and commerce, including the rise of near instant communication by electronic mail, instant messaging, Voice over Internet Protocol (VoIP) "phone calls", two-way interactive video calls, and the World Wide Web with its discussion forums, blogs, social networking, and online shopping sites. The research and education community continues to develop and use advanced networks such as NSF's very high speed Backbone Network Service (vBNS), Internet2, and National LambdaRail. Increasing amounts of data are transmitted at higher and higher speeds over fiber optic networks ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
operating at 1-Gbit/s, 10-Gbit/s, or more. The Internet continues to grow, driven by ever greater amounts of online information and knowledge, commerce, entertainment and social networking. It is estimated that in 1993 the Internet carried only 1% of the information flowing through two-way telecommunication, by 2000 this figure had grown to 51%, and by 2007 more than 97% of all telecommunicated information was carried over the Internet.[1 History of the World Wide Web The World Wide Web ("WWW" or simply the "Web") is a global information medium which users can read and write via computers connected to the Internet. The term is often mistakenly used as a synonym for the Internet itself, but the Web is a service that operates over the Internet, as e-mail does. The history of the Internet dates back significantly further than that of the World Wide Web. The hypertext portion of the Web in particular has an intricate intellectual history; notable influences and precursors include Vannevar Bush's Memex, IBM's Generalized Markup Language and Ted Nelson's Project Xanadu. The concept of a home-based global information system goes at least as far back as "A Logic Named Joe", a 1946 short story by Murray Leinster, in which computer terminals, called "logics," were in every home. Although the computer system in the story is centralized, the story captures some of the feeling of the ubiquitous information explosion driven by the Web. Uniform ResourceLocators (URLs) URLs, or Uniform Resource Locators, are the method by which documents or data are addressed in the World Wide Web. The URL contains the following information: the internet name of the site containing the resource (document or data) the type of service the resource is served by (eg, HTTP, Gopher, WAIS) the Internet port number of the service. If this is omitted the browser assumes a commonly accepted default value. the location of the resource in the directory structure of the server. URLs are more sophisticated than this brief introduction would imply. For more detail, have a look at the URL overview document, found at the URL: http://www.w3.org/hypertext/WWW/Addressing/URL/Overview.html. Structure of an URL The following is an outline of the most common form of a URL:
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
| | | | | |service | | | | |____ host ______| | | | | | |port| | | file and | |_ resource details _| 1. Service The above figure gives a general outline of URL structure. This outline if followed by most, but not all, URLs. Specific cases are discussed in subsequent sections. The first part is the service specifier, (here HTTP service) which specifies the access method. Specifically this is the part before the colon. Some examples of services are: http:, gopher:, wais: and ftp:. 2. Address and Port number The second part is usually the internet address of the server, indicated by the double forward slash (//). This address can also contain the (optional) port number the service listens at. The full name is then specified by a string like //www.address.edu:1234/, where :1234 means Port number 1234. If you want to use the default port number you can leave out both the colon and the number, i.e. //www.address.edu/. 3. Resource Location The forward slash after the host and port specifications indicates the end of the address and the beginning of the specification for the file/resource to be accessed. This field varies depending on the service being accessed. A few simple examples follow: more detailed ones are given in the documents listed below. 4. Special Cases In some cases the internet address and resource location are omitted. The common examples of this are news: (for accessing Usenet news group information) and mailto: (for sending e-mail). 5. Query Strings The URL scheme also allows you to include a query string that is to be passed to the designated URL. This is indicated by placing a question mark at the end of the URL, followed by the desired query string. For example: http://www.where.edu/cgi-bin/program?query_string_data
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
The query string must be specially encoded, using what is known as URL encoding. This is discussed in the CGI documentation found at NCSA and elsewhere in this document collection. Some Simple URL Examples http://info.cern.ch/hypertext/WWW/Addressing/URL/Overview.html Retrieve the named HTML document from the CERN http server running on the default port. gopher://gumby.brain.headache.edu:151/7fonebook.txt Access the searchable index 'fonebook.txt' from the named gopher server, running on port number 151. news:alt.rec.motorcycle Access the newsgroup alt.rec.motorcycle. For detailed information on the different URL formats see: HTTP Gopher FTP WAIS Telnet/tn3270/rlogin Usenet Mailto What's inan HTTP request? Whenever your web browser fetches a file (a page, a picture, etc) from a web server, it does so using HTTP - that's "Hypertext Transfer Protocol". HTTP is a request/response protocol, which means your computer sends a request for some file (e.g. "Get me the file 'home.html'"), and the web server sends back a response ("Here's the file", followed by the file itself). That request which your computer sends to the web server contains all sorts of (potentially) interesting information. We'll now examine the HTTP request your computer just sent to this web server, see what it contains, and find out what it tells me about you. The analysis Source IP address, port and proxy Source IP address: 115.111.105.154 Source port:
4948
Via:
not present
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
X-Forwarded-For: not present
In order to send the appropriate response back to your computer, the web server necessarily knows your computer's IP address, and a port number to which to send the response. Your IP address seems to be 115.111.105.154, and the port number used was 4948. On the other hand, there could be one or more proxy servers between your computer and the web server. If the HTTP request includes the header "Via", or "X-Forwarded-For", then that's a strong indication that there is at least one proxy server somewhere along the line. If neither of those headers were present, that could mean that no proxy servers were involved, or it could mean that they just chose not to "reveal" themselves by adding those headers. In this case since there is neither a "Via" header nor a "X-Forwarded-For" header, there quite possibly isn't a proxy between your computer and the web server. However, this isn't definite - it might be that there is a proxy, but it just chose not to add the "Via" / "X-ForwardedFor" headers. Your IP address For now we'll assume your IP address is 115.111.105.154. Let's see what we know about that address. (Note, this section is nothing to do with HTTP in particular; this is just an example of what information can be determined from an IP address). IP address: 115.111.105.154 DNS name: 115.111.105.154.static-pune.vsnl.net.in
Lots more interesting information can be learned from your IP address. For example whereabouts you are on the Internet, (roughly) what city you're in, and who your ISP is. Destination IP address, port, host and protocol Destination IP address: 81.187.237.83 Destination port:
80
Host:
djce.org.uk
Protocol:
INCLUDED
These headers tell us which web server you were trying to contact. If that seems odd, bear in mind that many web sites can be "hosted" on a single server, so when the request is received it ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
needs to know which web site you were attempting to access. The protocol used will almost always be either "HTTP/1.1" or "HTTP/1.0", and is a property of your computer's web browser and any proxies through which the request might have passed. Requested URI Requested URI: /dumprequest
Together with the 'Host' header and the destination port number (above), this specifies the document which should be retrieved. Given all these values we can determine that the URL of the document which is being retrieved is: http://djce.org.uk/dumprequest Request method and content Request method: GET Data:
none
The request method is usually either "GET" or "POST". Basically if you fill in and submit a form on a web page it might generate a POST request (or it might be "GET"), whereas if you just click on a link, or activate one of your browser's "bookmarks" or "favourites", then the request method will always be "GET". Therefore, if it's "POST", we can tell that a form was definitely submitted. The contents of the form would appear here, and there would also be some "Content" headers describing the data. Web browsers generate two kinds of "POST" data: either "multipart/form-data", which is used when uploading files to a web server, or the more common "application/x-www-form-urlencoded". User agent User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022) Accept:
image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.msxpsdocument, application/xaml+xml, */*
AcceptEncoding:
gzip, deflate
AcceptLanguage:
en-us
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
The User-Agent header describes your web browser. Typically it contains the browser name and version (e.g. Firefox 1.0.7), your Operating System and version (e.g. Windows XP), and possibly additional information (such as which "service packs" you have installed). The "Accept" headers describe what sort of things the web browser can handle, and what it would prefer to be given if there's a choice. The "Accept" header itself describes which document types the web browser can handle, so for example we can tell whether your browser is capable of handling "image/png" graphics. The "Accept-Charset" header describes what character sets are acceptable, so we can make some guesses as to what part of the world you might be in, and what language you might speak. For example, western European or north American users quite possibly only understand the "iso8859-1", "us-ascii" and "utf-8" character sets, whereas "big5" would suggest that you might be Chinese. "Accept-Encoding" describes the ability of your web browser to handle compressed transfer of documents. Nothing too interesting there, but it's another snippet of information about the browser you're using. "Accept-Language" is more interesting though; it tells us what language(s) you prefer to receive your documents in - again, if the web server offers a choice. For example, if the header tells us that your preference is for "en-gb" followed by "en", that means you're probably an English-speaking Briton. "pt-br" on the otherhand would suggest a Portuguese-speaking Brazilian. Referring page Re http://www.google.co.in/url?sa=t&source=web&cd=2&ved=0CDcQFjAB&url=http%3A%2 fer F%2Fdjce.org.uk%2Fdumprequest&rct=j&q=HTTP%20request%20and%20responce&ei=X er: TZ3TpS8LsL5rAez37DAAw&usg=AFQjCNEeAn5wSZMp_y_oTmOKonq482sS9A
The "referer" header tells us which document referred you to us - in essence, if you followed a link to get to this page, it is the URL of the page you came from to get here. If on the other hand you didn't follow a link - maybe you clicked on a browser "bookmark", or maybe you just typed the address of this page directly into your browser - then the "referer" will be missing. And yes, that isn't how it should be spelt. :-( Cookies Cookie: not present
Every time a web server provides you with a response (a page, a graphic, etc), it has the opportunity to send your browser a "cookie". These cookies are small pieces of information ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
which your browser stores, and then sends back to that same web server whenever you subsequently request a document. So there's two important points here: (1) each cookie is only sent back to the same web site as it came from in the first place, and (2) the "contents" of the cookie (the data it contains) can only be made up of whatever information the web server already knew anyway. For example, a web server can't just say "send me a cookie containing your e-mail address" unless that same web server had already sent you that information in the first place. Connection control Connection: Keep-Alive Keep-Alive: not present
These headers are used to fine-tune the network traffic between you and the web server. They don't tell us much, except a little about the capabilities of your web browser. Cache control Pragma:
not present
Cache-Control:
not present
If-Modified-Since: not present
These headers control cacheing of the document. By examining them the we can detect if you used your browser's "refresh" button to force the page to reload. For example, Mozilla (Netscape 6) sets "Cache-Control" to "max-age=0" when you use the "reload" button. MSIE 5.5 sets it to "no-cache" if you do a "hard" reload (while holding down the "control" key). Authorisation Username: not present
If you have "logged in" to a web site, your username appears here. Note that this only applies to web sites which use proper HTTP authentication - typically, a "login" window pops up and you get three chances to enter your username and password, otherwise you see a page which says "Authentication Required" or similar. It doesn't apply to web sites where the "login" is a separate page. It's also possible to supply the username and ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
password in the URL you tell your browser to visit - for example, http://user:password@www.example.com/. In that case, the username would appear here too. Reference-http://dev.opera.com/articles/view/2-the-history-of-the-internet-and-the-w/
http://www.address.edu:1234/path/subdir/file.ext http://djce.org.uk/dumprequest
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Chapter-2 PHP
PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. PHP borrows a bit of its syntax from other languages such as C, shell, Perl,and even Java. It is really a hybrid language, taking the best features from other languages and creating an easy-touse and powerful scripting language. When you finish reading this chapter, you will have learned The basic language structure of PHP How PHP is embedded in HTML How to write comments Managing variables and basic data types Defining constants for simple values The most common control structures, most of which are available in other programming languages Built-in or user-defined functions If you are an experienced PHP 4 developer, you might want to skip to the next chapter, which covers object-oriented support of the language that has changed significantly in PHP 5 Reference- PHP 5 Power Programming By Andi Gutmans, Stig Sæther Bakken, and Derick Rethans PHP–What is it? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software PHP is free to download and use PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly."This is generally a good definition of PHP. However, it does contain a lot of terms you may not be used to. Another way to think of PHP is a powerful, behind the scenes scripting language that your visitors won't see! .When someone visits your PHP webpage, your web server processes the PHP code. It then sees which parts it needs to show to visitors(content and pictures) and hides the ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
other stuff(file operations, math calculations, etc.) then translates your PHP into HTML. After the translation into HTML, it sends the webpage to your visitor's web browser. PHP-What's it do? It is also helpful to think of PHP in terms of what it can do for you. PHP will allow you to: Reduce the time to create large websites. Create a customized user experience for visitors based on information that you have gathered from them. Open up thousands of possibilities for online tools. Check out PHP - HotScripts for examples of the great things that are possible with PHP. Allow creation of shopping carts for e-commerce websites. WhatYou Should Know Before starting this tutorial it is important that you have a basic understanding and experience in the following: HTML - Know the syntax and especially HTML Forms. Basic programming knowledge - This isn't required, but if you have any traditional programming experience it will make learning PHP a great deal easier. PHP–Necessary Setup To begin working with PHP you must first have access to either of the following: A web hosting account that supports the use of PHP web pages and grants you access to MySQL databases. If you do not have a host, but are interested in signing up for one, we recommend that you first read our Web Host Guide to educate yourself about web hosting and avoid getting ripped off. Have PHP and MySQL installed on your own computer. Read this lesson thorougly for more information on installing PHP. Although MySQL is not absolutely necessary to use PHP, MySQL and PHP are wonderful complements to one another and some topics covered in this tutorial will require that you have MySQL access. Installing PHP For those who are experienced enough to do this yourself, simply head over to PHP.net Downloads and download the most recent version of PHP. However, if you are like most of us, you will most likely want to follow a guide to installing PHP onto your computer. These guides are kindly provided by PHP.net based on the operating system that you are using. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
PHP - Windows - Windows Installation Guide PHP - Mac - Mac Installation Guide PHP - Linux - Linux Installation Guide Installing MySQL As we mentioned before, MySQL is not a requirement to use PHP, however they often go hand in hand. Visit MySQL's MySQL Installation Guide for help on installing MySQL PHP-Syntax Before we talk about PHP's syntax, let us first define what syntax is referring to. Syntax - The rules that must be followed to write properly structured code. PHP's syntax and semantics are similar to most other programming languages (C, Java, Perl) with the addition that all PHP code is contained with a tag, of sorts. All PHP code must be contained within the following... PHP Code: <?php ?> or the shorthand PHP tag that requires shorthand support to be enabled on your server... <? ?>
If you are writing PHP scripts and plan on distributing them, we suggest that you use the standard form (which includes the ?php) rather than the shorthand form. This will ensure that your scripts will work, even when running on other servers with different settings. How to SaveYour PHP Pages
If you have PHP inserted into your HTML and want the web browser to interpret it correctly, then you must save the file with a .php extension, instead of the standard .html extension. So be sure to check that you are saving your files correctly. Instead of index.html, it should be index.php if there is PHP code in the file. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
ExampleSimple HTML & PHP Page Below is an example of one of the easiest PHP and HTML page that you can create and still follow web standards. PHP and HTML Code: <html> <head> <title>My First PHP Page</title> </head> <body> <?php echo "Hello World!"; ?> </body> </html> Display: Hello World! If you save this file (e.g. helloworld.php) and place it on PHP enabled server and load it up in your web browser, then you should see "Hello World!" displayed. If not, please check that you followed our example correctly. We used the PHP command echo to write "Hello World!" and we will be talking in greater depth about how echo is special later on in this tutorial. The Semicolon As you may or may not have noticed in the above example, there was a semicolon after the line of PHP code. The semicolon signifies the end of a PHP statement and should never be forgotten. For example, if we repeated our "Hello World!" code several times, then we would need to place a semicolon at the end of each statement.
PHP and HTML Code: <html> <head> <title>My First PHP Page</title> </head> <body> <?php echo "Hello World! "; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
echo "Hello World! "; echo "Hello World! "; echo "Hello World! "; echo "Hello World! "; ?> </body> </html>
Display: Hello World! Hello World! Hello World! Hello World! Hello World! WhiteSpace As with HTML, whitespace is ignored between PHP statements. This means it is OK to have one line of PHP code, then 20 lines of blank space before the next line of PHP code. You can also press tab to indent your code and the PHP interpreter will ignore those spaces as well. PHP and HTML Code:
<html> <head> <title>My First PHP Page</title> </head> <body> <?php echo "Hello World!";
echo "Hello World!";
?> </body> </html> Display: Hello World!Hello World! This is perfectly legal PHP code ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
PHP-Variables Variables in PHP are quite different from compiled languages such as C and Java. This is because their weakly typed nature, which in short means you don’t need to declare variables before using them, you don’t need to declare their type and, as a result, a variable can change the type of its value as much as you want. A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form: $variable_name = Value; Variables in PHP are preceded with a $ sign, and similar to most modern languages, they can start with a letter (A-Za-z) or_ (underscore) and can then contain as many alphanumeric characters and underscores as you like. Examples of legal variable names include $count $_Obj $A123 Example of illegal variable names include $123 $*ABC The following code example uses variables: $PI = 3.14; $radius = 5; $circumference = $PI * 2 * $radius; // Circumference = AQuickVariableExample Say that we wanted to store the values that we talked about in the above paragraph. How would we go about doing this? We would first want to make a variable name and then set that equal to the value we want. See our example below for the correct way to do this. PHP Code: <?php $hello = "Hello World!"; $a_number = 4; $anotherNumber = 8; ?>
________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Note for programmers: PHP does not require variables to be declared before being initialized. PHP Variable Naming Conventions There are a few rules that you need to follow when choosing a name for your PHP variables. PHP variables must start with a letter or underscore "_". PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ . Variables with more than one word should be separated with underscores. $my_variable Variables with more than one word can also be distinguished with capitalization. $myVariable PHP-Echo As you saw in the previous lesson, the PHP command echo is a means of outputting text to the web browser. Throughout your PHP career you will be using the echo command more than any other. So let's give it a solid perusal! OutputtingaString To output a string, like we have done in previous lessons, use PHP echo. You can place either a string variable or you can use quotes, like we do below, to create a string that the echo function will output. PHP Code: <?php $myString = "Hello!"; echo $myString; echo "<h5>I love using PHP!</h5>"; ?> Display: Hello! I love using PHP! In the above example we output "Hello!" without a hitch. The text we are outputting is being sent to the user in the form of a web page, so it is important that we use proper HTML syntax!
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this we simply put the <h5> at the beginning of the string and closed it at the end of the string. Just because you're using PHP to make web pages does not mean you can forget about HTML syntax! PHP Code: <?php // This won't work because of the quotes around specialH5! echo "<h5 class="specialH5">I love using PHP!</h5>"; // OK because we escaped the quotes! echo "<h5 class=\"specialH5\">I love using PHP!</h5>"; // OK because we used an apostrophe ' echo "<h5 class='specialH5'>I love using PHP!</h5>"; ?>
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape the quotations by placing a backslash in front of it ( \" ). The backslash will tell PHP that you want the quotation to be used within the string and NOT to be used to end echo's string. EchoingVariables Echoing variables is very easy. The PHP developers put in some extra work to make the common task of echoing all variables nearly foolproof! No quotations are required, even if the variable does not hold a string. Below is the correct format for echoing a variable. PHP Code: <?php $my_string = "Hello Bob. My name is: "; $my_number = 4; $my_letter = a; echo $my_string; echo $my_number; echo $my_letter; ?>
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Display: Hello Bob. My name is: 4a EchoingVariablesandTextStrings You can also place variables inside of double-quoted strings (e.g. "string here and a $variable"). By putting a variable inside the quotes (" ") you are telling PHP that you want it to grab the string value of that variable and use it in the string. The example below shows an example of this cool feature. PHP Code: <?php $my_string = "Hello Bob. My name is: "; echo "$my_string Bobettta <br />"; echo "Hi, I'm Bob. Who are you? $my_string <br />"; echo "Hi, I'm Bob. Who are you? $my_string Bobetta"; ?> Display: Hello Bob. My name is: Bobetta Hi, I'm Bob. Who are you? Hello Bob. My name is: Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta By placing variables inside a string you can save yourself some time and make your code easier to read, though it does take some getting used to. Remember to use double-quotes, singlequotes will not grab the value of the string. Single-quotes will just output the variable name to the string, like )$my_string), rather than (Hello Bob. My name is: ). String Variables in PHP String variables are used for values that contain characters. In this chapter we are going to look at the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the text "Hello World" to a string variable called $txt: <?php ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
$txt="Hello World"; echo $txt; ?>
The output of the code above will be: Hello World
Now, lets try to use some different functions and operators to manipulate the string. The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two string variables together, use the concatenation operator: <?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?>
The output of the code above will be: Hello World! What a nice day!
If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string (a space character), to separate the two strings. The strlen() function
The strlen() function is used to return the length of a string. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Let's find the length of a string: <?php echo strlen("Hello world!"); ?>
The output of the code above will be: 12
The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string). The strpos() function The strpos() function is used to search for a character/text within a string.If a match is found, this function will return the character position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string: <?php echo strpos("Hello world!","world"); ?> The output of the code above will be:6
The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that the first character position in the string is 0, and not 1.
PHP Operators This section lists the different operators used in PHP. Arithmetic Operators ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Operator Description
Example
Result
+
Addition
x=2 x+2
4
-
Subtraction
x=2 5-x
3
*
Multiplication
x=4 x*5
20
/
Division
15/5 5/2
3 2.5
%
Modulus remainder)
++
Increment
x=5 x++
x=6
--
Decrement
x=5 x--
x=4
(division 5%2 10%8 10%2
1 2 0
Assignment Operators Operator Example
Is The Same As
=
x=y
x=y
+=
x+=y
x=x+y
-=
x-=y
x=x-y
*=
x*=y
x=x*y
/=
x/=y
x=x/y
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
.=
x.=y
x=x.y
%=
x%=y
x=x%y
Comparison Operators Operator Description
Example
==
is equal to
5==8 returns false
!=
is not equal
5!=8 returns true
<>
is not equal
5<>8 returns true
>
is greater than
5>8 returns false
<
is less than
5<8 returns true
>=
is greater than or equal to 5>=8 returns false
<=
is less than or equal to
5<=8 returns true
Logical Operators Operator Description
Example
&&
x=6 y=3
and
(x < 10 && y > 1) returns true ||
or
x=6 y=3 (x==5 || y==5) returns false
!
not
x=6
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
y=3 !(x==y) returns true CONTROL STRUCTURES PHP supports a variety of the most common control structures available in other programming languages. They can be basically divided into two groups: 1. conditional control structures 2. loop control structures. The conditional control structures affect the flow of the program and execute or skip certain code according to certain criteria, whereas loop control structures execute certain code an arbitrary number of times according to specified criteria. Conditional Control Structures Conditional control structures are crucial in allowing your program to take different execution paths based on decisions it makes at runtime. PHP supports both the if and switch conditional control structures. if Statements if statements are the most common conditional constructs, and they exist in most programming languages. The expression in the if statement is referred to as the truth expression. If the truth expression evaluates to true, the statement or statement list following it are executed; otherwise, they’re not. Reference- PHP 5 Power Programming by Andi Gutmans, Stig Sæther Bakken, and Derick Rethans Syntax if (condition) code to be executed if condition is true;
The following example will output "Have a nice weekend!" if the current day is Friday: <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
</html>
The if...else Statement Use the if....else statement to execute some code if a condition is true and another code if a condition is false. Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false;
Example The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html>
You can add an else branch to an if statement to execute code only if all the truth expressions in the if statement evaluated to false: if ($var >= 50) { print '$var is in range'; } else { ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
print '$var is invalid'; } The if...elseif....else Statement Use the if....elseif...else statement to select one of several blocks of code to be executed. Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Notice the braces that delimit the statements following if and else, which make these statements a statement block. In this particular case, you can omit the braces because both blocks contain only one statement in them. It is good practice to write these braces even if they’re not syntactically required. Doing so improves readability, and it’s easier to add more statements to the if block later (for example, during debugging). The elseif construct can be used to conduct a series of conditional checks and only execute the code following the first condition that is met. Example The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
?> </body> </html>
switch Statements You can use the switch construct to elegantly replace certain lengthy if/ elseif constructs. It is given an expression and compares it to all possible case expressions listed in its body. When thereâ&#x20AC;&#x2122;s a successful match, the following code is executed, ignoring any further case lines (execution does not stop when the next case is reached). The match is done internally using the regular equality operator (==), not the identical operator (===). You can use the break statement to end execution and skip to the code following the switch construct. Syntax switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; }
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found. Example <html> <body>
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html>
PHP Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In PHP, we have the following looping statements: while - loops through a block of code while a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array
while loops while loops are the simplest kind of loops. In the beginning of each iteration, the while’s truth expression is evaluated. If it evaluates to true, the loop keeps on running and the statements inside it are executed. If it evaluates to false, the loop ends and the statement(s) inside the loop is skipped. For example, here’s one possible implementation of factorial, using a while loop ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
(assuming $n contains the number for which we want to calculate the factorial): Syntax while (condition) { code to be executed; }
Example The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html>
Output: The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 do...while Loops ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Syntax do { code to be executed; } while (condition);
The do...while loop is similar to the previous while loop, except that the truth expression is checked at the end of each iteration instead of at the beginning. This means that the loop always runs at least once. do...while loops are often used as an elegant solution for easily breaking out of a code block if a certain condition is met. Consider the following example: do { statement list if ($error) { break; } statement list } while (false); Because do...while loops always iterate at least one time, the statements inside the loop are executed once, and only once. The truth expression is always false. However, inside the loop body, you can use the break statement to stop the execution of the statements at any point, which is convenient. Of course, do...while loops are also often used for regular iterating purposes. Example The example below defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5: <html> <body> <?php $i=1; do { ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
$i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> </body> </html>
Output: The number is 2 The number is 3 The number is 4 The number is 5 The number is 6
for Loops PHP provides C-style for loops. The for loop accepts three arguments: Most commonly, for loops are used with only one expression for each of the init, condition, and increment expressions, Syntax for (init; condition; increment) { code to be executed; }
Parameters: init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop) ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas). Example The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> </body> </html>
Output: The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
The foreach Loop The foreach loop is used to loop through arrays. Syntax foreach ($array as $value) { code to be executed; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
}
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value. Example The following example demonstrates a loop that will print the values of the given array:
<html> <body> <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br />"; } ?> </body> </html> Output:one
two three
PHP Arrays An array stores multiple values in one single variable. What is an Array? A variable is a storage area holding a number or text. The problem is, a variable will hold only one value.An array is a special variable, which can store multiple values in one single ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
variable.If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: $cars1="Saab"; $cars2="Volvo"; $cars3="BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The best solution here is to use an array! An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own index so that it can be easily accessed. In PHP, there are three kind of arrays: Numeric array - An array with a numeric index Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays Numeric Arrays A numeric array stores each array element with a numeric index. There are two methods to create a numeric array. 1. In the following example the index are automatically assigned (the index starts at 0): $cars=array("Saab","Volvo","BMW","Toyota");
2. In the following example we assign the index manually: $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Example In the following example you access the variable values by referring to the array name and index: <?php $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; ?>
The code above will output: Saab and Volvo are Swedish cars.
Associative Arrays An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them. Example 1 In this example we use an array to assign ages to the different persons: $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2 This example is the same as example 1, but shows a different way of creating the array:
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";
The ID keys can be used in a script: <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?>
The code above will output: Peter is 32 years old.
Multidimensional Arrays In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example In this example we create a multidimensional array, with automatically assigned ID keys: $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
"Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
The array above would look like this if written to the output: Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) )
Example 2 Lets try displaying a single value from the array above: ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
The code above will output: Is Megan a part of the Griffin family?
PHP-Functions A function in PHP can be built-in or user-defined; however, they are both called the same way. A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable! The general form of a function call is func(arg1,arg2,â&#x20AC;Ś) The number of arguments varies from one function to another. Each argument can be any valid expression, including other function calls. PHP function guidelines: Give the function a name that reflects what the function does The function name can start with a letter or underscore (not a number Create a PHP Function A function will be executed by a call to the function. Syntax function { code }
functionName() to
be
executed;
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Example A simple function that writes my name when it is called: <html> <body> <?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?> </body> </html>
Output: My name is Kai Jim Refsnes
PHP-POST&GET Recall from the PHP Forms Lesson where we used an HTML form and sent it to a PHP web page for processing. In that lesson we opted to use the the post method for submitting, but we could have also chosen the get method. This lesson will review both transferring methods POST-Review In our PHP Forms Lesson we used the post method. This is what the pertinent line of HTML code looked like:
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
HTML Code Excerpt: <form action="process.php" method="post"> <select name="item"> ... <input name="quantity" type="text" />
This HTML code specifies that the form data will be submitted to the "process.php" web page using the POST method. The way that PHP does this is to store all the "posted" values into an associative array called "$_POST". Be sure to take notice the names of the form data names, as they represent the keys in the "$_POST" associative array.Now that you know about associative arrays, the PHP code from "process.php" should make a litte more sense. PHP Code Excerpt: $quantity = $_POST['quantity']; $item = $_POST['item'];
The form names are used as the keys in the associative array, so be sure that you never have two input items in your HTML form that have the same name. If you do, then you might see some problems arise. PHP-GET As we mentioned before, the alternative to the post method is get. If we were to change our HTML form to the get method, it would look like this: HTML Code Excerpt: <form action="process.php" method="get"> <select name="item"> ... <input name="quantity" type="text" />
The get method is different in that it passes the variables along to the "process.php" web page by appending them onto the end of the URL. The URL, after clicking submit, would have this added on to the end of it: "?item=##&quantity=##" The question mark "?" tells the browser that the following items are variables. Now that we changed the method of sending information on "order.html", we must change the "process.php" code to use the "$_GET" associative array. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
PHP Code Excerpt: $quantity = $_GET['quantity']; $item = $_GET['item'];
After changing the array name the script will function properly. Using the get method displays the variable information to your visitor, so be sure you are not sending password information or other sensitive items with the get method. You would not want your visitors seeing something they are not supposed to! Reference- http://www.tizag.com/phpT/postget.php PHP Form Handling The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Example The example below contains an HTML form with two input fields and a submit button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>
When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php": "welcome.php" looks like this: <html> ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
Output could be something like this: Welcome John! You are 28 years old.
Form Validation User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load. You should consider server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error. PHP-Files Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files. This section of the PHP tutorial is completely dedicated to how PHP can interact with files. After completing this section you should have a solid understanding of all types of file manipulation in PHP! PHP-Files:BeCareful When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
It is our hope that you will be able to avoid these and other slipups after reading this tutorial. However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP. PHP-Files:Overview The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP. Opening a File The fopen() function is used to open files in PHP. The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc). Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html>
The file may be opened in one of the following modes: PHP-Permissions If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Modes
Description
r
Read only. Starts at the beginning of the file
r+
Read/Write. Starts at the beginning of the file
w
Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+
Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
a
Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+
Read/Append. Preserves file content by writing to the end of the file
x
Write only. Creates a new file. Returns FALSE and an error if file already exists
x+
Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Note: If the fopen() function is unable to open the specified file, it returns 0 (false). Example The following example generates a message if the fopen() function is unable to open the specified file:
<html> <body> <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?> ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
</body> </html>
Closing a File The fclose() function is used to close an open file: <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?>
Check End-of-file The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length. Note: You cannot read from files opened in w, a, and x mode! if (feof($file)) echo "End of file";
Reading a File Line by Line The fgets() function is used to read a single line from a file. Note: After a call to this function the file pointer has moved to the next line. Example The example below reads a file line by line, until the end of file is reached:
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>
Reading a File Character by Character The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character. Example The example below reads a file character by character, until the end of file is reached: <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>
PHP-How to Create aFile PHP Code: $ourFileName = "testFile.txt"; $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); fclose($ourFileHandle);
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it. 1. $ourFileName = "testFile.txt"; Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName. 2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character "w". Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on. 3. fclose($ourFileHandle); We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson. PHP-File Append So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode. PHP-FileOpen:Append If we want to add on to a file we need to open it up in append mode. The code below does just that. PHP Code: $myFile = "testFile.txt"; $fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file. PHP-File Write:Appending Data ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data. PHP Code: $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "New Stuff 1\n"; fwrite($fh, $stringData); $stringData = "New Stuff 2\n"; fwrite($fh, $stringData); fclose($fh);
You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file. The contents of the file testFile.txt would now look like this: Contents of the testFile.txt File: Floppy Jalopy Pointy Pinto New Stuff 1 New Stuff 2
PHP File Upload With PHP, it is possible to upload files to the server. Create an Upload-File Form To allow users to upload files from a form can be very useful. Look at the following HTML form for uploading files: <html> <body> <form action="upload_file.php" method="post" ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
Notice the following about the HTML form above: The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads. Create The Upload Script The "upload_file.php" file contains the code for uploading a file: <?php if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
?>
By using the global PHP $_FILES array you can upload files from a client computer to the remote server. The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this: $_FILES["file"]["name"] - the name of the uploaded file $_FILES["file"]["type"] - the type of the uploaded file $_FILES["file"]["size"] - the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] - the error code resulting from the file upload This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload. Restrictions on Upload In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
} } else { echo "Invalid file"; } ?>
Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg. Saving the Uploaded File The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server.The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?>
The script above checks if the file already exists, if it does not, it copies the file to the specified folder. Note: This example saves the file to a new folder called "upload" PHP Cookies cookie is often used to identify a user. What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. How to Create a Cookie? The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax setcookie(name, value, expire, path, domain);
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Example 1 In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour: <?php setcookie("user", "Alex Porter", time()+3600); ?> <html> .....
Example 2 You can also set the expiration time of the cookie in another way. It may be easier than using seconds. <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> <html> .....
How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE);
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
?>
In the following example we use the isset() function to find out if a cookie has been set: <html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html>
How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>
What if a Browser Does NOT Support Cookies? If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial). The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button: ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>
Retrieve the values in the "welcome.php" file like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
PHPSessions A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL. Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session.Note: The session_start() function must appear BEFORE the <html> tag: <?php session_start(); ?> <html> <body> </body> </html>
The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session. Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
//retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html>
Output: Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1: <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?>
Destroying a Session If you wish to delete some session data, you can use the unset() or the session_destroy() function.The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?>
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
You can also completely destroy the session by calling the session_destroy() function: <?php session_destroy(); ?>
PHP allows you to send e-mails directly from a script. The PHP mail() Function The PHP mail() function is used to send emails from inside a script. Syntax mail(to,subject,message,headers,parameters) Parameter
Description
to
Required. Specifies the receiver / receivers of the email
subject
Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters
message
Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers
Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters
Optional. Specifies an additional parameter to the sendmail program
Note: For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file. Read more in our PHP Mail reference.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
PHP Simple E-Mail The simplest way to send an email with PHP is to send a text email. In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail() function to send an e-mail: <?php $to = "someone@example.com"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From:" . $from; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?>
PHP Mail Form With PHP, you can create a feedback-form on your website. The example below sends a text message to a specified e-mail address: <html> <body> <?php if (isset($_REQUEST['email'])) //if "email" is filled out, send email { //send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("someone@example.com", "$subject", $message, "From:" . $email); echo "Thank you for using our mail form"; } ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
else //if "email" is not filled out, display the form { echo "<form method='post' action='mailform.php'> Email: <input name='email' type='text' /><br /> Subject: <input name='subject' type='text' /><br /> Message:<br /> <textarea name='message' rows='15' cols='40'> </textarea><br /> <input type='submit' /> </form>"; } ?> </body> </html>
This is how the example above works: First, check if the email input field is filled out If it is not set (like when the page is first visited); output the HTML form If it is set (after the form is filled out); send the email from the form When submit is pressed after the form is filled out, the page reloads, sees that the email input is set, and sends the email Note: This is the simplest way to send e-mail, but it is not secure. In the next chapter of this tutorial you can read more about vulnerabilities in e-mail scripts, and how to validate user input to make it more secure. PHP Exception Handling Exceptions are used to change the normal flow of a script if a specified error occurs What is an Exception With PHP 5 came a new object oriented way of dealing with errors.
error
Exception handling is used to change the normal flow of the code execution if a specified (exceptional) condition occurs. This condition is called an exception.
This is what normally happens when an exception is triggered: ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
The current code state is saved The code execution will switch to a predefined (custom) exception handler function Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code We will show different error handling methods: Basic use of Exceptions Creating a custom exception handler Multiple exceptions Re-throwing an exception Setting a top level exception handler Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point. Basic Use of Exceptions When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. Lets try to throw an exception without catching it: <?php //create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception checkNum(2); ?>
The code above will get an error like this: ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6
Try, throw and catch To avoid the error from the example above, we need to create the proper code to handle an exception. Proper exception code should include: 1. Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown" 2. Throw - This is how you trigger an exception. Each "throw" must have at least one "catch" 3. Catch - A "catch" block retrieves an exception and creates an object containing the exception information Lets try to trigger an exception with valid code: <?php //create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception in a "try" block try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; }
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
//catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?> The code above will get an error like this:
Message: Value must be 1 or below
Example explained: The code above throws an exception and catches it: 1. The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception is thrown 2. The checkNum() function is called in a "try" block 3. The exception within the checkNum() function is thrown 4. The "catch" block retrives the exception and creates an object ($e) containing the exception information 5. The error message from the exception is echoed by calling $e->getMessage() from the exception object However, one way to get around the "every throw must have a catch" rule is to set a top level exception handler to handle errors that slip through. Creating a Custom Exception Class Creating a custom exception handler is quite simple. We simply create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class.The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it. Lets create an exception class: <?php class customException extends Exception { public function errorMessage() ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
{ //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg; } } $email = "someone@example...com"; try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>
The new class is a copy of the old exception class with an addition of the errorMessage() function. Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine() and getFile() and getMessage(). Example explained: The code above throws an exception and catches it with a custom exception class: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error message if an email address is invalid ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
3. The $email variable is set to a string that is not a valid e-mail address 4. The "try" block is executed and an exception is thrown since the e-mail address is invalid 5. The "catch" block catches the exception and displays the error message Multiple Exceptions It is possible for a script to use multiple exceptions to check for multiple conditions. It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages: <?php class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg; } } $email = "someone@example.com"; try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } //check for "example" in mail address if(strpos($email, "example") !== FALSE) { throw new Exception("$email is an example e-mail"); } } ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
catch (customException $e) { echo $e->errorMessage(); } catch(Exception $e) { echo $e->getMessage(); } ?>
Example explained: The code above tests two conditions and throws an exception if any of the conditions are not met: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error message if an email address is invalid 3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example" 4. The "try" block is executed and an exception is not thrown on the first condition 5. The second condition triggers an exception since the e-mail contains the string "example" 6. The "catch" block catches the exception and displays the correct error message If there was no customException catch, only the base exception catch, the exception would be handled there Re-throwing Exceptions Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block. A script should hide system errors from users. System errors may be important for the coder, but is of no interest to the user. To make things easier for the user you can re-throw the exception with a user friendly message: <?php ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
class customException extends Exception { public function errorMessage() { //error message $errorMsg = $this->getMessage().' is not a valid E-Mail address.'; return $errorMsg; } } $email = "someone@example.com"; try { try { //check for "example" in mail address if(strpos($email, "example") !== FALSE) { //throw exception if email is not valid throw new Exception($email); } } catch(Exception $e) { //re-throw exception throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Example explained: The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error message if an email address is invalid 3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example" 4. The "try" block contains another "try" block to make it possible to re-throw the exception 5. The exception is triggered since the e-mail contains the string "example" 6. The "catch" block catches the exception and re-throws a "customException" 7. The "customException" is caught and displays an error message If the exception is not caught in its current "try" block, it will search for a catch block on "higher levels". Set a Top Level Exception Handler The set_exception_handler() function sets a user-defined function to handle all uncaught exceptions. <?php function myException($exception) { echo "<b>Exception:</b> " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?>
The output of the code above should be something like this: Exception: Uncaught Exception occurred
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
In the code above there was no "catch" block. Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions. Rules for exceptions Code may be surrounded in a try block, to help catch potential exceptions Each try block or "throw" must have at least one corresponding catch block Multiple catch blocks can be used to catch different classes of exceptions Exceptions can be thrown (or re-thrown) in a catch block within a try block A simple rule: If you throw something, you have to catch it. MySQL MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows. Databases are useful when storing information categorically. A company may have a database with the following tables: "Employees", "Products", "Customers" and "Orders". Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons": LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City). ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Queries A query is a question or a request.With MySQL, we can query a database for specific information and have a recordset returned. Look at the following query: SELECT LastName FROM Persons
The query above selects all the data in the "LastName" column from the "Persons" table, and will return a recordset like this: LastName Hansen Svendson Pettersen Create a Connection to a MySQL Database Before you can access data in a database, you must create a connection to the database. In PHP, this is done with the mysql_connect() function. Syntax mysql_connect(servername,username,password); Parameter
Description
servername
Optional. Specifies the server to connect to. Default value is "localhost:3306"
username
Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process
password
Optional. Specifies the password to log in with. Default is ""
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Note: There are more available parameters, but the ones listed above are the most important. Visit our full PHP MySQL Reference for more details. Example In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?>
Closing a Connection The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?>
A database holds one or multiple tables. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Create a Database The CREATE DATABASE statement is used to create a database in MySQL. Syntax CREATE DATABASE database_name
To learn more about SQL, please visit our SQL tutorial. To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example creates a database called "my_db": <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } mysql_close($con); ?>
Create a Table The CREATE TABLE statement is used to create a table in MySQL. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Syntax CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )
To learn more about SQL, please visit our SQL tutorial.We must add the CREATE TABLE statement to the mysql_query() function to execute the command. Example The following example creates a table named "Persons", with three columns. The column names will be "FirstName", "LastName" and "Age": <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } // Create table mysql_select_db("my_db", $con); $sql = "CREATE TABLE Persons ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
( FirstName varchar(15), LastName varchar(15), Age int )"; // Execute query mysql_query($sql,$con); mysql_close($con); ?>
Important: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function. Note: When you create a database field of type varchar, you must specify the maximum length of the field, e.g. varchar(15). The data type specifies what type of data the column can hold. For a complete reference of all the data types available in MySQL, go to our complete Data Types reference. Primary Keys and Auto Increment Fields Each table should have a primary key field. A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique within the table. Furthermore, the primary key field cannot be null because the database engine requires a value to locate the record. The following example sets the personID field as the primary key field. The primary key field is often an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the value of the field by 1 each time a new record is added. To ensure that the primary key field cannot be null, we must add the NOT NULL setting to the field. Example $sql = "CREATE TABLE Persons ( personID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(personID), ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con);
The INSERT INTO statement is used to insert new records in a table. Insert Data Into a Database Table The INSERT INTO statement is used to add new records to a database table. Syntax It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values: INSERT INTO table_name VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
To learn more about SQL, please visit our SQL tutorial. To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Example In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')"); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')"); mysql_close($con); ?>
Insert Data From a Form Into a Database Now we will create an HTML form that can be used to add new records to the "Persons" table.Here is the HTML form: <html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
</html>
When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php".The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables.Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the "Persons" table. Here is the "insert.php" page: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?>
PHP MySQL Select The SELECT statement is used to select data from a database. Select Data From a Database Table The SELECT statement is used to select data from a database. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Syntax SELECT FROM table_name
column_name(s)
To learn more about SQL, please visit our SQL tutorial. To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example selects all the data stored in the "Persons" table (The * character selects all the data in the table): <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } mysql_close($con); ?>
The example above stores the data returned by the mysql_query() function in the $result variable.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']). The output of the code above will be: Peter Glenn Quagmire
Griffin
Display the Result in an HTML Table The following example selects the same data as the example above, but will display the data in an HTML table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons"); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "</tr>"; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
} echo "</table>"; mysql_close($con); ?>
The output of the code above will be: Firstname Lastname Glenn
Quagmire
Peter
Griffin
The WHERE clause The WHERE clause is used to extract only those records that fulfill a specified criterion. Syntax SELECT column_name(s) FROM table_name WHERE column_name operator value
To learn more about SQL, please visit our SQL tutorial. To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example selects all rows from the "Persons" table where "FirstName='Peter': <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } ?>
The output of the code above will be: Peter Griffin
The ORDER BY Keyword The ORDER BY keyword is used to sort the data in a recordset. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword. Syntax SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
To learn more about SQL, please visit our SQL tutorial. Example The following example selects all the data stored in the "Persons" table, and sorts the result by the "Age" column: ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['FirstName']; echo " " . $row['LastName']; echo " " . $row['Age']; echo "<br />"; } mysql_close($con); ?>
The output of the code above will be: Glenn Quagmire 33 Peter Griffin 35
Order by Two Columns It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are equal: SELECT column_name(s) FROM table_name ORDER BY column1, column2
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Update Data In a Database The UPDATE statement is used to update existing records in a table. Syntax UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example Earlier in the tutorial we created a table named "Persons". Here is how it looks: FirstName
LastName
Age
Peter
Griffin
35
Glenn
Quagmire
33
The following example updates some data in the "Persons" table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con);
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
mysql_query("UPDATE Persons SET Age = '36' WHERE FirstName = 'Peter' AND LastName = 'Griffin'"); mysql_close($con); ?>
After the update, the "Persons" table will look like this: FirstName
LastName
Age
Peter
Griffin
36
Glenn
Quagmire
33
PHPMySQLDelete The DELETE statement is used to delete records in a table. Delete Data In a Database The DELETE FROM statement is used to delete records from a database table. Syntax DELETE WHERE some_column = some_value
FROM
table_name
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Example Look at the following "Persons" table: FirstName
LastName
Age
Peter
Griffin
35
Glenn
Quagmire
33
The following example deletes all the records in the "Persons" table where LastName='Griffin': <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("DELETE FROM Persons WHERE LastName='Griffin'"); mysql_close($con); ?>
After the deletion, the table will look like this: FirstName
LastName
Age
Glenn
Quagmire
33
Reference- http://www.tizag.com/phpT/phpfunctions.php http://www.w3schools.com/php/php_operators.asp ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Chapter-3 PERL -- Practical Extraction and Report Language Perl stands for Practical Extraction and Report Language. Perl is known as a high-level, interpreted, general-purpose and dynamic programming language. Introducing to Perl Perl stands for Practical Extraction and Reporting Language. Perl is a general-purpose, high level, interpreted and dynamic computer programming language with a vast number of uses. Perl was invented by Larry Wall, a linguist working as a systems administrator at NASA in 1987. From the beginning, Perl was used as a general-purpose UNIX scripting language to help processing reports faster and easier. Since then Perl has undergone a lot of modifications and improvements to become popular among developer community. Even though Perl has far surpassed its first invention, Larry Wall is still developing the core language with the newest version of Perl now is Perl 6. Today Perl is found in varied applications such as finance, manufacturing, genetics, the military etc to process large data sets. Perl is used to be one of the most popular languages for developing web applications. At that time, Perl is used to write CGI scripts. You can find Perl in large projects such as Bugzilla, movable Type and other high-traffic websites such as Amazon.com, Ebay, LiveJournal and Craigslist. Perl is very good and optimized for problems that handle 90% of text and 10% of other. Perl is best for short and small programs that can be entered and run on a single command line. Perl run well on UNIX and Windows systems. If you develop Perl for UNIX system, it can be portable to Windows system as well. Setting Up Perl Development Environment We will use Windows environment through tutorial series. For your convenience, we will use all free development tools. You can also find such the same free tool in your platform such as Linux or Mac. Download and install ActivePerl ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
You first need to download ActivePerl the latest version from http://www.activestate.com/activeperl/. The file we downloaded at the time of this tutorial being written was ActivePerl5.10.0.1004-MSWin32-x86-287188.msi. You can also find the installation files for other systems and versions via following link http://www.activestate.com/activeperl/downloads/ To install ActivePerl just double click on the installation file. It will guide you through steps with options. Just make your own choices and click next. To check you installation succesfully, you can open command line through Run window and type following command: perl -version. If you installed Perl successfully, you will see the version and copyright information. Download and install Perl IDE: Open Perl IDE Open Perl IDE stands for integrated development environment. It includes source code editor with syntax highlight, interpreter, and debugger tool. The IDE helps you a lot while develop Perl Program. We highly recommend that you should use Open Perl IDE because it is free, simple, intuitive and easy to use. You can download the Open Perl IDE the latest version via following link: http://open-perlide.sourceforge.net/ With Open Perl IDE you don’t need to install to run it. First you unzip the downloaded file. (If you don’t have zip tool you can download a free tool called 7-ZIP from http://www.7-zip.org/ ). To launch the Open Perl IDE, you can open the unzip folder, find the file PerlIDE.exe, double click on it. Now you are ready to start learning Perl! Writing the First Perl Program When you learn every computer programming language you may realize that the first program to demonstrate is “Hello World”. Therefore, we use this simple but famous program to write the first program in Perl. First, you open the Open Perl IDE and type the following code: 1 #!/usr/bin/perl 2 print "Hello World!\n";
________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
You can save the Perl source code file with any name and extensions you want. It is highly recommended that Perl source code file should has extension *.pl or *.ple (Perl executable). When you click Run > Run or press F9, the program will launch and print the message “Hello World!” Let's look at the program in more details.
The first line of the program is a special comment. Comments in Perl program start from the pound sign (#) to the rest of line. There is no sign for block comment. On UNIX systems, two characters #! starting in a line indicates the program is stored in the file /usr/bin/perl
The second line starts with print statement followed by a string “Hello World” and then followed by a semi-comma. Every Perl statement has to be ended with a semi-comma (;).
You can also launch Perl program by double click on the source code file. There is no *.exe or *.dll file when you write Perl programs. If you want to distribute Perl program just copy the source code to other.
In this tutorial, you’ve learn how to write the first Perl program “Hello World”. You’ve also learned how to launch it in through IDE and source code file. Let’s go to the next tutorials to learn Perl in depth. Running Perl programs To run a Perl program from the Unix command line: 1.
perl progname.pl
Alternatively, put this as the first line of your script: 1.
#!/usr/bin/env perl
... and run the script as /path/to/script.pl. Of course, it'll need to be executable first, so chmod 755 script.pl (under Unix). (This start line assumes you have the env program. You can also put directly the path to your perl executable, like in #!/usr/bin/perl ). For more information, including instructions for other platforms such as Windows and Mac OS, read perlrun.
________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Safety net Perl by default is very forgiving. In order to make it more robust it is recommended to start every program with the following lines: 1. 2. 3.
#!/usr/bin/perl use strict; use warnings;
The two additional lines request from perl to catch various common problems in your code. They check different things so you need both. A potential problem caught by use strict; will cause your code to stop immediately when it is encountered, while use warnings; will merely give a warning (like the command-line switch -w) and let your code run. To read more about them check their respective manual pages at strict and warnings. Basic syntax overview A Perl script or program consists of one or more statements. These statements are simply written in the script in a straightforward fashion. There is no need to have a main() function or anything of that kind. Perl statements end in a semi-colon: 1.
print "Hello, world";
Comments start with a hash symbol and run to the end of the line 1.
# This is a comment
Whitespace is irrelevant: 1. 2. 3.
print "Hello, world" ;
... except inside quoted strings: 1. 2. 3.
# this would print with a linebreak in the middle print "Hello world";
Double quotes or single quotes may be used around literal strings: 1. 2.
print "Hello, world"; print 'Hello, world';
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
However, only double quotes "interpolate" variables and special characters such as newlines (\n): 1. 2.
print "Hello, $name\n"; # works fine print 'Hello, $name\n'; # prints $name\n literally
Numbers don't need quotes around them: 1.
print 42;
You can use parentheses for functions' arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence. 1. 2.
print("Hello, world\n"); print "Hello, world\n";
Perl variable types Perl has three main variable types: scalars, arrays, and hashes. Scalars A scalar represents a single value: 1. 2.
my $animal = "camel"; my $answer = 42;
Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. There is no need to pre-declare your variable types, but you have to declare them using the my keyword the first time you use them. (This is one of the requirements of use strict; .) Scalar values can be used in various ways: 3. 4. 5.
print $animal; print "The animal is $animal\n"; print "The square of $answer is ", $answer * $answer, "\n";
There are a number of "magic" scalars with names that look like punctuation or line noise. These special variables are used for all kinds of purposes, and are documented in perlvar. The only one you need to know about for now is $_ which is the "default variable". It's used as the default argument to a number of functions in Perl, and it's set implicitly by certain looping constructs. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
6. 7. Arrays
print;
# prints contents of $_ by default
An array represents a list of values: 1. 2. 3.
my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23);
Arrays are zero-indexed. Here's how you get at elements in an array: 4. 5.
print $animals[0]; print $animals[1];
# prints "camel" # prints "llama"
The special variable $#array tells you the index of the last element of an array: 6.
print $mixed[$#mixed];
# last element, prints 1.23
You might be tempted to use $#array + 1 to tell you how many items there are in an array. Don't bother. As it happens, using @array where Perl expects to find a scalar value ("in scalar context") will give you the number of elements in the array: 7.
if (@animals < 5) { ... }
The elements we're getting from the array start with a $ because we're getting just a single value out of the array; you ask for a scalar, you get a scalar. To get multiple values from an array: 8. 9. 10.
@animals[0,1]; # gives ("camel", "llama"); @animals[0..2]; # gives ("camel", "llama", "owl"); @animals[1..$#animals]; # gives all except the first element
This is called an "array slice". You can do various useful things to lists: 11. 12.
my @sorted = sort @animals; my @backwards = reverse @numbers;
There are a couple of special arrays too, such as @ARGV (the command line arguments to your script) and @_ (the arguments passed to a subroutine). These are documented in perlvar. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Hashes A hash represents a set of key/value pairs: 1.
my %fruit_color = ("apple", "red", "banana", "yellow");
You can use whitespace and the => operator to lay them out more nicely: 2. 3. 4. 5.
my %fruit_color = ( apple => "red", banana => "yellow", );
To get at hash elements: 6.
$fruit_color{"apple"};
# gives "red"
You can get at lists of keys and values with keys() and values(). 7. 8.
my @fruits = keys %fruit_colors; my @colors = values %fruit_colors;
Hashes have no particular internal order, though you can sort the keys and loop through them. Just like special scalars and arrays, there are also special hashes. The most well known of these is %ENV which contains environment variables. Read all about it (and other special variables) in perlvar. Scalars, arrays and hashes are documented more fully in perldata. More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes. A reference is a scalar value and can refer to any other Perl data type. So by storing a reference as the value of an array or hash element, you can easily create lists and hashes within lists and hashes. The following example shows a 2 level hash of hash structure using anonymous hash references. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
my $variables = { scalar => { description => "single item", sigil => '$', }, array => { description => "ordered list of items", sigil => '@', }, hash => {
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
11. 12. 13. 14. 15. 16.
description => "key/value pairs", sigil => '%', }, }; print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";
Exhaustive information on the topic of references can be found in perlreftut, perllol, perlref and perldsc. Variable scoping Throughout the previous section all the examples have used the syntax: 1.
my $var = "value";
The my is actually not required; you could just use: 1.
$var = "value";
However, the above usage will create global variables throughout your program, which is bad programming practice. my creates lexically scoped variables instead. The variables are scoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are defined. 1. 2. 3. 4. 5. 6. 7. 8. 9.
my $x = "foo"; my $some_condition = 1; if ($some_condition) { my $y = "bar"; print $x; # prints "foo" print $y; # prints "bar" } print $x; # prints "foo" print $y; # prints nothing; $y has fallen out of scope
Using my in combination with a use strict; at the top of your Perl scripts means that the interpreter will pick up certain common programming errors. For instance, in the example above, the final print $y would cause a compile-time error and prevent you from running the program. Using strict is highly recommended. Conditional and looping constructs Perl has most of the usual conditional and looping constructs. As of Perl 5.10, it even has a case/switch statement (spelled given /when ). See Switch statements in perlsyn for more details. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
The conditions can be any Perl expression. See the list of operators in the next section for information on comparison and boolean logic operators, which are commonly used in conditional statements. if 1. 2. 3. 4. 5. 6. 7.
if ( condition ) { ... } elsif ( other condition ) { ... } else { ... }
There's also a negated version of it: 8. 9. 10.
unless ( condition ) { ... }
This is provided as a more readable version of if (!condition). Note that the braces are required in Perl, even if you've only got one line in the block. However, there is a clever way of making your one-line conditional blocks more English like: 11. 12. 13. 14. 15. 16. 17. 18. while 1. 2. 3.
# the traditional way if ($zippy) { print "Yow!"; } # the Perlish post-condition way print "Yow!" if $zippy; print "We have no bananas" unless $bananas; while ( condition ) { ... }
There's also a negated version, for the same reason we have unless : 4. 5. 6.
until ( condition ) { ... }
You can also use while in a post-condition: ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
7.
print "LA LA LA\n" while 1;
# loops forever
for Exactly like C: 1. 2. 3.
for ($i = 0; $i <= $max; $i++) { ... }
The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning foreach loop. foreach 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
foreach (@array) { print "This element is $_\n"; } print $list[$_] foreach 0 .. $max; # you don't have to use the default $_ either... foreach my $key (keys %hash) { print "The value of $key is $hash{$key}\n"; }
For more detail on looping constructs (and some that weren't mentioned in this overview) see perlsyn. Builtin operators and functions Perl comes with a wide selection of builtin functions. Some of the ones we've already seen include print, sort and reverse. A list of them is given at the start of perlfunc and you can easily read about any given function by using perldoc -f functionname. Perl operators are documented in full in perlop, but here are a few of the most common ones: Arithmetic 1. + addition 2. - subtraction 3. * multiplication 4. / division Numeric comparison 1. == equality 2. != inequality 3. < less than ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
4. > greater than 5. <= less than or equal 6. >= greater than or equal String comparison 1. eq equality 2. ne inequality 3. lt less than 4. gt greater than 5. le less than or equal 6. ge greater than or equal (Why do we have separate numeric and string comparisons? Because we don't have special variable types, and Perl needs to know whether to sort numerically (where 99 is less than 100) or alphabetically (where 100 comes before 99). Boolean logic 1. && and 2. || or 3. ! not (and , or and not aren't just in the above table as descriptions of the operators. They're also supported as operators in their own right. They're more readable than the Cstyle operators, but have different precedence to && and friends. Check perlop for more detail.) Miscellaneous 1. = assignment 2. . string concatenation 3. x string multiplication 4. .. range operator (creates a list of numbers) Many operators can be combined with a = as follows: 1. 2. 3.
$a += 1; # same as $a = $a + 1 $a -= 1; # same as $a = $a - 1 $a .= "\n"; # same as $a = $a . "\n";
Files and I/O You can open a file for input or output using the open() function. It's documented in extravagant detail in perlfunc and perlopentut, but in short: 1. 2. 3.
open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
You can read from an open filehandle using the <> operator. In scalar context it reads a single line from the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list: 1. 2.
my $line = <$in>; my @lines = <$in>;
Reading in the whole file at one time is called slurping. It can be useful but it may be a memory hog. Most text file processing can be done a line at a time with Perl's looping constructs. The <> operator is most often seen in a while loop: 1. 2. 3.
while (<$in>) { # assigns each line in turn to $_ print "Just read in this line: $_"; }
We've already seen how to print to standard output using print(). However, print() can also take an optional first argument specifying which filehandle to print to: 1. 2. 3.
print STDERR "This is your final warning.\n"; print $out $record; print $log $logmessage;
When you're done with your filehandles, you should close() them (though to be honest, Perl will clean up after you if you forget): 1.
close $in or die "$in: $!";
Regular expressions Perl's regular expression support is both broad and deep, and is the subject of lengthy documentation in perlrequick, perlretut, and elsewhere. However, in short: Simple matching 1. if (/foo/) { ... } # true if $_ contains "foo" 2. if ($a =~ /foo/) { ... } # true if $a contains "foo" The // matching operator is documented in perlop. It operates on $_ by default, or can be bound to another variable using the =~ binding operator (also documented in perlop). Simple substitution 1. s/foo/bar/; 2. $a =~ s/foo/bar/;
# replaces foo with bar in $_ # replaces foo with bar in $a
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
3.
$a =~ s/foo/bar/g;
# replaces ALL INSTANCES of foo with bar in $a
The s/// substitution operator is documented in perlop. More complex regular expressions You don't just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. These are documented at great length in perlre, but for the meantime, here's a quick cheat sheet: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.
. a single character \s a whitespace character (space, tab, newline, ...) \S non-whitespace character \d a digit (0-9) \D a non-digit \w a word character (a-z, A-Z, 0-9, _) \W a non-word character [aeiou] matches a single character in the given set [^aeiou] matches a single character outside the given set (foo|bar|baz) matches any of the alternatives specified ^ $
start of string end of string
Quantifiers can be used to specify how many of the previous thing you want to match on, where "thing" means either a literal character, one of the metacharacters listed above, or a group of characters or metacharacters in parentheses. 14. 15. 16. 17. 18. 19.
* + ? {3} {3,6} {3,}
zero or more of the previous thing one or more of the previous thing zero or one of the previous thing matches exactly 3 of the previous thing matches between 3 and 6 of the previous thing matches 3 or more of the previous thing
Some brief examples: 20. 21. 22. 23. 24.
/^\d+/ /^$/ /(\d\s){3}/ /(a.)+/
string starts with one or more digits nothing in the string (start and end are adjacent) a three digits, each followed by a whitespace character (eg "3 4 5 ") matches a string in which every odd-numbered letter
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
25. is a (eg "abacadaf") 26. 27. # This loop reads from STDIN, and prints non-blank lines: 28. while (<>) { 29. next if /^$/; 30. print; 31. } Parentheses for capturing As well as grouping, parentheses serve a second purpose. They can be used to capture the results of parts of the regexp match for later use. The results end up in $1 , $2 and so on. 1. # a cheap and nasty way to break an email address up into parts 2. 3. if ($email =~ /([^@]+)@(.+)/) { 4. print "Username is $1\n"; 5. print "Hostname is $2\n"; 6. } Other regexp features Perl regexps also support backreferences, lookaheads, and all kinds of other complex details. Read all about them in perlrequick, perlretut, and perlre. Writing subroutines Writing subroutines is easy: 1. 2. 3. 4. 5.
sub logger { my $logmessage = shift; open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; print $logfile $logmessage; }
Now we can use the subroutine just as any other built-in function: 1.
logger("We have a logger subroutine!");
What's that shift? Well, the arguments to a subroutine are available to us as a special array called @_ (see perlvar for more on that). The default argument to the shift function just happens to be @_ . So my $logmessage = shift; shifts the first item off the list of arguments and assigns it to $logmessage . ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
We can manipulate @_ in other ways too: 1. 2.
my ($logmessage, $priority) = @_; # common my $logmessage = $_[0]; # uncommon, and ugly
Subroutines can also return values: 1. 2. 3. 4. 5.
sub square { my $num = shift; my $result = $num * $num; return $result; }
Then use it like: 1.
$sq = square(8);
For more information on writing subroutines, see perlsub. OO Perl OO Perl is relatively simple and is implemented using references which know what sort of object they are based on Perl's concept of packages. However, OO Perl is largely beyond the scope of this document. Read perlboot, perltoot, perltooc and perlobj. As a beginning Perl programmer, your most common use of OO Perl will be in using thirdparty modules, which are documented below. Using Perl modules Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A number of popular modules are included with the Perl distribution itself. Categories of modules range from text manipulation to network protocols to database integration to graphics. A categorized list of modules is also available from CPAN. To learn how to install modules you download from CPAN, read perlmodinstall. To learn how to use a particular module, use perldoc Module::Name. Typically you will want to use Module::Name, which will then give you access to exported functions or an OO interface to the module. perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
perlmod describes Perl modules in general. perlmodlib lists the modules which came with your Perl installation. Common Gateway Interface (CGI) Introduction to CGI Common Gateway Interface (CGI) is a standard for interfacing external programs with information servers on the Internet. So what does this mean? Basically, CGI is distinguished from a plain HTML document in that the plain HTML document is static, while CGI executes in real-time to output dynamic information. A program thatimplements CGI is executable, while the plain HTML document exists as a constant text file that doesn’t change. CGI, then, obtains information from users and tailors pages to their needs. While there are newer ways to perform the same kinds of actions that traditionally have been implemented with CGI, the latter is older and, in many ways, more versatile. It is for this reason that, over time, CGI has become generalized to refer to any program that runs on a Web server and interacts with a browser. For example, if you wanted to allow people from all over the world to query some database you had developed, you could create an executable CGI script that would transmit information to the database engine and then receive results and display them in the user’s Web browser. The user could not directly access the database without some gateway to allow access. This link between the database and the user is the “gateway,” which is where the CGI standard originated. A CGI script can be written in any language that allows it to be executed (e.g., C/C++, Fortran, PERL, TCL, Visual Basic, AppleScript, Python, and Unix shells), but by far, the most common language for CGI scripting is PERL, followed by C/C++. A CGI script is easier to debug, modify, and maintain than the typical compiled program, so many people prefer CGI for this reason. As you traverse the vast frontier of the World Wide Web, you will come across documents that make you wonder, "How did they do this?" These documents could consist of, among other things, forms that ask for feedback or registration information, imagemaps that allow you to click on various parts of the image, counters that display the number of users that accessed the document, and utilities that allow you to search databases for particular information. In most cases, you'll find that these effects were achieved using the Common Gateway Interface, commonly known as CGI. One of the Internet's worst-kept secrets is that CGI is astoundingly simple. That is, it's trivial in design, and anyone with an iota of programming experience can write rudimentary scripts that work. It's only when your needs are more demanding that you have to master the more complex workings of the Web. In a way, CGI is easy the same way cooking is easy: anyone can toast a muffin or poach an egg. It's only when you want a Hollandaise sauce that things start to get complicated. CGI is the part of the Web server that can communicate with other programs running on the server. With CGI, the Web server can call up a program, while passing user-specific data to the program (such as what host the user is connecting from, or input the user has supplied using ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
HTML form syntax). The program then processes that data and the server passes the program's response back to the Web browser. CGI isn't magic; it's just programming with some special types of input and a few strict rules on program output. Everything in between is just programming. Of course, there are special techniques that are particular to CGI, and that's what this book is mostly about. But underlying it all is the simple model shown in Figure 1.1. Figure 1.1: Simple diagram of CGI
How CGI Scripts Work
1. The Web surfer fills out a form and clicks, “Submit.” The information in the form is sent over the Internet to the Web server. 2. The Web server “grabs” the information from the form and passes it to the CGI software. 3. The CGI software performs whatever validation of this information that is required. For instance, it might check to see if an e-mail address is valid. If thisis a database program, the CGI software prepares a database statement to either add, edit, or delete information from the database. 4. The CGI software then executes the prepared database statement, which is passed to the database driver. ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
5. The database driver acts as a middleman and performs the requested action on the database itself. 6. The results of the database action are then passed back to the database driver. 7. The database driver sends the information from the database to the CGI software. 8. The CGI software takes the information from the database and manipulates it into the format that is desired. 9. If any static HTML pages need to be created, the CGI program accesses the Web server computer’s file system and reads, writes, and/or edits files. 10. The CGI software then sends the result it wants the Web surfer’s browser to see back to the Web server. 11. The Web server sends the result it got from the CGI software back to the Web surfer’s browser What is CGI? The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows: The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress. Web Browsing To understand the concept of CGI, lets see what happens when we click a hyper link to browse a particular web page or URL. Your browser contacts the HTTP web server and demand for the URL ie. filename. Web Server will parse the URL and will look for the filename in if it finds that file then sends back to the browser otherwise sends an error message indicating that you have requested a wrong file. Web browser takes response from web server and displays either the received file or error message. However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a PERL Script, Shell Script, C or C++ program etc.
________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
CGI Architecture Diagram
Web Server Support & Configuration Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /cgi-bin. By convention PERL CGI files will have extention as .cgi. First CGI Program Here is a simple link which is linked to a CGI script called hello.cgi. This file is being kept in /cgi-bin/ directory and it has following content. Before running your CGI program make sure you have chage mode of file using chmod 755 hello.cgi UNIX command. #!/usr/bin/perl print "Content-type:text/html\r\n\r\n"; print '<html>'; print '<head>'; print '<title>Hello Word - First CGI Program</title>'; print '</head>'; print '<body>'; print '<h2>Hello Word! This is my first CGI program</h2>'; print '</body>'; print '</html>'; 1; If you click hello.cgi then this produces following output: Hello Word! This is my first CGI program
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
This hello.cgi script is a simple PERL script which is writing its output on STDOUT file ie. screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and specifiy the content type to be displayed on the browser screen. Now you must have undertood basic concept of CGI and you can write many complicated CGI programs using PERL. This script can interact with any other exertnal system also to exchange information such as RDBMS. HTTP Header The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form HTTP Field Name: Field Content For Example Content-type:text/html\r\n\r\n There are few other important HTTP headers which you will use frequently in your CGI Programming. Header
Description
Content-type: String
A MIME string defining the format of the file being returned. Example is Content-type:text/html
Expires: Date String
The date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT.
Location: URL String
The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file.
Last-modified: String
The date of last modification of the resource.
Content-length: String The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file. Set-Cookie: String
Set the cookie passed through the string
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
CGI Environment Variables All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program. Variable Name
Description
CONTENT_TYPE
The data type of the content. Used when the client is sending attached content to the server. For example file upload etc.
CONTENT_LENGTH
The length of the query information. It's available only for POST requests
HTTP_COOKIE
Return the set cookies in the form of key & value pair.
HTTP_USER_AGENT
The User-Agent request-header field contains information about the user agent originating the request. Its name of the web browser.
PATH_INFO
The path for the CGI script.
QUERY_STRING
The URL-encoded information that is sent with GET method request.
REMOTE_ADDR
The IP address of the remote host making the request. This can be useful for logging or for authentication purpose.
REMOTE_HOST
The fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address.
REQUEST_METHOD
The method used to make the request. The most common methods are GET and POST.
SCRIPT_FILENAME
The full path to the CGI script.
SCRIPT_NAME
The name of the CGI script.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
SERVER_NAME
The server's hostname or IP Address
SERVER_SOFTWARE The name and version of the software the server is running.
Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment #!/usr/bin/perl print "Content-type: text/html\n\n"; print "<font size=+1>Environment</font>\n"; foreach (sort keys %ENV) { print "<b>$_</b>: $ENV{$_}<br>\n"; } 1;
HowToRaise a"FileDownload"DialogBox? Sometime it is desired that you want to give option where a use will click a link and it will pop up a "File Download" dialogue box to the user in stead of displaying actual content. This is very easy and will be achived through HTTP header. This HTTP header will be different from the header mentioned in previous section. For example,if you want make a FileName file downloadable from a given link then its syntax will be as follows. #!/usr/bin/perl # HTTP Header print "Content-Type:application/octet-stream; name=\"FileName\"\r\n"; print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n"; # Actual File Content will go hear. open( FILE, "<FileName" ); while(read(FILE, $buffer, 100) ) { print("$buffer"); } ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
GETand POST Methods You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently browser uses two methods two pass this information to web server. These methods are GET Method and POST Method. Passing Information using GET method: The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows: http://www.test.com/cgi-bin/hello.cgi?key1=value1&key2=value2 The GET method is the defualt method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limtation: only 1024 characters can be in a request string. This information is passed using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM> tags to pass information using GET method. Simple URL Example : Get Method Here is a simple URL which will pass two values to hello_get.cgi program using GET method.http://www.tutorialspoint.com/cgi-in/hello_get.cgi?first_name=ZARA&last_name=ALI Below is hello_get.cgi script to handle input given by web browser. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "GET") { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
{ ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $first_name = $FORM{first_name}; $last_name = $FORM{last_name}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Hello - Second CGI Program</title>"; print "</head>"; print "<body>"; print "<h2>Hello $first_name $last_name - Second CGI Program</h2>"; print "</body>"; print "</html>"; 1; Simple FORM Example: GET Method Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI script hello_get.cgi to handle this imput. <FORM action="/cgi-bin/hello_get.cgi" method="GET"> First Name: <input type="text" name="first_name"> <br> Last Name: <input type="text" name="last_name"> <input type="submit" value="Submit"> </FORM> Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result. First Name:
Last Name:
Submit
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Passing Information using POST method: A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input. Below is hello_post.cgi script to handle input given by web browser. This script will handle GET as well as POST method. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); }else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $first_name = $FORM{first_name}; $last_name = $FORM{last_name}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Hello - Second CGI Program</title>"; print "</head>"; print "<body>"; print "<h2>Hello $first_name $last_name - Second CGI Program</h2>"; print "</body>"; print "</html>"; 1; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Let us take again same examle as above, which passes two values using HTML FORM and submit button. We are going to use CGI script hello_post.cgi to handle this imput. <FORM action="/cgi-bin/hello_post.cgi" method="POST"> First Name: <input type="text" name="first_name"> <br> Last Name: <input type="text" name="last_name"> <input type="submit" value="Submit"> </FORM> Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result. First Name: Submit
Last Name:
Passing Checkbox Data to CGI Program Checkboxes are used when more than one option is required to be selected. Here is example HTML code for a form with two checkboxes <form action="/cgi-bin/checkbox.cgi" method="POST" target="_blank"> <input type="checkbox" name="maths" value="on"> Maths <input type="checkbox" name="physics" value="on"> Physics <input type="submit" value="Select Subject"> </form> The result of this code is the following form Maths
Physics
Select Subject
Below is checkbox.cgi script to handle input given by web browser for radio button. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
# Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); }else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } if( $FORM{maths} ){ $maths_flag ="ON"; }else{ $maths_flag ="OFF"; } if( $FORM{physics} ){ $physics_flag ="ON"; }else{ $physics_flag ="OFF"; } print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Checkbox - Third CGI Program</title>"; print "</head>"; print "<body>"; print "<h2> CheckBox Maths is : $maths_flag</h2>"; print "<h2> CheckBox Physics is : $physics_flag</h2>"; print "</body>"; print "</html>"; 1; Passing RadioButton Datato CGI Program Radio Buttons are used when only one option is required to be selected.Here is example HTML code for a form with two radio button: ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<form action="/cgi-bin/radiobutton.cgi" method="POST" target="_blank"> <input type="radio" name="subject" value="maths"> Maths <input type="radio" name="subject" value="physics"> Physics <input type="submit" value="Select Subject"> </form> The result of this code is the following form Maths
Physics
Select Subject
Below is radiobutton.cgi script to handle input given by web browser for radio button. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); }else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $subject = $FORM{subject}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Radio - Fourth CGI Program</title>"; print "</head>"; print "<body>"; print "<h2> Selected Subject is $subject</h2>"; print "</body>"; print "</html>"; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
1; Passing TextArea Data to CGI Program TEXTAREA element is used when multiline text has to be passed to the CGI Program. Here is example HTML code for a form with a TEXTAREA box: <form action="/cgi-bin/textarea.cgi" method="POST" target="_blank"> <textarea name="textcontent" cols=40 rows=4> Type your text here... </textarea> <input type="submit" value="Submit"> </form> The result of this code is the following form Type your text here...
Submit
Below is textarea.cgi script to handle input given by web browser. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); }else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
$FORM{$name} = $value; } $text_content = $FORM{textcontent}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Text Area - Fifth CGI Program</title>"; print "</head>"; print "<body>"; print "<h2> Entered Text Content is $text_content</h2>"; print "</body>"; print "</html>"; 1; Passing DropDown Box DatatoCGI Program Drop Down Box is used when we have many options available but only one or two will be selected. Here is example HTML code for a form with one drop down box <form action="/cgi-bin/dropdown.cgi" method="POST" target="_blank"> <select name="dropdown"> <option value="Maths" selected>Maths<option> <option value="Physics">Physics<option> </select> <input type="submit" value="Submit"> </form> The result of this code is the following form Maths
Submit
Below is dropdown.cgi script to handle input given by web browser. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); }else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $subject = $FORM{dropdown}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Dropdown Box - Sixth CGI Program</title>"; print "</head>"; print "<body>"; print "<h2> Selected Subject is $subject</h2>"; print "</body>"; print "</html>"; 1;
Using Cookies in CGI HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after completing many pages. But how to maintain user's session information across all the web pages. In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics. How It Works Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored. Cookies are a plain text data record of 5 variable-length fields: Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. Domain : The domain name of your site. Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page. Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists. Name=Value : Cookies are set and retrviewed in the form of key and value pairs.
Setting up Cookies This is very easy to send cookies to browser. These cookies will be sent along with HTTP Header. Assuming you want to set UserID and Password as cookies. So it will be done as follows #!/usr/bin/perl print "Set-Cookie:UserID=XYZ;\n"; print "Set-Cookie:Password=XYZ123;\n"; print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";\n"; print "Set-Cookie:Domain=www.tutorialspoint.com;\n"; print "Set-Cookie:Path=/perl;\n"; print "Content-type:text/html\r\n\r\n"; ...........Rest of the HTML Content.... From this example you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies. Here it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n. Retrieving Cookies This is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form. key1=value1;key2=value2;key3=value3.... ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Here is an example of how to retrieving cookies. #!/usr/bin/perl $rcvd_cookies = $ENV{'HTTP_COOKIE'}; @cookies = split /;/, $rcvd_cookies; foreach $cookie ( @cookies ){ ($key, $val) = split(/=/, $cookie); # splits on the first =. $key =~ s/^\s+//; $val =~ s/^\s+//; $key =~ s/\s+$//; $val =~ s/\s+$//; if( $key eq "UserID" ){ $user_id = $val; }elsif($key eq "Password"){ $password = $val; } } print "User ID = $user_id\n"; print "Password = $password\n"; This will produce following result User ID = XYZ Password = XYZ123 Reference- http://www.tutorialspoint.com/perl/perl_cgi.htm
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Chapter-4 Ecommerce What is Ecommerce - an overview In its simplest form ecommerce is the buying and selling of products and services by businesses and consumers over the Internet. People use the term "ecommerce" to describe encrypted payments on the Internet. Sometimes these transactions include the real-time transfer of funds from buyer to seller and sometimes this is handled manually through an eft-pos terminal once a secure order is received by the merchant. Internet sales are increasing rapidly as consumers take advantage of lower prices offer by wholesalers retailing their products. This trend is set to strengthen as web sites address consumer security and privacy concerns. What is e-commerce? Electronic commerce or e-commerce refers to a wide range of online business activities for products and services.1 It also pertains to â&#x20AC;&#x153;any form of business transaction in which the parties interact electronically rather than by physical exchanges or direct physical contact E-commerce is usually associated with buying and selling over the Internet, or conducting any transaction involving the transfer of ownership or rights to use goods or services through a computer-mediated network.3 Though popular, this definition is not comprehensive enough to capture recent developments in this new and revolutionary business phenomenon. A more complete definition is: E-commerce is the use of electronic communications and digital information processing technology in business transactions to create, transform, and redefine relationships for value creation between or among organizations, and between organizations and individuals.4 International Data Corp (IDC) estimates the value of global e-commerce in 2000 at US$350.38 billion. This is projected to climb to as high as US$3.14 trillion by 2004. IDC also predicts an increase in Asiaâ&#x20AC;&#x2122;s percentage share in worldwide e-commerce revenue from 5% in 2000 to 10% in 2004
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Asia-Pacific e-commerce revenues are projected to increase from $76.8 billion at year-end of 2001 to $338.5 billion by the end of 2004. Is e-commerce the same as e-business? While some use e-commerce and e-business interchangeably, they are distinct concepts. In e-commerce, information and communications technology (ICT) is used in inter-business or inter-organizational transactions (transactions between and among firms/organizations) and in business-to-consumer transactions (transactions between firms/organizations and individuals). In e-business, on the other hand, ICT is used to enhance one’s business. It includes any process that a business organization (either a for-profit, governmental or non-profit entity) conducts over a computer-mediated network. A more comprehensive definition of e-business is: “The transformation of an organization’s processes to deliver additional customer value through the application of technologies, philosophies and computing paradigm of the new economy.” Three primary processes are enhanced in e-business:5 1. Production processes, which include procurement, ordering and replenishment of stocks; processing of payments; electronic links with suppliers; and production control processes, among others; 2. Customer-focused processes, which include promotional and marketing efforts, selling over the Internet, processing of customers’ purchase orders and payments, and customer support, among others; 3. Internal management processes, which include employee services, training, internal information-sharing, video-conferencing, and recruiting. Electronic applications enhance information flow between production and sales forces to improve sales force productivity. Workgroup communications and electronic publishing of internal business information are likewise made more efficient.6 Is the Internet economy synonymous with e-commerce and e-business? The Internet economy is a broader concept than e-commerce and e-business. It includes ecommerce and e-business. The Internet economy pertains to all economic activities using electronic networks as a medium for commerce or those activities involved in both building the networks linked to the Internet and the purchase of application services7 such as the provision of enabling hardware and software and network equipment for Web-based/ online retail and shopping malls (or “e-malls”). It is made up of three major segments: physical (ICT) infrastructure, business infrastructure, and commerce What are the different types of e-commerce? The major different types of e-commerce are: business-to-business (B2B); businessto- consumer (B2C); business-to-government (B2G); consumer-to-consumer (C2C); and mobile commerce (m-commerce). What is B2B e-commerce? B2B e-commerce is simply defined as e-commerce between companies. This is the type of ecommerce that deals with relationships between and among businesses. About 80% of ecommerce is of this type, and most experts predict that B2B ecommerce will continue to grow faster than the B2C segment. ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
The B2B market has two primary components: e-frastructure and e-markets. Efrastructure is the architecture of B2B, primarily consisting of the following: ● logistics - transportation, warehousing and distribution (e.g., Procter and Gamble); ● application service providers - deployment, hosting and management of packaged software from a central facility (e.g., Oracle and Linkshare); ● outsourcing of functions in the process of e-commerce, such as Web-hosting, security and customer care solutions (e.g., outsourcing providers such as eShare, NetSales, iXL Enterprises and Universal Access); ● auction solutions software for the operation and maintenance of real-time auctions in the Internet (e.g., Moai Technologies and OpenSite Technologies); ● content management software for the facilitation of Web site content management and delivery (e.g., Interwoven and ProcureNet); and ● Web-based commerce enablers (e.g., Commerce One, a browser-based, XMLenabled purchasing automation software). E-markets are simply defined as Web sites where buyers and sellers interact with each other and conduct transactions.10 The more common B2B examples and best practice models are IBM, Hewlett Packard (HP), Cisco and Dell. Cisco, for instance, receives over 90% of its product orders over the Internet. Most B2B applications are in the areas of supplier management (especially purchase order processing), inventory management (i.e., managing order-ship-bill cycles), distribution management (especially in the transmission of shipping documents), channel management (i.e., information dissemination on changes in operational conditions), and payment management (e.g., electronic payment systems or EPS).11 eMarketer projects an increase in the share of B2B e-commerce in total global ecommerce from 79.2% in 2000 to 87% in 2004 and a consequent decrease in the share of B2C e-commerce from 20.8% in 2000 to only 13% in 2004
Benefits of E-Commerce E-commerce can provide the following benefits over non-electronic commerce: Reduced costs by reducing labour, reduced paper work, reduced errors in keying in data, reduce post costs ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Reduced time. Shorter lead times for payment and return on investment in advertising, faster delivery of product Flexibility with efficiency. The ability to handle complex situations, product ranges and customer profiles without the situation becoming unmanageable. Improve relationships with trading partners. Improved communication between trading partners leads to enhanced long-term relationships. Lock in Customers. The closer you are to your customer and the more you work with them to change from normal business practices to best practice e-commerce the harder it is for a competitor to upset your customer relationship. New Markets. The Internet has the potential to expand your business into wider geographical locations. Transaction costs. There are three cost areas that are significantly reduced through the conduct of B2B e-commerce. First is the reduction of search costs, as buyers need not go through multiple intermediaries to search for information about suppliers, products and prices as in a traditional supply chain. In terms of effort, time and money spent, the Internet is a more efficient information channel than its traditional counterpart. In B2B markets, buyers and sellers are gathered together into a single online trading community, reducing search costs even further. Second is the reduction in the costs of processing transactions (e.g. invoices, purchase orders and payment schemes), as B2B allows for the automation of transaction processes and therefore, the quick implementation of the same compared to other channels (such as the telephone and fax). Efficiency in trading processes and transactions is also enhanced through the B2B e-marketâ&#x20AC;&#x2122;s ability to process sales through online auctions. Third, online processing improves inventory management and logistics. Disintermediation. Through B2B e-markets, suppliers are able to interact and transact directly with buyers, thereby eliminating intermediaries and distributors. However, new forms of intermediaries are emerging. For instance, e-markets themselves can be considered as intermediaries because they come between suppliers and customers in the supply chain. Transparency in pricing. Among the more evident benefits of e-markets is the increase in price transparency. The gathering of a large number of buyers and sellers in a single e-market reveals market price information and transaction processing to participants. The Internet allows for the publication of information on a single purchase or transaction, making the information readily accessible and available to all members of the e-market. Increased price transparency has the effect of pulling down price differentials in the market. In this context, buyers are provided much more time to compare prices and make better buying decisions. Moreover, B2B e-markets expand borders for dynamic and negotiated pricing wherein multiple buyers and sellers collectively participate in price-setting and two-way auctions. In such environments, prices can be set through automatic matching of bids and offers. In the emarketplace, the requirements of both buyers and sellers are thus aggregated to reach competitive prices, which are lower than those resulting from individual actions. Economies of scale and network effects. The rapid growth of B2B e-markets creates traditional supply-side cost-based economies of scale. Furthermore, the bringing together of a significant number of buyers and sellers provides the demand-side economies of scale or network effects. Each additional incremental participant in the e-market creates value for all participants in the ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
demand side. More participants form a critical mass, which is key in attracting more users to an e-market. B2C - business to consumer In the Australian context B2C (business to consumer) trading activity has been slow to take off as at first consumers had doubts about the security of credit card transactions. Initial B2C trading focused on music CDs, software and books - items which were compact and easily shipped and where prices could be slashed once the retailer's cut was taken out of the margin. The Amazon book store would be a good example of this. These products pushed the perimeters of the market out for goods bought on-line. Books and CDs are relatively generic products. A CD bought in the US will have the same music and quality as one bought locally (the exception is the cover art) and so there is no doubt in the consumers mind exactly what the product is. This is not the case with clothing, where sizes can confuse the purchase decision... and where tactile senses figure strongly in the purchasing decision. Ebay has really transform purchasing behaviour on the web. Many people have made their first ecommerce transaction on Ebay. Many people sell on Ebay too, given raise to the work-from-home/drop shipping model of ecommerce. Interestingly though B2C transactions of previously localised or hard to find products can be extremely strong. If you have a unique product that is highly relevant to a niche audience, you are likely to do very well on the web. Although sales are increasing rapidly on the Internet, the volume of turnover figures continue to fail short of industry estimates. But as retail web sites become more navigable and privacy policies are displayed, more people will be drawn to Net-based purchasing by lower prices and convenience. Business-to-consumer e-commerce, or commerce between companies and consumers, involves customers gathering information; purchasing physical goods (i.e., tangibles such as books or consumer products) or information goods (or goods of electronic material or digitized content, such as software, or e-books); and, for information goods, receiving products over an electronic network 12 It is the second largest and the earliest form of e-commerce. Its origins can be traced to online retailing (or e-tailing). 13 Thus, the more common B2C business models are the online retailing companies such as Amazon.com, Drugstore.com, Beyond.com, Barnes and Noble and ToysRus. Other B2C examples involving information goods are E-Trade and Travelocity.The more common applications of this type of e-commerce are in the areas of purchasing products and information, and personal finance management, which pertains to the management of personal investments and finances with the use of online banking tools (e.g., Quicken) 14eMarketer estimates that worldwide B2C e-commerce revenues will increase from US$59.7 billion in 2000 to US$428.1 billion by 2004. Online retailing transactions make up a significant share of this market. eMarketer also estimates that in the Asia- Pacific region, B2C revenues, while registering a modest figure compared to B2B, nonetheless went up to $8.2 billion by the ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
end of 2001, with that figure doubling at the end of 2002-at total worldwide B2C sales below 10%. B2C e-commerce reduces transactions costs (particularly search costs) by increasing consumer access to information and allowing consumers to find the most competitive price for a product or service. B2C e-commerce also reduces market entry barriers sincethe cost of putting up and maintaining a Web site is much cheaper than installing a “brick-and-mortar” structure for a firm. In the case of information goods, B2C e-commerce is even more attractive because it saves firms from factoring in the additional cost of a physical distribution network. Moreover, for countries with a growing and robust Internet population, delivering information goods becomes increasingly feasible. What is B2G e-commerce? Business-to-government e-commerce or B2G is generally defined as commerce between companies and the public sector. It refers to the use of the Internet for public procurement, licensing procedures, and other government-related operations. This kind of e-commerce has two features: first, the public sector assumes a pilot/leading role in establishing e-commerce; and second, it is assumed that the public sector has the greatest need for making its procurement system more effective. Web-based purchasing policies increase the transparency of the procurement process (and reduces the risk of irregularities). To date, however, the size of the B2G ecommerce market as a component of total e-commerce is insignificant, as government e-procurement systems remain undeveloped. What is C2C e-commerce? Consumer-to-consumer e-commerce or C2C is simply commerce between private individuals or consumers. This type of e-commerce is characterized by the growth of electronic marketplaces and online auctions, particularly in vertical industries where firms/businesses can bid for what they want from among multiple suppliers. It perhaps has the greatest potential for developing new markets. This type of e-commerce comes in at least three forms: ● auctions facilitated at a portal, such as eBay, which allows online real-time bidding on items being sold in the Web; ● peer-to-peer systems, such as the Napster model (a protocol for sharing files between users used by chat forums similar to IRC) and other file exchange and later money exchange models; and classified ads at portal sites such as Excite Classifieds and eWanted (an interactive, online marketplace where buyers and sellers can negotiate and which features “Buyer Leads & Want Ads”). Consumer-to-business (C2B) transactions involve reverse auctions, which empower the consumer to drive transactions. A concrete example of this when competing airlines gives a traveler best travel and ticket offers in response to the traveler’s post that she wants to fly from New York to San Francisco. There is little information on the relative size of global C2C e-commerce. However, C2C figures of popular C2C sites such as eBay and Napster indicate that this market is quite large. These sites produce millions of dollars in sales every day. ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
What is m-commerce? M-commerce (mobile commerce) is the buying and selling of goods and services through wireless technology-i.e., handheld devices such as cellular telephones and personal digital assistants (PDAs). Japan is seen as a global leader in m-commerce. As content delivery over wireless devices becomes faster, more secure, and scalable,some believe that m-commerce will surpass wireline e-commerce as the method of choice for digital commerce transactions. This may well be true for the Asia-Pacific where there are more mobile phone users than there are Internet users. Industries affected by m-commerce include: ● Financial services, including mobile banking (when customers use their handheld devices to access their accounts and pay their bills), as well as brokerage services (in which stock quotes can be displayed and trading conducted from the same handheld device); ● Telecommunications, in which service changes, bill payment and account reviews can all be conducted from the same handheld device; ● Service/retail, as consumers are given the ability to place and pay for orders on-the-fly; and ● Information services, which include the delivery of entertainment, financial news, sports figures and traffic updates to a single mobile device. Forrester Research predicts US$3.4 billion sales closed using PDA and cell phones by 2005 (See Table 3). What forces are fueling e-commerce? There are at least three major forces fuelling e-commerce: economic forces, marketing and customer interaction forces, and technology, particularly multimedia convergence. B2B - business to business On the Internet, B2B (business to business) is the exchange of products or services between businesses rather than between businesses and consumers. Although early interest centered on the growth of retailing on the Internet, forecasts are that B2B revenue will far exceed B2C revenue in the near future.According to studies published in early 2000, the money volume of B2B exceeds that of B2C by 10 to 1. Over the next five years, B2B is expected to have a compound annual growth of 41%. Payment Gateways Both PayPal and Paymate offer credit card to bank account payments. Using one of these services you can invoice a customer, they can pay on Paymate and the funds will be deposited in your bank account ... less a transaction fee. Unlike a credit card merchant facility you will not have ongoing, minimum monthly fees... and the transaction fee is better than what most card companies offer small merchants. Additional these service are being backed into other ecommerce sites and shopping carts. Ebay for example uses Paypal to process some payments. The Rise and Rise of Auction Sites Auction sites such as Ebay and TradeMe have done an enormous amount to get ordinary people involved in online trading. Today many Ebay merchants are establishing their own web sites to ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
avoid Ebay and Pay Pal fees. They have learnt about how to present their product in their Ebay store and what issues are important to their customers in purchasing their product and now they are ready to start their own web site. Ecommerce Software EPages and fully integrated ecommerce software package that gives the web site owner control of ALL aspect of the web site, not give a product catelogue. It integrates with Ebay and Froogle. OSEcommerce is an open source ecommerce software solution. It covers most of the basics and is free, but there is no support other than documentation and forums. Many php developers are available for customisation. Eway offers "real time" payments from your web site to your bank account - the "glue" if you like between between your web site and bank. Let's say you have a web site that can take secure orders over SSL, you get the credit card number and put through a manual debit. Eway takes away the manual debit part of the circle. Mals-e.com offers a free shopping cart with customisable freight and payment options. Great for small stores. Security On the Internet, security is handled by passing "keys" between Internet server and client browser. When entering a secure site your browser is passed a public key by which transactions between you and the web server are encrypted. The servers key is always kept private. On your web site security can be handled two ways - depending on your budget. You can "piggyback" on someone else's "key" or you can register and pay for your own key or SSL certificate at Thwate or Verisign. Generally today businesses who host web sites offer access to a secure server and you can use their server and secure certificate for less than if you registered and paid for your own key. However the person browsing your site will notice the URL change to one they do not recognise - or trust. This may put your customers off (although there is no evidence of this). Therefore one of the advantages of buying your own key would be to have a URL for your secure pages that is consistent with the rest of your site. Presently, in Australia, Verisign may sell you a key for over $800 while foreign ecommerce providers like Instant SSL can sell it for $150. Although Verisign will argue that their key comes with a range of value add benefits, the bottom line is the product, i.e. the key, is the same. Credit Card Security The credit card companies are constantly evolving more secure credit card purchasing on the Internet. Often you will be asked to give a three digit verification code on the reverse of your card. This is to prove you have the card in your hand at the time you made the purchase. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Card companies also monitor your card activity to check for suspicious or out of ordinary purchases. They will contact you to verify it is you creating the usually break in the purchasing pattern. A range of biometric security measure have been proposed for credit cards. None are in widespread use at this time. Smartcards house a chip that has extra data in it about the card holder or carry an public key. To give customers confidence in purchasing on the Internet however card companies generally stand by customers who have had their card or card number stolen. This is not exactly the case for merchants though. The card company will alert the merchant to stolen cards and fraudulent transaction but do not indemnify the merchant from losses. Finding an ecommerce Provider/Partner Generally your web developer will advise you on the various security options. Their recommendation will consider things like volume of sales amount of data that needs to be captured per sale number of products in your store how often you need to change the product prices or other details your special freight requirements whether ordering has to interface with your banking/accounting system and so on Smaller businesses generally only required a secure form that returns results to the business owner, while a larger company with multiple products and locations will require a solution that takes the order, banks the money and sends a message to outwards goods to dispatch the goods. Who you choose as an ecommerce provider is therefore very much dependent on the size of your business and the range of your products. Banks Banks were slow at first to embrace Internet technologies citing security fears. More recently though in the drive for higher profits and greater shareholder return they have been moving more and more of their business online. Mostly this transition has gone smoothly. The only real difficulty is phishing scams where people are tricked into logging into a web site designed to look like their bank, but instead traps their login details. Banks have warned people not to click links in their email to login into the bank's web site, but to type the URL into their browser window every time. In Australia banks will soon issue a usb device required in conjunction with a PIN to access a bank account. This will tighten security further. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Integration Imagine a web site that would allow your customers to place an order for your goods and when they sent their order to you, your stock or inventory database was updated immediately, outwards goods were notified and the customer was sent an advice from packing staff when the goods were shipped. Many businesses do each of these things but few join them together or "integrate" them. As businesses become familiar with the Internet, it won't take long for business people to see that their order-taking, stock control and delivery systems should be merged into one seamless function. Indeed Microsoft Retail Manager offers precisely this function. Maintain one database in your store and synchronise it in real time with your online database... meaning your web site is constantly up to date. Reference-
http://www.dynamicwebs.com.au/tutorials/e-commerce.htm
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
CHAPTER 5 Servlets The rise of server-side Java applications is one of the latest and most exciting trends in Java programming. The Java language was originally intended for use in small, embedded devices. It was first hyped as a language for developing elaborate client-side web content in the form of applets. Until recently, Java's potential as a server-side development platform had been sadly overlooked. Now, Java is coming into its own as a language ideally suited for server-side development. Businesses in particular have been quick to recognize Java's potential on the server--Java is inherently suited for large client/server applications. The cross-platform nature of Java is extremely useful for organizations that have a heterogeneous collection of servers running various flavors of the Unix and Windows operating systems. Java's modern, object-oriented, memory-protected design allows developers to cut development cycles and increase reliability. In addition, Java's built-in support for networking and enterprise APIs provides access to legacy data, easing the transition from older client/server systems. Java servlets are a key component of server-side Java development. A servlet is a small, pluggable extension to a server that enhances the server's functionality. Servlets allow developers to extend and customize any Java-enabled server--a web server, a mail server, an application server, or any custom server--with a hitherto unknown degree of portability, flexibility, and ease. But before we go into any more detail, let's put things into perspective. History of Web Applications While servlets can be used to extend the functionality of any Java-enabled server, today they are most often used to extend web servers, providing a powerful, efficient replacement for CGI scripts. When you use a servlet to create dynamic content for a web page or otherwise extend the functionality of a web server, you are in effect creating a web application. While a web page merely displays static content and lets the user navigate through that content, a web application provides a more interactive experience. A web application can be as simple as a keyword search on a document archive or as complex as an electronic storefront. Web applications are being deployed on the Internet and on corporate intranets and extranets, where they have the potential to increase productivity and change the way that companies, large and small, do business. Common Gateway Interface The Common Gateway Interface, normally referred to as CGI, was one of the first practical techniques for creating dynamic content. With CGI, a web server passes certain requests to an external program. The output of this program is then sent to the client in place of a static file. The advent of CGI made it possible to implement all sorts of new functionality in web pages, and CGI quickly became a de facto standard, implemented on dozens of web servers.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
It's interesting to note that the ability of CGI programs to create dynamic web pages is a side effect of its intended purpose: to define a standard method for an information server to talk with external applications. This origin explains why CGI has perhaps the worst life cycle imaginable. When a server receives a request that accesses a CGI program, it must create a new process to run the CGI program and then pass to it, via environment variables and standard input, every bit of information that might be necessary to generate a response. Creating a process for every such request requires time and significant server resources, which limits the number of requests a server can handle concurrently. Figure 1-1 shows the CGI life cycle.
Figure 1-1. The CGI life cycle Even though a CGI program can be written in almost any language, the Perl programming language has become the predominant choice. Its advanced text-processing capabilities are a big help in managing the details of the CGI interface. Writing a CGI script in Perl gives it a semblance of platform independence, but it also requires that each request start a separate Perl interpreter, which takes even more time and requires extra resources. Another often-overlooked problem with CGI is that a CGI program cannot interact with the web server or take advantage of the server's abilities once it begins execution because it is running in a separate process. For example, a CGI script cannot write to the server's log file. FastCGI A company named Open Market developed an alternative to standard CGI named FastCGI. In many ways, FastCGI works just like CGI--the important difference is that FastCGI creates a single persistent process for each FastCGI program, as shown in Figure 1-2. This eliminates the need to create a new process for each request.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Figure 1-2. The FastCGI life cycle Although FastCGI is a step in the right direction, it still has a problem with process proliferation: there is at least one process for each FastCGI program. If a FastCGI program is to handle concurrent requests, it needs a pool of processes, one per request. Considering that each process may be executing a Perl interpreter, this approach does not scale as well as you might hope. (Although, to its credit, FastCGI can distribute its processes across multiple servers.) Another problem with FastCGI is that it does nothing to help the FastCGI program more closely interact with the server. As of this writing, the FastCGI approach has not been implemented by some of the more popular servers, including Microsoft's Internet Information Server. Finally, FastCGI programs are only as portable as the language in which they're written. mod_perl If you are using the Apache web server, another option for improving CGI performance is using mod_perl. mod_perl is a module for the Apache server that embeds a copy of the Perl interpreter into the Apache httpd executable, providing complete access to Perl functionality within Apache. The effect is that your CGI scripts are precompiled by the server and executed without forking, thus running much more quickly and efficiently. PerlEx PerlEx, developed by ActiveState, improves the performance of CGI scripts written in Perl that run on Windows NT web servers (Microsoft's Internet Information Server, O'Reilly's WebSite Professional, and Netscape's FastTrack Server and Enterprise Server). PerlEx uses the web server's native API to achieve its performance gains. Other Solutions CGI/Perl has the advantage of being a more-or-less platform-independent way to produce dynamic web content. Other well-known technologies for creating web applications, such as ASP and server-side JavaScript, are proprietary solutions that work only with certain web servers.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Server Extension APIs Several companies have created proprietary server extension APIs for their web servers. For example, Netscape provides an internal API called NSAPI (now becoming WAI) and Microsoft provides ISAPI. Using one of these APIs, you can write server extensions that enhance or change the base functionality of the server, allowing the server to handle tasks that were once relegated to external CGI programs. As you can see in Figure 1-3, server extensions exist within the main process of a web server.
Figure 1-3. The server extension life cycle Because server-specific APIs use linked C or C++ code, server extensions can run extremely fast and make full use of the server's resources. Server extensions, however, are not a perfect solution by any means. Besides being difficult to develop and maintain, they pose significant security and reliability hazards: a crashed server extension can bring down the entire server. And, of course, proprietary server extensions are inextricably tied to the server API for which they were written-and often tied to a particular operating system as well. Active Server Pages Microsoft has developed a technique for generating dynamic web content called Active Server Pages, or sometimes just ASP. With ASP, an HTML page on the web server can contain snippets of embedded code (usually VBScript or JScript--although it's possible to use nearly any language). This code is read and executed by the web server before it sends the page to the client. ASP is optimized for generating small portions of dynamic content. Server-side JavaScript Netscape too has a technique for server-side scripting, which it calls server-side JavaScript, or SSJS for short. Like ASP, SSJS allows snippets of code to be embedded in HTML pages to generate dynamic web content. The difference is that SSJS uses JavaScript as the scripting language. With SSJS, web pages are precompiled to improve performance.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Java Servlets Enter Java servlets. As was said earlier, a servlet is a generic server extension--a Java class that can be loaded dynamically to expand the functionality of a server. Servlets are commonly used with web servers, where they can take the place of CGI scripts. A servlet is similar to a proprietary server extension, except that it runs inside a Java Virtual Machine (JVM) on the server (see Figure 1-4), so it is safe and portable. Servlets operate solely within the domain of the server: unlike applets, they do not require support for Java in the web browser.
Figure 1-4. The servlet life cycle Unlike CGI and FastCGI, which use multiple processes to handle separate programs and/or separate requests, servlets are all handled by separate threads within the web server process. This means that servlets are also efficient and scalable. Because servlets run within the web server, they can interact very closely with the server to do things that are not possible with CGI scripts. Another advantage of servlets is that they are portable: both across operating systems as we are used to with Java and also across web servers. As you'll see shortly, all of the major web servers support servlets. We believe that Java servlets offer the best possible platform for web application development, and we'll have much more to say about this later in the chapter. Although servlets are most commonly used as a replacement for CGI scripts on a web server, they can extend any sort of server. Imagine, for example, a Java-based FTP server that handles each command with a separate servlet. New commands can be added by simply plugging in new servlets. Or, imagine a mail server that allows servlets to extend its functionality, perhaps by performing a virus scan on all attached documents or handling mail filtering tasks. This book emphasizes the use of servlets as a replacement for CGI programs. We believe that, at least in the near term, most servlet developers will design and deploy servlets for use with HTTP servers. In the long term, however, other uses are likely to catch on, so this book takes pains to point out what functionality is applicable to generic servlets and what applies only to HTTP servlets. Whatever you hope to do with servlets, this book can help you with your task. [1] ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
javax.servlet.GenericServlet Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable GenericServlet defines a generic, protocol-independent servlet. GenericServlet gives a blueprint and makes writing servlet easier. GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet implements the log method, declared in the ServletContext interface. To write a generic servlet, it is sufficient to override the abstract service method. javax.servlet.http.HttpServlet Signature: public abstract class java.io.Serializable
HttpServlet
extends
GenericServlet
implements
HttpServlet defines a HTTP protocol specific servlet. HttpServlet gives a blueprint for Http servlet and makes writing them easier. HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet. Signature: public interface ServletConfig ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.
Example code: <servlet> <servlet-name>ServletConfigTest</servlet-name> <servlet-class>com.javapapers.ServletConfigTest</servlet-class> <init-param> <param-name>topic</param-name> <param-value>Difference between ServletConfig and ServletContext</param-value> </init-param> </servlet> Signature: public interface ServletContext ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web applicationa is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file. Example code: <context-param> <param-name>globalVariable</param-name> <param-value>javapapers.com</param-value> </context-param> [2]
Servlet writers who are developing HTTP servlets that specialize the HttpServlet class should override the method or methods designed to handle the HTTP interactions that their servlet will handle. The candidate methods include, doGet, for handling GET, conditional GET and HEAD requests doPost, for handling POST requests doPut, for handling PUT requests doDelete, for handling DELETE requests By default, these methods return a BAD_REQUEST (400) error. An example HTTP servlet that handles GET and HEAD requests follows; it specializes the doGet method. The second example is also provided. It handles POST requests from a form by specializing the doPost method. The HttpServlet's service method, by default, also calls the doOptions method when it receives an OPTIONS request, and doTrace when it receives a TRACE request. The default implementation of doOptions automatically determines what HTTP options are supported and returns that information. The default implementation of doTrace causes a response with a message containing all of the headers sent in the trace request. These methods are not typically overridden. Whatever method you override, it will take two arguments. The first encapsulates the data from the client, and is an HttpServletRequest. The second encapsulates the response to the client, and is an HttpServletResponse. The following paragraphs discuss their use. An HttpServletRequest object provides access to HTTP header data, such as any cookies found in the request and the HTTP method with which the request was made. It, of course, allows the you to obtain the arguments that the client sent as part of the request. How you access the client data might depend on the HTTP method of the request. For any HTTP method, you can use the getParameterValues method, which will return the value of a named parameter. (The method getParameterNames provides the names of the parameters.) You can also manually parse the request. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
For requests using the HTTP GET method, the getQueryString method will return a String to be parsed. For HTTP methods POST, PUT, and DELETE, you have the choice between two methods. If you expect text data, then it can be read using the BufferedReader returned by the getReader method, if you expect binary data, then it should be read with the ServletInputStream returned by the getInputStream method. Note that you should use either the getParameterValues method or one of the methods that allow you to parse the data yourself. They can not be used together in a single request. For responding to the client, an HttpServletResponse object provides two ways of returning the response data to the user. You can use the writer returned by the getWriter method or the output stream returned by the getOutputStream method. You should use getWriter to return text data to the user, and getOutputStream for binary data. Before accessing the Writer or OutputStream, HTTP header data should be set. The HttpServletResponse class provides methods to access the header data, such as the content type and encoding, and content length of the response. After you set the headers, you may obtain the writer or output stream and send the body of the response to the user. Closing the writer or output stream after sending the response to the client allows the server to know when the response is complete. Example of an HTTP Servlet that handles the GET and HEAD methods /** * This is a simple example of an HTTP Servlet. It responds to the GET * and HEAD methods of the HTTP protocol. */ public class SimpleServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // set header field first res.setContentType("text/html"); // then get the writer and write the response data PrintWriter out = res.getWriter(); out.println("<HEAD><TITLE> SimpleServlet Output</TITLE></HEAD><BODY>"); out.println("<h1> SimpleServlet Output </h1>"); out.println("<P>This is output is from SimpleServlet."); out.println("</BODY>"); out.close(); }
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
public String getServletInfo() { return "A simple servlet"; } } The example above shows the code for the entire servlet. The doGet method, because it is returning text to the client, uses the HttpServletResponse's getWriter method. It sets the response header field, content type, before writing the body of the response, and closes the writer after writing the response. In addition to doGet, there is a second method, getServletInfo. More information on the getServletInfo method appears in later section. Because this servlet is an example shipped with the release, it is already compiled. To try the servlet, run it in the servletrunner section. Example of an HTTP Servlet that handles the POST method The following example processes data POSTed by a form. The form looks like this: <html> <head><title>JdcSurvey</title></head> <body> <form action=http://demo:8080/servlet/survey method=POST> <input type=hidden name=survey value=Survey01Results> <BR><BR>How Many Employees in your Company?<BR> <BR>1-100<input type=radio name=employee value=1-100> <BR>100-200<input type=radio name=employee value=100-200> <BR>200-300<input type=radio name=employee value=200-300> <BR>300-400<input type=radio name=employee value=300-400> <BR>500-more<input type=radio name=employee value=500-more> <BR><BR>General Comments?<BR> <BR><input type=text name=comment> <BR><BR>What IDEs do you use?<BR> <BR>JavaWorkShop<input type=checkbox name=ide value=JavaWorkShop> <BR>J++<input type=checkbox name=ide value=J++> <BR>Cafe'<input type=checkbox name=ide value=Cafe'> <BR><BR><input type=submit><input type=reset> </form> </body> </html> ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
The servlet writes the form data to a file, and responds to the user with a thank you message. The doPost method of the servlet looks like this: /** * Write survey results to output file in response to the POSTed * form. Write a "thank you" to the client. */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // first, set the "content type" header of the response res.setContentType("text/html"); //Get the response's PrintWriter to return text to the client. PrintWriter toClient = res.getWriter(); try { //Open the file for writing the survey results. String surveyName = req.getParameterValues("survey")[0]; FileWriter resultsFile = new FileWriter(resultsDir + System.getProperty("file.separator") + surveyName + ".txt", true); PrintWriter toFile = new PrintWriter(resultsFile); // Get client's form data & store it in the file toFile.println("<BEGIN>"); Enumeration values = req.getParameterNames(); while(values.hasMoreElements()) { String name = (String)values.nextElement(); String value = req.getParameterValues(name)[0]; if(name.compareTo("submit") != 0) { toFile.println(name + ": " + value); } } toFile.println("<END>"); //Close the file. resultsFile.close(); // Respond to client with a thank you toClient.println("<html>"); toClient.println("<title>Thank you!</title>"); toClient.println("Thank you for participating"); toClient.println("</html>"); } catch(IOException e) { ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
e.printStackTrace(); toClient.println( "A problem occured while recording your answers. " + "Please try again."); } // Close the writer; the response is done. toClient.close(); } The doPost method uses the getParameterNames and getParameterValues methods to get the form data. Because it returns text to the client, doPost calls the getWriter method. It sets the sets the response header field, content type, before writing the body of the response, and closes the writer when the response is complete. What is Session Tracking? There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with ecommerce. When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying? There are three typical solutions to this problem. 1. Cookies. You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. This is an excellent alternative, and is the most widely used approach. However, even though servlets have a high-level and easy-to-use interface to cookies, there are still a number of relatively tedious details that need to be handled: o Extracting the cookie that stores the session identifier from the other cookies (there may be many, after all), o Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and o Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never go in cookies). 2. URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
works with browsers that don't support cookies or where the user has disabled cookies. However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL returned to the user (even via indirect means like Location fields in server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost. 3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier. Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies if the browser supports them, but automatically revert to URL-rewriting when cookies are unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of the details, doesn't have to explicitly manipulate cookies or information appended to the URL, and is automatically given a convenient place to store data that is associated with each session. The Session Tracking API Using sessions in servlets is quite straightforward, and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions. Looking up the HttpSession object associated with the current request. This is done by calling the getSession method of HttpServletRequest. If this returns null, you can create a new session, but this is so commonly done that there is an option to automatically create a new session if there isn't one already. Just pass true to getSession. Thus, your first step usually looks like this: HttpSession session = request.getSession(true); Looking up Information Associated with a Session. HttpSession objects live on the server; they're just automatically associated with the requester by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects have a builtin data structure that let you store any number of keys and associated values. In version 2.1 and earlier of the servlet API, you use getValue("key") to look up a previously stored value. The return type is Object, so you have to do a typecast to whatever more specific type of data was associated with that key in the session. The return value is null if there is no such attribute. In version 2.2, getValue is deprecated in favor of getAttribute, both because of the better naming ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
match with setAttribute (the match for getValue is putValue, not setValue), and because setAttribute lets you use an attached HttpSessionBindingListener to monitor values, while putValue doesn't. Nevertheless, since few commercial servlet engines yet support version 2.2, I'll use getValue in my examples. Here's one representative example, assuming ShoppingCart is some class you've defined yourself that stores information on items being purchased. HttpSession session = request.getSession(true); ShoppingCart previousItems = (ShoppingCart)session.getValue("previousItems"); if (previousItems != null) { doSomethingWith(previousItems); } else { previousItems = new ShoppingCart(...); doSomethingElseWith(previousItems); } In most cases, you have a specific attribute name in mind, and want to find the value (if any) already associated with it. However, you can also discover all the attribute names in a given session by calling getValueNames, which returns a String array. In version 2.2, use getAttributeNames, which has a better name and which is more consistent in that it returns an Enumeration, just like the getHeaders and getParameterNames methods of HttpServletRequest. Although the data that was explicitly associated with a session is the part you care most about, there are some other pieces of information that are sometimes useful as well. getId. This method returns the unique identifier generated for each session. It is sometimes used as the key name when there is only a single value associated with a session, or when logging information about previous sessions. isNew. This returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions. getCreationTime. This returns the time, in milliseconds since the epoch, at which the session was made. To get a value useful for printing out, pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar. getLastAccessedTime. This returns the time, in milliseconds since the epoch, at which the session was last sent from the client. getMaxInactiveInterval. This returns the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never timeout. Associating Information with a Session As discussed in the previous section, you read information associated with a session by using getValue (or getAttribute in version 2.2 of the servlet spec). To specify information, you use putValue (or setAttribute in version 2.2), supplying a key and a value. Note that putValue replaces any previous values. Sometimes that's what you want (as with the referringPage entry in ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
the example below), but other times you want to retrieve a previous value and augment it (as with the previousItems entry below). Here's an example: HttpSession session = request.getSession(true); session.putValue("referringPage", request.getHeader("Referer")); ShoppingCart previousItems = (ShoppingCart)session.getValue("previousItems"); if (previousItems == null) { previousItems = new ShoppingCart(...); } String itemID = request.getParameter("itemID"); previousItems.addEntry(Catalog.getEntry(itemID)); session.putValue("previousItems", previousItems); 3. Example: Showing Session Information Here is a simple example that generates a Web page showing some information about the current session. package hall; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import java.util.*; public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Searching the Web"; String heading; Integer accessCount = new Integer(0);; if (session.isNew()) { heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; Integer oldAccessCount = // Use getAttribute, not getValue, in version // 2.2 of servlet API. (Integer)session.getValue("accessCount"); if (oldAccessCount != null) { ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
accessCount = new Integer(oldAccessCount.intValue() + 1); } } // Use putAttribute in version 2.2 of servlet API. session.putValue("accessCount", accessCount); out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n" + "<TR>\n" + " <TD>Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" + " <TD>Time of Last Access\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }[4] References: 1) http://docstore.mik.ua/orelly/java-ent/servlet/ch01_01.htm 2) http://javapapers.com/servlet/difference-between-servletconfig-and-servletcontext/ 3) http://www.cse.iitb.ac.in/dbms/Data/Courses/DBIS/Software/servlets/servlet_tutorial.htm l 4) http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-SessionTracking.html ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
CHAPTER 6 JSP JavaServer Pages (JSP) is a Java technology that helps software developers serve dynamically generated web pages based on HTML, XML, or other document types. Released in 1999 as Sun's answer to ASP and PHP .JSP was designed to address the perception that the Java programming environment didn't provide developers with enough support for the Web. To deploy and run, a compatible web server with servlet container is required. The Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems and the JCP must both be met by the container. Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSP pages are loaded in the server and are operated from a structured special installed Java server packet called a Java EE Web Application, often packaged as a .war or .ear file archive. JSP allows Java code and certain pre-defined actions to be interleaved with static web markup content, with the resulting page being compiled and executed on the server to deliver an HTML or XML document. The compiled pages and any dependent Java libraries use Java bytecode rather than a native software format, and must therefore be executed within a Java virtual machine (JVM) that integrates with the host operating system to provide an abstract platform-neutral environment. JSP syntax is a fluid mix of two basic content forms: scriptlet elements and markup. Markup is typically standard HTML or XML, while scriptlet elements are delimited blocks of Java code which may be intermixed with the markup. When the page is requested the Java code is executed and its output is added, in situ, with the surrounding markup to create the final page. JSP pages must be compiled to Java bytecode classes before they can be executed, but such compilation is needed only when a change to the source JSP file has occurred. Java code is not required to be complete (self contained) within its scriptlet element block, but can straddle markup content providing the page as a whole is syntactically correct (for example, any Java if/for/while blocks opened in one scriptlet element must be correctly closed in a later element for the page to successfully compile). This system of split inline coding sections is called step over scripting because it can wrap around the static markup by stepping over it. Markup which falls inside a split block of code is subject to that code, so markup inside an if block will only appear in the output when the if condition evaluates to true; likewise markup inside a loop construct may appear multiple times in the output depending upon how many times the loop body runs. The JSP syntax adds additional XML-like tags, called JSP actions, to invoke built-in functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as extensions to the standard HTML or XML tags. JVM operated tag libraries provide a platform independent way of extending the capabilities of a web server. Note that not all commercial Java servers are Java EE specification compliant. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
JSPs are compiled into servlets by a JSP compiler. The compiler either generates a servlet in Java code that is then compiled by the Java compiler, or it may compile the servlet to byte code which is directly executable. JSPs can also be interpreted on-the-fly, reducing the time taken to reload changes. Regardless of whether the JSP compiler generates Java source code for a servlet or emits the byte code directly, it is helpful to understand how the JSP compiler transforms the page into a Java servlet. For example, consider the following input JSP and its resulting generated Java Servlet. Input JSP <%@ page errorPage="myerror.jsp" %> <%@ page import="com.foo.bar" %> <html> <head> <%! int serverInstanceVariable = 1;%> <% int localStackBasedVariable = 1; %> <table> <tr><td><%= toStringOrBlank( "expanded inline data " + 1 ) %></td></tr> Resulting servlet package jsp_servlet; import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import com.foo.bar; // Imported as a result of <%@ page import="com.foo.bar" %> import … class _myservlet implements javax.servlet.Servlet, javax.servlet.jsp.HttpJspPage { // Inserted as a // result of <%! int serverInstanceVariable = 1;%> int serverInstanceVariable = 1; … public void _jspService( javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response ) throws javax.servlet.ServletException, ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
java.io.IOException { javax.servlet.ServletConfig config = …; // Get the servlet config Object page = this; PageContext pageContext = …; // Get the page context for this request javax.servlet.jsp.JspWriter out = pageContext.getOut(); HttpSession session = request.getSession( true ); try { out.print( "<html>\r\n" ); out.print( "<head>\r\n" ); … // From <% int localStackBasedVariable = 1; %> int localStackBasedVariable = 1; … out.print( "<table>\r\n" ); out.print( " <tr><td>" ); // From <%= toStringOrBlank( "expanded inline data " + 1 ) %> out.print( toStringOrBlank( "expanded inline data " + 1 ) ); out.print( " </td></tr>\r\n" ); … } catch ( Exception _exception ) { // Clean up and redirect to error page in <%@ page errorPage="myerror.jsp" %> } } } What are the Advantages of JSP? vs. Active Server Pages (ASP). ASP is a similar technology from Microsoft. The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS-specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers. vs. Pure Servlets. JSP doesn't give you anything that you couldn't in principle do with a servlet. But it is more convenient to write (and to modify!) regular HTML than to have a zillion println statements that generate the HTML. Plus, by separating the look from the content you can put different people on different tasks: your Web page design experts can build the HTML, leaving places for your servlet programmers to insert the dynamic content. vs. Server-Side Includes (SSI). SSI is a widely-supported technology for including externally-defined pieces into a static Web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynamic part. Besides, SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like. vs. JavaScript. JavaScript can generate HTML dynamically on the client. This is a useful capability, but only handles situations where the dynamic information is based on the ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
client's environment. With the exception of cookies, HTTP and form submission data is not available to JavaScript. And, since it runs on the client, JavaScript can't access serverside resources like databases, catalogs, pricing information, and the like. vs. Static HTML. Regular HTML, of course, cannot contain dynamic information. JSP is so easy and convenient that it is quite feasible to augment HTML pages that only benefit marginally by the insertion of small amounts of dynamic data. Previously, the cost of using dynamic data would preclude its use in all but the most valuable instances. JSP Directives In this JSP tutorial, you will learn about Directive tag with example, page directive, language, extends, import, session and buffer. Directive tag: The directive tag gives special information about the page to JSP Engine. This changes the way JSP Engine processes the page. Using directive tag, user can import packages, define error handling pages or session information of JSP page. General notation of directive tag is as follows: There are three types of directive tag. page Include Tag Lib Syntax and usage of directive tag page directive: General syntax for the page directive is <%@ page optional attribute ... %> There are many optional attributes available for page directive. Each of these attributes are used to give special processing information to the JSP Engine changing the way the JSP Engine processes the page. Some of the optional attributes available for page directive are: language extends import session buffer autoFlush ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
isThreadSafe info errorPage IsErrorPage contentType Syntax and usage of some of the optional attributes available for page directive discussed below. language: This attribute is used to denote the language used by a file. Language denotes the scripting language used in scriptlets, declarations, and expressions in the JSP page and any included files. Syntax of language attribute available for page directive is <%@ page language = "lang" %> In the above statement page and language are keywords and one places whatever language the file uses inside " ". For example if one wants to mention the language as java which is generally mentioned for all it is done as shown below: <%@ page language = "java" %> extends: This is used to signify the fully qualified name of the Super class of the Java class used by the JSP engine for the translated Servlet. Syntax of extends attribute available for page directive is <%@ page extends = "package.class"%> In the above statement page and extends are keywords. import: The import attribute is used to import all the classes in a java package into the current JSP page. With this facility, the JSP page can use other java classes. Syntax of import attribute available for page directive is <%@ page import = "java.util.*" %> ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
In the above statement page and import are keywords. If there are many Java packages that the JSP page wants to import, the programmer can use import more than once in a JSP page or separate the Java packages with commas, as shown below: <%@ page import="{package.class | package.*}, ..." %> session: The session attribute, when set to true, sets the page to make use of sessions. NOTE: by default, the session attribute value is set to true therefore, all JSP pages have session data available. If the user sets the session attribute to false, it should be performed in this section. When the session attribution is set to false, the user cannot use the session object, or a <jsp:useBean> element with scope=session in the JSP page which, if used, would give error. Syntax of session attribute available for page directive is <%@ page session="true|false" %> In the above statement page and session are keywords. And either true or false value can be setted and by default the value is true. buffer: If a programmer likes to control the use of buffered output for a JSP page then the buffer attribute can be made use of for achieving this. Syntax of buffer attribute available for page directive is <%@ page buffer = "none|8kb|sizekb" %> In the above statement page and buffer are keywords. The size of buffer size is mentioned in kilobytes. This is used by the out object to handle output sent from the compiled JSP page to the client web browser. The default value is 8kb. If a user specifies a buffer size then the output is buffered with at least the size mentioned by the user. For example one can specify as: <%@ page buffer = "none" %> [2]
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Include directive This section illustrates you about the include directive of the JSP. You will learn about what is include and how to implement it in the JSP page. This directive includes the static file in a JSP page and parse the file's JSP elements from the included JSP file. This directive has only one attribute i.e. the file which value is the relative URL of the file from the root directory of your JSP application. There are two ways of including a file in to the JSP page of your application. These are as follows: <%@include file="relativeURL" %> <jsp:include page="relativeURL" page="relativeURL"></jsp:include>
/>
or
<jsp:include
In above both cases, files are included in the JSP page of your application but the first case includes the file or the text or the code of the file in the calling JSP file at compilation time and executes later. But through the another way of including a file to the JSP page of your application, is <jsp:include page="relativeURL" /> allow you to include the specified file either static or dynamic resource in a JSP page. Contents of the include file is added to the calling JSP page if the resource is static otherwise the include file acts on the request object and result after execution of the include dynamic file on the server, sends back to the calling JSP page if the resource is dynamic. Here is the code of the program: <html> <head><title>Include Directive JSP Page.</title></head> <body> <%@include file="PageDir_Example.jsp" %><br/> <font size="10"><%="Hello World!" %></font><br/> <jsp:include page="PageDir_Example.jsp" /> </body> </html> Taglib Directive Defines a tag library and prefix for the custom tags used in the JSP page. JSP Syntax ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %> Examples <%@ taglib uri="http://www.jspcentral.com/tags" prefix="public" %> <public:loop> . . </public:loop> Description The <%@ taglib %> directive declares that the JSP file uses custom tags, names the tag library that defines them, and specifies their tag prefix. Here, the term custom tag refers to both tags and elements. Because JSP files can be converted to XML, it is important to understand the relationship of tags and elements. A tag is simply a short piece of markup that is part of a JSP element. A JSP element is a unit of JSP syntax that has an XML equivalent with a start tag and an end tag. An element can also contain other text, tags, or elements. For example, a jsp:plugin element always has a <jsp:plugin> start tag and a </jsp:plugin> end tag and may have a <jsp:params> element and a <jsp:fallback> element. You must use a <%@ taglib %> directive before you use the custom tag in a JSP file. You can use more than one <%@ taglib %> directive in a JSP file, but the prefix defined in each must be unique. The technique for creating custom tags is described in the JavaServer Pages Specification for version 1.1. Attributes uri="URIToTagLibrary" The Uniform Resource Identifier (URI) that uniquely names the set of custom tags associated with the named tag prefix. A URI can be any of the following:
A Uniform Resource Locator (URL), as defined in RFC 2396, available at http://www.hut.fi/u/jkorpela/rfc/2396/full.html A Uniform Resource Name (URN), as defined in RFC 2396 An absolute or relative pathname prefix="tagPrefix" The prefix that precedes the custom tag name, for example, public in <public:loop>. Empty prefixes are illegal. If you are developing or using custom tags, you cannot use the ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
tag prefixes jsp, jspx, java, javax, servlet, sun, and sunw, as they are reserved by Sun Microsystems. <jsp:forward> Forwards a client request to an HTML file, JSP file, or servlet for processing. JSP Syntax <jsp:forward page={"relativeURL" | "<%= expression %>"} /> or <jsp:forward page={"relativeURL" | "<%= expression %>"} > <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+ </jsp:forward> Examples <jsp:forward page="/servlet/login" /> <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" /> </jsp:forward> Description The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. The lines in the source JSP file after the <jsp:forward> element are not processed. You can pass parameter names and values to the target file by using a <jsp:param> clause. An example of this would be passing the parameter name username (with name="username") and the value scott (with value="scott") to a servlet login file as part of the request. If you use <jsp:param>, the target file should be a dynamic file that can handle the parameters. Be careful when using <jsp:forward> with unbuffered output. If you have used the <%@ page %> directive with buffer=none to specify that the output of your JSP file should not be buffered, and if the JSP file has any data in the out object, using <jsp:forward> will cause an IllegalStateException. Attributes page="{relativeURL | <%= expression %>}"
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
A String or an expression representing the relative URL of the file to which you are forwarding the request. The file can be another JSP file, a servlet, or any other dynamic file that can handle a request object. The relative URL looks like a path-it cannot contain a protocol name, port number, or domain name. The URL can be absolute or relative to the current JSP file. If it is absolute (beginning with a /), the path is resolved by your Web or application server. <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> Sends one or more name/value pairs as parameters to a dynamic file. The target file should be dynamic, that is, a JSP file, servlet, or other file that can process the data that is sent to it as parameters. You can use more than one <jsp:param> clause if you need to send more than one parameter to the target file. The name attribute specifies the parameter name and takes a case-sensitive literal string as a value. The value attribute specifies the parameter value and takes either a case-sensitive literal string or an expression that is evaluated at request time. Scripting Elements JSP scripting elements let you insert code into the servlet that will be generated from the JSP page. There are three forms: 1. Expressions of the form <%= expression %>, which are evaluated and inserted into the servlet’s output 2. Scriptlets of the form <% code %>, which are inserted into the servlet’s _jspService method (called by service) 3. Declarations of the form <%! code %>, which are inserted into the body of the servlet class, outside of any existing methods JSPActions In this section we will explain you about JSP Action tags and in the next section we will explain the uses of these tags with examples. We will also show how to use JSP Action Tags in the JSP application. What is JSP Actions? Servlet container provides many built in functionality to ease the development of the applications. Programmers can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page. Here is the list of JSP Actions: ________________________________________________________________________________________________________ Copyright © 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
jsp:include The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page. jsp:param The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block. jsp:forward The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page. jsp:plugin In older versions of Netscape Navigator and Internet Explorer; different tags is used to embed applet. The jsp:plugin tag actually generates the appropriate HTML code the embed the Applets correctly. jsp:fallback The jsp:fallback tag is used to specify the message to be shown on the browser if applets is not supported by browser. Example: <jsp:fallback> <p>Unable to load applet</p> </jsp:fallback> jsp:getProperty The jsp:getPropertyB is used to get specified property from the JavaBean object. jsp:setProperty The jsp:setProperty tag is used to set a property in the JavaBean object. jsp:useBean The jsp:useBean tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.[4] SessionManagementIn JSP As we know that the Http protocol is a stateless protocol, that means that it can't persist the data. Http treats each request as a new request so every time you will send a request you will be considered as a new user. It is not reliable when we are doing any type of transactions or any other related work where persistence of the information is necessary. To remove these obstacles we use session management. In session management whenever a request comes for any resource, a unique token is generated by the server and transmitted to the client by the response object and stored on the client machine as a cookie. We can also say that the process of managing the state of a web based client is through the use of session IDs. Session IDs are used to uniquely identify a client browser, while the server side processes are used to associate the session ID with a level ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
of access. Thus, once a client has successfully authenticated to the web applicatiion, the session ID can be used as a stored authentication voucher so that the client does not have to retype their login information with each page request. Now whenever a request goes from this client again the ID or token will also be passed through the request object so that the server can understand from where the request is coming. Session management can be achieved by using the following thing. 1. Cookies: cookies are small bits of textual information that a web server sends to a browser and that browsers returns the cookie when it visits the same site again. In cookie the information is stored in the form of a name, value pair. By default the cookie is generated. If the user doesn't want to use cookies then it can disable them. 2. URL rewriting: In URL rewriting we append some extra information on the end of each URL that identifies the session. This URL rewriting can be used where a cookie is disabled. It is a good practice to use URL rewriting. In this session ID information is embedded in the URL, which is recieved by the application through Http GET requests when the client clicks on the links embedded with a page. 3. Hidden form fields: In hidden form fields the html entry will be like this : <input type ="hidden" name = "name" value="">. This means that when you submit the form, the specified name and value will be get included in get or post method. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command. In JSP we have been provided a implicit object session so we don't need to create a object of session explicitly as we do in Servlets. In Jsp the session is by default true. The session is defined inside the directive <%@ page session = "true/false" %>. If we don't declare it inside the jsp page then session will be available to the page, as it is default by true. For the convenience to understand the concept of session management we have made one program. The code of the program is given below: <html> <head> <title>Welcome to the first program of jsp</title> </head> <body> <form method = "post" action = "FirstPageOfSession.jsp"> <font size = 6>Enter your name<input type = "text" name = "name"></font><br><br> <font size = 6>Enter your password<input type="password" name = "pwd" > </font><br><br> <input type = "submit" name = "submit" value = "submit" > </form> ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
</body> </html> <% String name = request.getParameter("name"); String password = request.getParameter("pwd"); if(name.equals("Williams") && password.equals("abcde")) { session.setAttribute("username",name); response.sendRedirect("NextPageAfterFirst.jsp"); } else { response.sendRedirect("SessionManagement.html"); } %> <html> <head> <title>Welcome in In the program of URL rewriting</title> </head> <body> <font size = 6>Hello</font> <%= session.getAttribute("username") %> </body> </html> The output of the program is given below:
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
When the values entered is correct.
When the entered values are incorrect, the SessionManagement.html will be displayed again to you.
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
JSPpage errorhandling For JSP pages that require more intricate error handling and recovery, a page can be written to directly handle errors from the data bean; that is, handling errors from within the same page. The JSP page can either catch exceptions thrown by the data bean or it can check for error codes set within each data bean, depending on how the data bean was activated. The JSP page can then take an appropriate recovery action based on the error received. Note that a JSP page can use any combination of the following error handling scopes. The JSP page should use try and catch blocks to capture the exception so that it can take appropriate action based on the exception type. Here is an example of a JSP snippet using try and catch Java statements: SomeDataBean sdb = new SomeDataBean(); sdb.setSomeProperty(""); try { com.ibm.commerce.beans.DataBeanManager.activate(sdb, request); } catch(Exception ex){ //Handle the exception in whichever way you want.. } To obtain more details about an error, include an ErrorDataBean your JSP file. ErrorDataBeans can be instantiated, populated, and used. Here is an example: ErrorDataBean errorBean = new ErrorDataBean ( ); com.ibm.commerce.beans.DataBeanManager.activate (errorBean, request); Once the data bean is instantiated, it has methods to get ExceptionData, ExceptionMessage, MessageKey, ExceptionType and other helper methods. For storefront JSP files, use StoreErrorDataBean to handle the errors. Error handling outside of the current page You can have a separate dedicated error handling page, delegating the request to that page, when an exception occurs in the current JSP page. When using a separate error handling page, you can have two options: error handling at the page level or at the application level. Error handling at the page level A JSP page can specify its own default error JSP page from an exception occurring within it, through the JSP error tag. This enables a JSP page to specify its own handling of an error. A JSP page that does not contain a JSP error tag will have an error fall through to the application-level error JSP page. In a page-level error JSP page, it must call a JSP helper class ( com.ibm.commerce.server.JSPHelper ) to roll back the current transaction. ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
Here is an example of including error handling at the page level: 1. Create a single error JSP page which handles the errors that occur across all the other JSP pages in the application. To specify a JSP page as an errorHandler page, use this JSP page directive: <%@ page isErrorPage="true" %> In the errorHandler JSP page, use ErrorDataBean or StoreErrorDataBean to retrieve more information about the exception and display messages. 2. Include the errorHandler JSP page in other JSP pages, by using this JSP directive to specify that if there are exceptions occurring on the current page, forward the request to errorHandler.jsp: <%@ page errorPage="/errorHandler.jsp" %> Error handling at the application level An application under WebSphere Commerce can specify a default error JSP page when an exception from within any of its servlets or JSP pages occurs. The application-level error JSP page can be used as a site level or store level error handler. In the application-level error JSP page, a call must be made to the servlet helper class to roll back the current transaction. Use the application-level error handling strategy only when required. Include error handler at the application level using the deployment descriptor (WEBINF/web.xml) of the Web application. For example, if you want to handle a Payment Exception generically at the application level, code a paymentError.jsp file and specify the same in the web.xml file by using the <error-page> tag. Here is an example: <error-page> <exception-type>PaymentException</exception-type> <location>/paymentError.jsp</location> </error-page> Using this example, if Payment Exception is thrown in a JSP page that does not handle certain exception types, or if the JSP page does not specify its own error page, then the request will be redirected to paymentError.jsp. The paymentError.jsp file can use ErrorDataBean or StoreErrorDataBean to retrieve more information about the exception. To include a generic page for all exceptions, at application level, use the following in the web.xml file: <error-page> ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<exception-type>Exception</exception-type> <location>/paymentError.jsp</location> </error-page> Note that in the <exception-type> tag, instead of using the exception class name, you can specify the specific error code, such as browser error 404, which is a page not found error.[6] What Is a Custom Tag? A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed. Custom tags have a rich set of features. They can Be customized via attributes passed from the calling page. Access all the objects available to JSP pages. Modify the response generated by the calling page. Communicate with each other. You can create and initialize a JavaBeans component, create a variable that refers to that bean in one tag, and then use the bean in another tag. Be nested within one another, allowing for complex interactions within a JSP page Declaring Tag Libraries You declare that a JSP page will use tags defined in a tag library by including a taglib directive in the page before any custom tag is used: <%@ taglib uri="/WEB-INF/tutorial-template.tld" prefix="tt" %>
The uri attribute refers to a URI that uniquely identifies the tag library descriptor (TLD), described in the section Tag Library Descriptors. This URI can be direct or indirect. The prefix attribute defines the prefix that distinguishes tags defined by a given tag library from those provided by other tag libraries. Tag library descriptor file names must have the extension .tld. TLD files are stored in the WEBINF directory of the WAR or in a subdirectory of WEB-INF. You can reference a TLD directly and indirectly. The following taglib directive directly references a TLD filename: <%@ taglib uri="/WEB-INF/tutorial-template.tld" prefix="tt" %>
This taglib directive uses a short logical name to indirectly reference the TLD: ________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.
<%@ taglib uri="/tutorial-template" prefix="tt" %>
A logical name must be mapped to an absolute location in the Web application deployment descriptor. To map the logical name /tutorial-template to the absolute location /WEBINF/tutorial-template.tld: 1. Select Bookstore3WAR. 2. Select the File Refs tab. 3. Click the Add button in the JSP Tag Libraries subpane. 4. Enter the relative URI /tutorial-template in the Coded Reference field. 5. Enter the absolute location /WEB-INF/tutorial-template.tld in the Tag Library field.[8]
References:1) http://en.wikipedia.org/wiki/JavaServer_Pages 2) http://www.exforsys.com/tutorials/jsp/jsp-directive-tag.html 3) http://java.sun.com/products/jsp/tags/11/syntaxref11.fm8.html 4) http://www.roseindia.net/jsp/jspactions.shtml 5) http://www.roseindia.net/jsp/jspsession/SessionManagement.shtml 6) http://publib.boulder.ibm.com/infocenter/wchelp/v6r0m0/index.jsp?topic=/com.ib m.commerce.developer.doc/concepts/csdjsperror.htm 7) http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags2.html#67760 8) http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags4.html#69766
________________________________________________________________________________________________________ Copyright Š 2011 by Indira Institute of management (MCA), Pune. {IIMP (MCA)} This online tutorial is compiled with the help of Referred References by Faculty of IIMP (MCA) with the help of ISSUU. For any Query of Copyright Contact: itlibrary@indiraiimp.edu.in.