100898068 web technologies notes

Download 100898068 Web Technologies Notes

If you can't read please download the document

Upload: mohd-khairuddin-yasin

Post on 04-Oct-2015

6 views

Category:

Documents


1 download

DESCRIPTION

xxx

TRANSCRIPT

WEB TECHNOLOGIESMATERIALByP.Ravi Teja Asst .Professor, C.S.E.Dept, G.I.S.T-S.P.S.R.Nellore Ph: 9030104017P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 1

UNIT-I Introduction To Web ServerA web server is the combination of computer and the program installed on it. Webserver interacts with the client through a web browser. It delivers the web pages to the client and to an application by using the web browser. and the HTTP protocols respectively. We can also define the web server as the package of largenumber of programs installed on a computer connected to Internet or intranet fordownloading the requested files using File Transfer Protocol, serving e-mail and building and publishing web pages. A web server works on a client server model. A computer connected to the Internet or intranet must have a server program. The most commonly used Web servers are Apache, which has been implemented for a variety of computer platforms, and Microsofts Internet Information Server (IIS), which runs under Windows operating systems.. There are many types of web server, Enterprise uses according to their need. Some of the popular categories of web servers are HTTP Server - It handles HTTP request coming from clients browser and transfer the static pages to client in response to their request. This pages runs of the client browser. It generally contains the static pages. FTP Server - This type of server used for file transfer from one machine (Computer) to another using the internet or intranet. It uses File Transfer Protocols to transfer file from one computer to another. Such type ofserver uses some file transfer policies, authentication, login validation etc Mail Server - A Mail Server store and retrieve mail messages from client mail box. Application Server - It is installed database and web servers Apache Tomcat ispopular web server being used today for the implementation of some java technologies. It is a open source software used for implementing web applications. In the next example of servlet we will use the Apache Tomcat as a web server.Email:[email protected] Page 2P.Ravi Theja,Asst.Professor,GIST,Nellore

Web Server OperationClients and servers is a natural consequence of information distribution, this configuration offers some additional benefits for the Web. Web servers need not be involved in this display process, they can handle many clients. Web browsers initiate network communications with servers by sending them URLs. A URL can specify one of two different things: the address of a data file stored on the serverthat is to be sent to the client, or a program stored on the server that the client wants executed, with the output of the program returned to the client. Allthe communications between a Web client and a Web server use the standard Web protocol, Hypertext Transfer Protocol (HTTP). When a Web server begins execution,it informs the operating system under which it is running that it is now ready to accept incoming network connections through a specific port on the machine. While in this running state, the server runs as a background process in the operating system environment. A Web client, or browser, opens a network connection toa Web server, sends information requests and possibly data to the server, receives information from the server, and closes the connection. The primary task of aWeb server is to monitor a communications port on its host machine, accept HTTPcommands through that port, and perform the operations specified by the commands. All HTTP commands include a URL, which includes the specification of a host server machine. When the URL is received, it is translated into either a file name or a program name. All current Web servers have a common ancestry: the first two servers, developed at CERN in Europe and NCSA at the University of Illinois.Currently, the most common server configuration is Apache running on some version of UNIX.General Server CharacteristicsThe file structure of a Web server has two separate directories. The root of oneof these is called the document root. The file hierarchy that grows from the document root stores the Web documents to which the server has direct access and normally serves to clients. The root of the other directory is called the serverroot. This directory, along with its descendant directories, stores the server and its support software. The files stored directly in the document root are those available to clients through top-level URLs. Typically, clients do not accessthe document root directly in URLs; rather, the server maps requested URLs to the document root, whose location is not known to clients. For example, suppose that the site name is www.tunias.com (not a real siteat least, not yet), which we will assume to be a UNIX-based system. Suppose further that the document root isnamed topdocs and is stored in the /admin/web directory, making its address /admin/web/topdocs. A request for a file from a client with the URL http://www.tunias.com/petunias.html will cause the server to search for the file with the file path /admin/web/topdocs/petunias.html. Likewise, the URL http://www.tunias.com/bulbs/tulips.html will cause the server to search for the file with the address /admin/web/topdocs/bulbs/tulips.html Many servers allow part of the servable document collection to be stored outside the directory at the document root. The secondary areas from which documents can be served are called virtual document trees. For example, the original configuration of a server might have the server store all its servable documents from the primary system disk on the server machine.Later, the collection of servable documents might outgrow that disk, in which case part of the collection could be stored on a secondary disk. This secondary disk might reside on the server machine or on some other machine on a local areanetwork.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 3

Many servers can support more than one site on a computer, potentially reducingthe cost of each site and making their maintenance more convenient. Such secondary hosts are called virtual hosts. Some servers can serve documents that are inthe document root of other machines on the Web; in this case, they are called proxy servers. Although Web servers were originally designed to support only the HTTP protocol, many now support ftp, gopher, news, and mailto.Apache HTTP ServerThe Apache HTTP Server, commonly referred to as Apache ,is web server software notable for playing a key role in the initial growth of the World Wide Web. In 2009 it became the first web server software to surpass the 100 million website milestone. Apache was the first viable alternative to the Netscape CommunicationsCorporation web server (currently named Oracle iPlanet Web Server), and since has evolved to rival other web servers in terms of functionality and performance.Typically Apache is run on a Unix-like operating system. Apache is developed andmaintained by an open community of developers under the auspices of the ApacheSoftware Foundation. The application is available for a wide variety of operating systems, including Unix, GNU, FreeBSD, Linux, Solaris, Novell NetWare, AmigaOS, Mac OS X, Microsoft Windows, OS/2, TPF, and eComStation. Released under the Apache License, Apache is open-source software. Apache was originally based on NCSA HTTPd code. The NCSA code is since removed from Apache, due to a rewrite. WhenApache begins execution, it reads its configuration information from a file andsets its parameters to operate accordingly. A new copy of Apache includes default configuration information for a typical operation. The site manager modifies this configuration information to fit his or her particular needs and tastes. Forhistorical reasons, there are three configuration files in an Apache server: httpd.conf, srm.conf, and access.conf. Only one of these, httpd.conf, actually stores the directives that control an Apache servers behavior. The other two point tohttpd.conf, which is the file that contains the list of directives that specifythe servers operation. Since April 1996 Apache has been the most popular HTTP server software in use. As of May 2011 Apache was estimated to serve 63% of all websites and 66% of the million busiest.[5] Stronghold was a fork of the Apache HTTP Server, which included the Secure Socket Layer software to enable https. It was created by C2Net, which was eventually purchased by Red Hat. Stronghold s last support date was 2005-12-31 Name According to the FAQ in the Apache project website, the name Apache was chosen out of respect to the Native American tribe Apache (Inde) and its superior skills in warfare and strategy. In addition the website claims that the name s story resulting from the server being A Patchy server (since it was a conjunction of software patches) is popular but incorrect.[6]Features Apache supports a variety of features, many implemented as compiled modules which extend the core functionality. These can range from server-side programming language support to authentication schemes. Some common language interfaces support Perl, Python, Tcl, and PHP. Popular authentication modules include mod_access, mod_auth, mod_digest, and mod_auth_digest, the successor to mod_digest. A sample of other features include Secure Sockets Layer and Transport Layer Security support (mod_ssl), a proxy module (mod_proxy), a URL rewriter (also knownas a rewrite engine,P.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 4

implemented under mod_rewrite), custom log files (mod_log_config), and filteringsupport (mod_include and mod_ext_filter). Popular compression methods on Apacheinclude the external extension module, mod_gzip, implemented to help with reduction of the size (weight) of web pages served over HTTP. ModSecurity is an opensource intrusion detection and prevention engine for web applications. Apache logs can be analyzed through a web browser using free scripts such as AWStats/W3Perl or Visitors. Virtual hosting allows one Apache installation to serve many different actual websites. For example, one machine with one Apache installation could simultaneously serve www.example.com, www.example.org, test47.test-server.example.edu, etc. Apache features configurable error messages, DBMS-based authentication databases, and content negotiation. It is also supported by several graphical user interfaces (GUIs). It supports password authentication and digital certificate authentication. Apache has a built in search engine and an HTML authorizing tool and supports FTP. Performance Although the main design goal of Apacheis not to be the "fastest" web server, Apache does have performance comparable to other "high-performance" web servers. Instead of implementing a single architecture, Apache provides a variety of MultiProcessing Modules (MPMs) which allow Apache to run in a process-based, hybrid (process and thread) or event-hybrid mode, to better match the demands of each particular infrastructure. This implies that the choice of correct MPM and the correct configuration is important. Wherecompromises in performance need to be made, the design of Apache is to reduce latency and increase throughput, relative to simply handling more requests, thus ensuring consistent and reliable processing of requests within reasonable time-frames. The Apache version considered by the Apache Foundation as providing high-performance is the multithreaded version which mixes the use of several processesand several threads per process. While this architecture works faster than theprevious multi-process based topology (because threads have a lower overhead than processes), it does not match the performances of the event-based architectureprovided by other servers, especially when they process events with several worker threads. This difference can be easily explained by the overhead that one thread per connection brings (as opposed to a couple of worker threads per CPU, each processing many connection events). Each thread needs to maintain its own stack, environment, and switching from one thread to another is also an expensive task for CPUs.Internet Information ServicesInternet Information Services (IIS) formerly called Internet Information Server is a web server application and set of feature extension modules created by Microsoft for use with Microsoft Windows. It is the most used web server after Apache HTTP Server. IIS 7.5 supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP. It is anintegral part of Windows Server family of products, as well as certain editionsof Windows XP, Windows Vista and Windows 7. IIS is not turned on by default whenWindows is installed.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 5

From the point of view of the site manager, the most important difference between Apache and IIS is that Apache is controlled by a configuration file that is edited by the manager to change Apaches behavior. With IIS, server behavior is modified by changes made through a window-based management program, named the IIS snap-in, which controls both IIS and ftp. This program allows the site manager toset parameters for the server. History The first Microsoft web server was a research project at European Microsoft Windows NT Academic Centre (EMWAC), part of the University of Edinburgh in Scotland, and was distributed as freeware. However, since the EMWAC server was unable to scale sufficiently to handle the volume of traffic going to microsoft.com, Microsoft was forced to develop its own web server, IIS. Almost every version of IIS was released either alongside or with a version of Microsoft Windows operating system. IIS 1.0 was initially released asa free add-on, a set of web-based services for Windows NT 3.51. However, IIS 2.0was included with Windows NT 4.0. IIS 3.0, which was included with Service Pack3 of Windows NT 4, introduced the Active Server Pages dynamic scripting environment. IIS 4.0 was released as part of an "Option Pack" for Windows NT 4.0 and dropped support for the Gopher protocol.[citation needed] IIS 5.0 shipped with Windows 2000 and introduced additional authentication methods, management enhancements including a new MMC based administration application, support for the WebDAVprotocol, and enhancements to ASP. IIS 5.1 was shipped with Windows XP Professional, and was nearly identical to IIS 5.0 on Windows 2000 except for several limitations Microsoft introduced. IIS 5.1 supported only 10 simultaneous connections and supported only a single web site. IIS 6.0, included with Windows Server 2003 and Windows XP Professional x64 Edition, added support for IPv6 and includeda new worker process model that increased security as well as reliability. IIS 7.0 was a complete redesign and rewrite of IIS, and was shipped with Windows Vista and Windows Server 2008. IIS 7.0 included a new modular design that allowed for a reduced attack surface and increased performance. IIS 7.0 also introduced ahierarchical configuration system allowing for simpler site deploys, a new Windows Forms based management application, new command line management options and increased support for the .NET Framework. IIS 7.0 on Vista does not limit the number of allowed connections as IIS on XP did, but limits concurrent requests to 10 (Windows Vista Ultimate, Business, and Enterprise Editions) or 3 (Vista Home Premium). Additional requests are queued, which hampers performance, but they arenot rejected as with XP. The current shipping version of IIS is IIS 7.5, included in Windows 7 and Windows Server 2008 R2. IIS 7.5 improved WebDAV and FTP modules as well as command line administration in PowerShell. It also introduced Best Practices Analyzer tool and process isolation for application pools.[9] Versions IIS 1.0, Windows NT 3.51 available as a free add-on IIS 2.0, Windows NTIS 3.0, Windows NT 4.0 Service Pack 2[10] IIS 4.0, Windows NT 4.0 Option Pack IIS 5.0, Windows 2000 IIS 5.1, Windows XP Professional and Windows XP Media CenterEdition (requires retail CD) IIS 6.0, Windows Server 2003 and Windows XP Professional x64 Edition IIS 7.0, Windows Server 2008 and Windows Vista (Home Premium,Business, Enterprise and Ultimate editions) IIS 7.5, Windows Server 2008 R2 andWindows 7 (Home Premium, Professional, Enterprise and Ultimate editions)Email:[email protected] Page 6P.Ravi Theja,Asst.Professor,GIST,Nellore

Usage As of October 2011, IIS is the second most used server in the world, afterApache HTTP Server. It is used on 15.66% of servers and responds to 12.46% of total requests. Security Earlier versions of IIS were hit with a number of vulnerabilities, especially the CA-2001-13 which led to the infamous Code Red worm; however, both versions 6.0 and 7.0 currently have no reported issues with this specific vulnerability. In IIS 6.0 Microsoft opted to change the behaviour of pre-installed ISAPI handlers, many of which were culprits in the vulnerabilities of 4.0 and 5.0, thus reducing the attack surface of IIS. In addition, IIS 6.0 addeda feature called "Web Service Extensions" that prevents IIS from launching any program without explicit permission by an administrator. In the current release,IIS 7, the components are provided as modules so that only the required components have to be installed, thus further reducing the attack surface. In addition,security features are added such as Request Filtering, which rejects suspiciousURLs based on a user-defined rule set. By default IIS 5.1 and lower run websitesin-process under the SYSTEM account, a default Windows account with superuserrights. Under 6.0 all request handling processes have been brought under a Network Services account with significantly fewer privileges so that should there bea vulnerability in a feature or in custom code it won t necessarily compromisethe entire system given the sandboxed environment these worker processes run in.IIS 6.0 also contained a new kernel HTTP stack (http.sys) with a stricter HTTPrequest parser and response cache for both static and dynamic content. Accordingto Secunia, as of June 2011, IIS 7 had a total of 6 resolved vulnerabilities while IIS 6 had a total of 11 vulnerabilities out of which 1 was still unpatched.The unpatched security advisory has a severity rating of 2 out of 5. In June 2007, a Google study of 80 million domains concluded that while the IIS market share was 23% at the time, IIS servers hosted 49% of the worlds malware, same as Apache servers whose market share was 66%. The study also observed the geographicallocation of these dirty servers and suggested that the cause of this could be the use of pirated copies of Windows for which security updates were unavailable.This is no longer the case: Microsoft supplies security updates to all users. Features The architecture of IIS 7 is modular. Modules, also called extensions, can be added or removed individually so that only modules required for specific functionality have to be installed. IIS 7 includes native modules as part of thefull installation. These modules are individual features that the server uses toprocess requests and include the following: HTTP modules Used to perform tasksspecific to HTTP in the request-processing pipeline, such as responding to information and inquiries sent in client headers, returning HTTP errors, and redirecting requests. Security modules Used to perform tasks related to security in therequest-processing pipeline, such as specifying authentication schemes, performing URL authorization, and filtering requests. Content modules Used to perform tasks related to content in the request-processing pipeline, such as processing requests for static files, returning a default page when a client does not specifya resource in a request, and listing the contents of a directory.Email:[email protected] Page 7P.Ravi Theja,Asst.Professor,GIST,Nellore

Compression modules Used to perform tasks related to compression in the requestprocessing pipeline, such as compressing responses, applying Gzip compression transfer coding to responses, and performing pre-compression of static content. Caching modules Used to perform tasks related to caching in the request-processingpipeline, such as storing processed information in memory on the server and using cached content in subsequent requests for the same resource. Logging and Diagnostics modules Used to perform tasks related to logging and diagnostics in the request-processing pipeline, such as passing information and processing status toHTTP.sys for logging, reporting events, and tracking requests currently executing in worker processes.XAMPPXAMPP is a free and open source cross-platform web server solution stack package, consisting mainly of the Apache HTTP Server, MySQL database, and interpretersfor scripts written in the PHP and Perl programming languages. XAMPP s name is an acronym for: X (to be read as "cross", meaning cross-platform) Apache HTTP Server MySQL PHP PerlThe program is released under the terms of the GNU General Public License and acts as a free web server capable of serving dynamic pages. XAMPP is available forMicrosoft Windows, Linux, Solaris, and Mac OS X, and is mainly used for web development projects. This software is useful while we are creating dynamic webpages using programming languages like PHP, JSP, Servlets. Requirements and featuresXAMPP requires only one zip, tar, 7z, or exe file to be downloaded and run, andlittle or no configuration of the various components that make up the web server is required. XAMPP is regularly updated to incorporate the latest releases ofApache/MySQL/PHP and Perl. It also comes with a number of other modules including OpenSSL and phpMyAdmin. Installing XAMPP takes less time than installing eachof its components separately. Self-contained, multiple instances of XAMPP can exist on a single computer, and any given instance can be copied from one computerto another. It is offered in both a full, standard version and a smaller version. Use Officially, XAMPP s designers intended it for use only as a development tool, to allow website designers and programmers to test their work on their owncomputers without any access to the Internet. To make this as easy as possible,many important security features are disabled by default.[2] In practice, however, XAMPP is sometimes used to actually serve web pages on the World Wide Web. Aspecial tool is provided to password-protect the most important parts of the package.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 8

XAMPP also provides support for creating and manipulating databases in MySQL andSQLite among others. Once XAMPP is installed we can treat our localhost like aremote host by connecting using an FTP client. Using a program like FileZilla has many advantages when installing a content management system (CMS) like Joomla.We can also connect to localhost via FTP with our HTML editor. The default MySQL user is "root" while there is no default MySQL password.WAMPWAMPs are packages of independently-created programs installed on computers thatuse a Microsoft Windows operating system.WAMP is an acronym formed from the initials of the operating system Microsoft Windows and the principal components ofthe package: Apache, MySQL and one of PHP, Perl or Python. Apache is a web server. MySQL is an open-source database. PHP is a scripting language that can manipulate information held in a database and generate web pages dynamically each timecontent is requested by a browser. Other programs may also be included in a package, such as phpMyAdmin which provides a graphical user interface for the MySQLdatabase manager, or the alternative scripting languages Python or Perl. Equivalent packages are MAMP (for the Apple Mac) and LAMP (for the Linux operating system). This is a list of AMP (Apache, MySQL, Perl/PHP/Python) solution stacks forall computer platforms; these software bundles are used to run dynamic Web sites or servers. There are LAMPs (for Linux); WAMPs (for Windows); MAMPs (for Macintosh); SAMPs (for Solaris); and FAMPs (for FreeBSD).P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 9

The difference between wamp, lamp and xampp. All these three are used for serving php websites and acts as the local server so that we can see our working website without uploading it first. .wamp wamp stands for windows, apache, mysql, php. The best advantage of using wamp is that it is easy to setup configuration in wamp. But when i started using wamp, some times i faced problems while running php code , may be it was my coding problem but what else. Mostly people talk that wamp is not good for beginner but i say that wamp is very easy to use and it is best for both beginner and advanced users.xampp xampp stands for x-os, apache, mysql, php , perl. x-os means it can be used for any operating system. xampp is easy to use than wamp. Its cpanel is very nice and good for beginner and its start, pause and stop button work very nicelyby functionality. We can add other services to xampp also. I personally use xampp for my development.lamp lamp stands for linux, apache, mysql, php. Its functionality is same as wamp and xampp. I want to tell we one thing that the main functionality of all these three(wamp, xampp, lamp) are same i.e compile and run the php code, manage databases and other stuff. All these softwares give us ease in our development so that the complexity of handling all the services(databases handling, code manipulation) becomes easy for us.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 10

XAMPP INSTALATION PROCESSSelect English language and click okClick on Next buttonP.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 11

Select destination folder and press nextTick check boxes install Apache as Service and MySQl as service and click installP.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 12

Then installation process started wait until installing completedAfter installation get completed it will check for necessary port for Apache andMySQLP.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 13

After finshing installation it will lanch the XAMPP control panelThere check whether the Apache and MySQL in running mode or not. if not use start option to start both servers. Then press apache Adimin button it will open a explorer window there select language English.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 14

To place our documents in server check where the server is installed.Check for xampp older in that check for htdocs folder And create a new folder and rename toour own and place our application on that.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 15

Next open Explorer in the url give http://localhost/teja and press enter It willlaunch our applicationP.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 16

WAMP InstallationClick on next button and select license agreementP.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 17

Click on install buttonP.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 18

After installation Click on next button then installation process get completedIn left corner we get wamp control panel click on that.Click on local host for localhost To place our documents in server check where the server is installed.Check for wamp older in that check for www folder and create a new folder and rename to our own and place our application on that.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 19

And follow the same process as XAMPP to launch applicationThe Hypertext Transfer ProtocolAll Web communications transactions use the same protocol: the Hypertext Transfer Protocol (HTTP). The current version of HTTP is 1.1, formally defined as RFC 2616, which was approved in June 1999. RFC 2616 is available at the Web site forthe World Wide Web Consortium (W3C), http://www.w3.org. This section provides abrief introduction to HTTP. HTTP consists of two phases: the request and the response. Each HTTP communication (request or response) between a browser and a Webserver consists of two parts: a header and a body. The header contains information about the communication; the body contains the data of the communication ifthere is any.The Request PhaseThe general form of an HTTP request is as follows: 1. HTTP method Domain part ofthe URL HTTP version 2. Header fields 3. Blank line 4. Message body The following is an example of the first line of an HTTP request: GET /storefront.html HTTP/1.1 Only a few request methods are defined by HTTP, and even a smaller number of these are typically used. Table lists the most commonly used methods.P.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 20

Among the methods given in Table, GET and POST are the most frequently used. POST was originally designed for tasks such as posting a news article to a newsgroup. Its most common use now is to send form data from a browser to a server, along with a request to execute a program on the server that will process the data.Following the first line of an HTTP communication is any number of header fields, most of which are optional. The format of a header field is the field name followed by a colon and the value of the field. There are four categories of headerfields: 1. General: For general information, such as the date 2. Request: Included in request headers 3. Response: For response headers 4. Entity: Used in bothrequest and response headers One common request field is the Accept field, which specifies a preference of the browser for the MIME type of the requested document. More than one Accept field can be specified if the browser is willing to accept documents in more than one format. For example; we might have any of the following: Accept: text/plain Accept: text/html Accept: image/gif A wildcard character, the asterisk (*), can be used to specify that part of a MIME type can be anything. For example, if any kind of text is acceptable, the Accept field couldbe as follows: Accept: text/* The Host: host name request field gives the name of the host. The Host field is required for HTTP 1.1. The If-Modified-Since: daterequest field specifies that the requested file should be sent only if it has been modified since the given date. If the request has a body, the length of thatbody must be given with a Content-length field, which gives the length of the response body in bytes. POST method requests require this field because they senddata to the server. The header of a request must be followed by a blank line, which is used to separate the header from the body of the request. Requests thatuse the GET, HEAD, and DELETE methods do not have bodies. In these cases, the blank line signals the end of the request. A browser is not necessary to communicate withP.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 21

a Web server; telnet can be used instead. Consider the following command, givenat the command line of any widely used operating system: > telnet blanca.uccs.edu http This command creates a connection to the http port on the blanca.uccs.eduserver. The server responds with the following: Trying 128.198.162.60 ... Connected to blanca Escape character is ^] . The connection to the server is now complete, and HTTP commands such as the following can be given: GET /~user1/respond.html HTTP/1.1 Host: blanca.uccs.eduThe Response PhaseThe general form of an HTTP response is as follows: 1. Status line 2. Response header fields 3. Blank line 4. Response body The status line includes the HTTP version used, a three-digit status code for the response, and a short textual explanation of the status code. For example, most responses begin with the following: HTTP/1.1 200 OK The status codes begin with 1, 2, 3, 4, or 5. The general meanings of the five categories specified by these first digits are shown in TableOne of the more common status codes is one users never want to see: 404d, which means the requested file could not be found. Of course, 200 OKusers want to see, because it means that the request was handle withouthe 500 code means that the server has encountered a problem and was notfulfill the request.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 22

Not Founis whaterror. Table to

After the status line, the server sends a response header, which can contain several lines of information about the response, each in the form of a field. The only essential field of the header is Content-type The following is the responseheader for the request HTTP/1.1 200 OK Date: Sat, 25 July 2009 22:15:11 GMT Server: Apache/2.2.3 (CentOS) Last-modified: Tues, 18 May 2004 16:38:38 GMT ETag: "1b48098-16c-3dab592dc9f80" Accept-ranges: bytes Content-length: 364 Connection: close Content-type: text/html, charset=UTF-8 The response header must be followedby a blank line, as is the case for request headers. The response data followsthe blank line. In the preceding example, the response body would be the HTML file, respond.html. In HTTP versions prior to 1.1, when a server finished sendinga response to the client, the communications connection was closed. However, thedefault operation of HTTP 1.1 is that the connection is kept open for a time sothat the client can make several requests over a short span of time without needing to reestablish the communications connection with the server. This change led to significant increases in the efficiency of the Web.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 23

UNIT - IIDifference between PHP, JSP and ASP PHP is an open-source page scripting/templating system that is very similar to JSP and ASP. It defines its own scripting language, which looks and feels a lot like Perl. JSP uses Java as its scripting language. ASP uses VBScript. PHP is very popular -- it is used on over a million web sites -- but its main advantage (IMHO) seems to be that the language, being more "scripty" and Perl-like, is less intimidating to the great unwashed mass of HTML monkeys and hackers. In the long run, JSP and Java provide a more powerful system. Anything we can do with PHP, we can do with JSP; the reverse is not trueJSP is much more powerful, since it has access to all the Java libraries. PHP only has access to PHP libraries . JSP is Object-Oriented, so leads to cleaner code that s easier to debug, maintain, and improve. (PHP also allows objects, but the object model is more primitive, and most scripted pages ignore PHP objects and just use normal variables.) JSP s concept of state management and persistenceis more explicit and powerful than PHP s. With JSP, we can specify whether a variable persists for the page, the request, the session, or the application (or ifit s just local to the function). The JSP engine automatically does the right thing with cookies so we have access to the variable on later requests. With PHP,we just have "global" and "not global", we don t have automatic session management, and have to do our state thing manually with cookies or hidden variables. PHP, [www.php.net], while loosely based on C and Perl, has never faced the overwhelming complications ASP has. PHP is an object oriented language - though scripts need not necessarily be developed that way (there are still a vast number of developers preferring procedural programming, and PHP caters to both schools). PHP is both cross platform and open source, available for every major operating system and works with most web servers. It is easily extendable by anyone capableof coding in C, and comes prebundled with more functionality than ASP could everoffer. Simple capabilities, such as FTP, data compression, file uploads, XML, MD5, encryption and email are not included in ASP and require expensive, third-party packages to be installed. All of this functionality and more are built rightinto PHP. Complex functions such as dynamic images, IMAP, SNMP, dynamic flash,PDF, native access (non ODBC) to Oracle, Ovrimos, Postgre, Sybase, mySql, MSSQL,Ingres, Interbase and Informix databases, LDAP, and sockets, just to name a few, are available for free to any installation of PHP, but are not (and probably never will be) available with ASP. In addition, one could make the point that PHPis a more mature language than ASP. ASP has only been around since 1996; PHP has been around since 1994, and has a huge base of developers working on it everywaking minute of every day; bugs are usually fixed within minutes of being reported and new features are being integrated daily. P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected]

Page 24

ASP is significantly slower than PHP, for obvious reasons. Primarily, PHP runs on notoriously fast Unix and Linux servers which have for years outpaced Windowsrunning on comparable hardware. ASP does not run on any operating system other than Windows, and even then, only in IIS and PWS. I could discuss countless reasons why IIS makes a terrible web server, but that would be a discussion all on its own. PHP runs on almost any web server, on almost any platform. I have even built a web server in PHP which was capable of executing PHP scripts. ASP natively supports only Access and MSSQL, whereas PHP natively supports a huge number ofdatabases. They both support ODBC equally well. MySQL is a database that PHP closely integrates with; it is a very powerful database that rivals Oracle in speed. Like PHP, MySQL is free, and blows most other databases out of the water. Another hidden cost with ASP is the database angle; Microsoft expects we to developusing Access and when our webpage outgrows it, to switch to MSSQL, an extremelyexpensive option. While even the best software has glitches, PHP has notoriously few. The PHP development team has an outstanding reputation for fixing bugs, and in order to streamline the process they even have an online system through which new bug reports can be submitted. Most bugs are resolved within 24 hours, and I m speaking from experience here. There are a huge number of outstanding bugsin ASP which will probably never be fixed. Unless we re a major corporation, chances are that our bug report to Microsoft will likely go unanswered. And finally, cost. PHP is free. ASP isn t free. If we want to use ASP, we have to use IIS,and if we want to use IIS, we have to buy Windows. Traditionally, the cost of Windows has been high. Microsoft has been aggressively trying to reduce this factor but they re hardly going to give Windows away for free. The cost of running an ASP-based website implies a full Windows server platform; development costs are higher, software licenses are expensive and speed, security and flexibility are all sacrificed.PHP HistoryIn 1995 PHP developed by a contractor named Rasmus Lerdorf developed a Perl/CGIscript that enabled him to know how many visitors were reading his online rsum. The clamor for the PHP toolset prompted Lerdorf to continue developing the language, with perhaps the most notable early change being a new feature for convertingdata entered in an HTML form into symbolic variables, encouraging exportation into other systems. To accomplish this, he opted to continue development in C code rather than Perl. Ongoing additions to the PHP toolset culminated in November1997 with the release of PHP 2.0, or Personal Home Page/Form Interpreter (PHP/FI). As a result of PHPs rising popularity, the 2.0 release was accompanied by a number of enhancements and improvements from programmers worldwide. The new PHP release was extremely popular, and a core team of developers soon joined Lerdorf.They kept the original concept of incorporating code directly alongside HTML andrewrote the parsing engine, giving birth to PHP 3.0. By the June 1998 release of version 3.0, more than 50,000 users were using PHP to enhance their Web pages.Development continued at a hectic pace over the next two years, with hundreds of functions being added and the user count growing in leaps and bounds. At the beginning of 1999, Netcraft (http://www.netcraft.com/), an Internet research andanalysis company, reported a conservative estimate of a user base of more than 1million, making PHP one of the most popular scripting languages in the world. Its popularity surpassed even the greatest expectations of the developers, as itsoon became apparent that users intended to use PHP to power far larger applications than originally anticipated. Two core developers, Zeev Suraski and Andi Gutmans, took the initiative to completely rethink the way PHP operated, culminatin

g in a rewriting of the PHP parser, dubbed theZend scripting engine. The resultof this work was in the PHP 4 release.P.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 25

PHP 4 On May 22, 2000, roughly 18 months after the first official announcement of the new development effort, PHP 4.0 was released. Many considered the releaseof PHP 4 to be the languages official debut within the enterprise development scene, an opinion backed by the languages meteoric rise in popularity. Just a few months after the major release, Netcraft estimated that PHP had been installed onmore than 3.6 million domains. PHP 4 added several enterprise-level improvementsto the language, including the following: Improved resource handling: One of version 3.Xs primary drawbacks was scalability. This was largely because the designers underestimated how rapidly the language would be adopted for large-scale applications. The language wasnt originally intended to run enterprise-class Web sites, and continued interest in using it for such purposes caused the developers to rethink much of the languages mechanics in this regard. Object-oriented support: Version 4 incorporated a degree of object-oriented functionality, although itwas largely considered an unexceptional and even poorly conceived implementation. Nonetheless, the new features played an important role in attracting users used to working with traditional object-oriented programming (OOP) languages. Standard class and object development methodologies were made available in addition to features such as object overloading and run-time class information. A much more comprehensive OOP implementation has been made available in version 5 Native session-handling support: HTTP session handling, available to version 3.X users through the third-party package PHPLIB (http://phplib.sourceforge.net), was natively incorporated into version 4. This feature offers developers a means for tracking user activity and preferences with unparalleled efficiency and ease. Encryption: The MCrypt (http://mcrypt.sourceforge.net) library was incorporated into the default distribution, offering users both full and hash encryption using encryption algorithms including Blowfish, MD5, SHA1, and TripleDES, among others ISAPI support: ISAPI support offered users the ability to use PHP in conjunction ith Microsofts IIS Web server Native COM/DCOM support: Another bonus for Windows users is PHP 4s ability o access and instantiate COM objects. This functionality opened up a wide ange of interoperability with Windows applications. Native Java support: In another boost to PHPs interoperability, support for binding Java objects from a PHP application was made available in version 4.0. Perl Compatible Regular Expressions (PCRE) library: The Perl language has long been heralded as thereigning royalty of the string-parsing kingdom. The developers knew that powerful regular expression functionality would play a major role in the widespread acceptance of PHP and opted to simply incorporate Perls functionality rather than reproduce it, rolling the PCRE library package into PHPs default distribution (asof version 4.2.0).P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 26

PHP 5 Version 5 was yet another watershed in the evolution of the PHP language.Although previous major releases had enormous numbers of new library additions,version 5 contains improvements over existing functionality and adds several features commonly associated with mature programming language architectures: Vastlyimproved object-oriented capabilities: Improvements to PHPs objectoriented architecture is version 5s most visible feature. Version 5 includes numerous functional additions such as explicit constructors and destructors, object cloning, classabstraction, variable scope, and interfaces, and a major improvement regardinghow PHP handles object management. Try/catch exception handling: Devising customerror-handling strategies within structural programming languages is, ironically, error-prone and inconsistent. To remedy this problem, version 5 supports exception handling. Long a mainstay of error management in many languages, such as C++, C#, Python, and Java, exception handling offers an excellent means for standardizing our error-reporting logic. Improved XML and Web Services support: XML support is now based on the libxml2 library, and a new and rather promising extension for parsing and manipulating XML, known as SimpleXML, has been introduced.In addition, a SOAP extension is now available. In Chapter 20, these two extensions are introduced, along with a number of slick third-party Web Services extensions. Native support for SQLite: Always keen on choice, the developers added support for the powerful yet compact SQLite database server (http://www.sqlite.org/). SQLite offers a convenient solution for developers looking for many of the features found in some of the heavyweight database products without incurring theaccompanying administrative overhead. PHPs support for this powerful database engine PHP 6 At press time, PHP 6 was in beta and scheduled to be released by the conclusion of 2007. The decision to designate this a major release (version 6) isconsidered by many to be a curious one, in part because only one particularly significant feature has been added Unicode support. However, in the programming world, the word significant is often implied to mean sexy or marketable, so dont let the addition of Unicode support overshadow the many other important features that have been added to PHP 6. A list of highlights is found here: Unicode support: Native Unicode support has been added, making it much easier to build and maintain multilingual applications. Security improvements: A considerable number ofsecurity-minded improvements have been made that should greatly decrease the prevelance of securityrelated gaffes that to be frank arent so much a fault of thelanguage, but are due to inexperienced programmers running with scissors, so tospeak. These changes are discussed in Chapter 2. New language features and constructs: A number of new syntax features have been added, including, most notably,a 64-bit integer type, a revamped foreach looping construct for multidimensional arrays, and support for labeled breaks.Downloading PHPP.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 27

PHP comes bundled with most Linux distributions. we should download the latest stable version from the PHP Web site. To decrease download time, choose from theapproximately 100 mirrors residing in more than 50 countries, a list of which isavailable here: http://www.php.net/mirrors.php. Source: If Linux is our targetserver platform, or if we plan to compile from source for the Windows platform,choose this distribution format. Building from source on Windows isnt recommendedand isnt discussed in this book. Unless our situation warrants very special circumstances, the prebuilt Windows binary will suit our needs just fine. This distribution is compressed in Bzip2 and Gzip formats. Keep in mind that the contentsare identical; the different compression formats are just there for our convenience. Windows zip package: If we plan to use PHP in conjunction with Apache on Windows, we should download this distribution because its the focus of the later installation instructions. Windows installer: This version offers a convenient Windows installer interface for installing and configuring PHP, and support for automatically configuring the IIS, PWS, and Xitami servers. Although we could use this version in conjunction with Apache, it is not recommended. Instead, use theWindows zip package version. Further, if were interested in configuring PHP to run with IIS, see the later section titled Installing IIS and PHP on Windows. A recent collaboration between Microsoft and PHP product and services leader Zend Technologies Ltd. has resulted in a greatly improved process that is covered in thatsection.Downloading ApacheApache is packaged with all mainstream Linux distributions, the following page offered a listing of 251 mirrors located in52 global regions: http://www.apache.org/mirrors/. Navigate to this page and choose a suitable mirror by clicking theappropriate link. The resulting page will consist of a list of directories representing all projects found under the Apache Software Foundation umbrella. Enterthe httpd directory. This will take we to the page that includes links to the most recent Apache releases and various related projects and utilities. The distribution is available in two formats: Source: If our target server platform is Linux, consider downloading the source code. Although there is certainly nothing wrong with using one of the convenient binary versions, the extra time invested inlearning how to compile from source will provide we with greater configurationflexibility. If our target platform is Windows and wed like to compile from source, a separate source package intended for the Win32 platform is available for download. However, note that this chapter does not discuss the Win32 source installation process. Instead, this chapter focuses on the much more commonplace (andrecommended) binary installer. Binary: Binaries are available for a number of operating systems, among them Microsoft Windows, Sun Solaris, and OS/2. Well find these binaries under the binaries directory. So which Apache version should we download? Although Apache 2 was released more than five years ago, version 1.X remains in widespread use. In fact, it seems that the majority of shared-server ISPs have yet to migrate to version 2.X. The reluctance to upgrade doesnt have anything to do with issues regarding version 2.X, but rather is a testament to the amazing stability and power of version 1.X. For standard use, the external differences between the two versions are practically undetectable; therefore, considergoing with Apache 2 to take advantage of its enhanced stability. In fact, if weplan to run Apache on Windows for either development or deployment purposes, itis recommended that we choose version 2 because it is a complete rewrite of theprevious Windows distribution and is significantly more stable than its predecessor.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 28

Installing Apache and PHP on WindowsThe installation process follows: 1. Start the Apache installer by double-clicking the apache_X.X.XX-win32-x86-no_ssl.msi icon. The Xs in this file name represent the latest stable version numbers of the distributions we downloaded in the previous section. 2. The installation process begins with a welcome screen. Takea moment to read the screen and then click Next. 3. The license agreement is displayed next. Carefully read through the license. Assuming that we agree with thelicense stipulations, click Next. 4. A screen containing various items pertinent to the Apache server is displayed next. Take a moment to read through this information and then click Next. 5. We will be prompted for various items pertinentto the servers operation, including the network domain, the server name, and theadministrators e-mail address. If we know this information, fill it in now; otherwise, just enter localhost for the first two items and put in any e-mail address for the last. We can always change this information later in the httpd.conf file. Well also be prompted as to whether Apache should run as a service for all users or only for the current user. If we want Apache to automatically start withthe operating system, which is recommended, then choose to install Apache as a service for all users. When were finished, click Next. 6. We are prompted for a Setup Type: Typical or Custom. Unless there is a specific reason we dont want the Apache documentation installed, choose Typicaland click Next. Otherwise, choose Custom, click Next, and on the next screen, uncheck the Apache Documentation option. 7. Were prompted for the Destination folder. By default, this is C:\Program Files\Apache Group. Consider changing this to C:\, which will create an installation directory C:\apache2\. Regardless of what we choose, keep in mind that the latter is used here for the sake of convention. Click Next. 8. Click Install to complete the installation. Thats it for Apache. Next well install PHP. 9. Unzip thePHP package, placing the contents into C:\php6\. Were free to choose any installation directory we please, but avoid choosing a path that contains spaces. Regardless, the installation directory C:\php6\ will be used throughout this chapterfor consistency. 10. Navigate to C:\apache2\conf and open httpd.conf for editing. 11. Add the following three lines to the httpd.conf file. Consider adding themdirectly below the block of LoadModule entries located in the bottom of the Global Environment section: LoadModule php6_module c:/php6/php6apache2.dll AddTypeapplication/x-httpd-php .php PHPIniDir "c:\php6"P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 29

Because at the time of publication PHP 6 wasnt yet official, we should use the latest stable version of PHP 5 if were planning on running any production applications. To do so, well need to make some minor changes to the previous lines, as follows:LoadModule php5_module c:/php5/php5apache2.dll AddType application/x-httpd-php .php PHPIniDir "c:\php5" 12. Rename the php.ini-dist file to php.ini and save itto the C:\php6 directory. The php.ini file contains hundreds of directives thatare responsible for tweaking PHPs behavior. The later section Configuring PHP examines php.inis purpose and contents in detail. Note that we can place this configuration file anywhere we please, but if we choose a nondefault location, we also need to configure PHP using the -with-config-file-path option. Also note that there is another default configuration file at our disposal, php.ini-recommended. This file sets various nonstandard settings and is intended to better secure andoptimize our installation, although this configuration may not be fully compatible with some of the legacy applications. Consider using this file in lieu of php.ini-dist. 13. Locate Apache in the list and make sure that it is started. If itis not started, highlight the label and click Start the Service, located to theleft of the label. If it is started, highlight the label and click Restart theService, so that the changes made to the httpd.conf file take effect. Next, right-click Apache and choose Properties. Ensure that the startup type is set to Automatic.Installing Apache and PHP on LinuxThe installationprocess follows: 1. Unzip and untar Apache and PHP. In the following code, the X represents the latest stable version numbers of the distributions we downloaded in the previous section: %>gunzip httpd-2_X_XX.tar.gz %>tar xvfhttpd-2_X_XX.tar %>gunzip php-XX.tar.gz %>tar xvf php-XX.tar2. Configure and build Apache. At a minimum, well want to pass the option --enable-so, which tells Apache to enable the ability to load shared modules: %>cd httpd-2_X_XX %>./configure --enable-so [other options] %>make 3. Install Apache: %>make install 4. Configure, build, and install PHP (see the section Configuring PHPat Build Time on Linux for information regarding modifying installation defaultsand incorporating third-party extensions into PHP). In the following steps, APACHE_INSTALL_DIR is a placeholder for the path to Apaches installed location, forinstance /usr/local/apache2:P.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 30

%>cd ../php-X_XX %>./configure --with-apxs2=APACHE_INSTALL_DIR/bin/apxs [other options] %>make %>make install 5. PHP comes bundled with a configuration file that controls many aspects of PHPs behavior. This file is known as php.ini, but it was originally named php.ini-dist. We need to copy this file to its appropriate location and rename it php.ini. The later section Configuring PHP examines php.inispurpose and contents in detail. Note that we can place this configuration file anywhere we please, but if we choose a non default location, we also need to configure PHP using the --with-config-file-path option. Also note that there is another default configuration file at our disposal, php.ini-recommended. This file sets various nonstandard settings and is intended to better secure and optimize our installation, although this configuration may not be fully compatible with some of the legacy applications. Consider using this file in lieu of php.ini-dist.To use this file, execute the following command: %>cp php.ini-recommended /usr/local/lib/php.ini 6. Open Apaches configuration file, known as httpd.conf, and verify that the followinglines exist. (The httpd.conf file is located at APACHE_INSTALL_DIR/conf/httpd.conf.) If they dont exist, go ahead and add them. Consider adding each alongside the other LoadModule and AddType entries, respectively: LoadModule php6_module modules/libphp6.so AddType application/x-httpd-php .php Because at the time of publication PHP 6 wasnt yet official, we should use the lateststable version of PHP 5 if were planning on running any production applications.In the case of PHP 5, the lines will look like this: LoadModule php5_module modules/libphp5.so AddType application/x-httpd-php .php Believe it or not, thats it.Restart the Apache server with the following command: %>/usr/local/apache2/bin/apachectl restartConfiguring PHP1.Enable Short Open TagsSearch for the line that reads: short_open_tag = Off If short_open_tag is set to"off", tags like " Abstract Abstract methods are special in that they are declared only within a parent class but are implemented in child classes. Only classesdeclared as abstract can contain abstract methods. Abstract methods are declaredlike this: abstract function methodName() Ex: abstract class Employee { abstract function hire(); abstract function fire(); abstract function promote(); abstract demote(); } Final Marking a method as final prevents it from being overriddenby a subclass. A finalized method is declared like this: class Employee { ... final function getName() { ... } }Type Hinting Type hinting ensures that the object being passed to the method isindeed a member of the expected class. For example, it makes sense that only objects of class Employee should be passed to the takeLunchbreak() method. privatefunction takeLunchbreak(Employee $employee) { ... }P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 70

Constructors A constructor is defined as a block of code that automatically executes at the time of object instantiation. OOP constructors offer a number of advantages: Constructors can accept parameters, which are assigned to specific object fields at creation time. Constructors can call class methods or other functions. Class constructors can call on other constructors, including those from theclass parent. PHP recognizes constructors by the name __construct. The general syntax for constructor declaration follows: function __construct([argument1, argument2, ..., argumentN]) { // Class initialization code } This results inthe following: Title: Beginning Python Number copies available: 5P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 71

Invoking Parent Constructors PHP does not automatically call the parent constructor; you must call it explicitly using the parent keyword. An example follows: This results in the following: Employee constructor called! Manager constructor called! Invoking Unrelated Constructors You can invoke class constructors that dont have any relation to the instantiated object simply by prefacing __constructor with the class name, like so: classname::__construct() Ex: Employee::__construct() Destructors Objects were automatically destroyed upon script completion Destructors are created like any othermethod but must be titled __destruct (). An example follows: Heres the result: Book class instance created. Book class instance destroyed. When the script is complete, PHP will destroy any objects that reside in memory. Therefore, if the instantiated class andany information created as a result of the instantiation reside in memory, yourenot required to explicitly declare a destructor. Static Class Members Fields are declared as static, any changes made to its value are reflected across all instantiated objects. The results areas follows: 1 2P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 73

The instanceof Keyword The instanceof keyword was introduced with PHP 5. With ityou can determine whether an object is an instance of a class, is a subclass ofa class, or implements a particular interface, and do something accordingly. For example, suppose you want to learn whether an object called manager is derivedfrom the class Employee: $manager = new Employee(); ... if ($manager instanceofEmployee) echo "Yes";Class Inheritance class inheritance is accomplished by using the extends keyword. Ex: first creating an Employee class and then creating an Executive class thatinherits from Employee. This returns the following: My name is Richard. I m selling company assets to finance my yacht! Inheritance and Constructors If a parent class offers a constructor, it does execute when the child class is instantiated, provided that the child class does not alsohave a constructor. function __construct($name) { $this->setName($name); }P.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 74

Then you instantiate the CEO class and retrieve the name member: $ceo = new CEO("Dennis"); echo $ceo->getName();It will yield the following: My name is Dennis If the child class also has a constructor, that constructor will execute when the child class is instantiated, regardless of whether the parent class also has aconstructor. function __construct() { echo "CEO object created!"; } Then you instantiate the CEO class: $ceo = new CEO("Dennis"); echo $ceo->getName(); This time it will yield the following output because the CEO constructor overrides the Employee constructor: CEO object created! My name is When it comes time to retrieve the name member, you find that its blank because the setName() method, which executes in the Employee constructor, never fires. youre quite likely going to want those parent constructors to also fire function __construct($name) { parent::__construct($name); echo "

CEO object created!"; } Again instantiating the CEO class and executing getName() in the same fashion as before, this time youll see a different outcome: CEO object created! My name is DennisInterfaces An interface defines a general specification for implementing a particular service, declaring the required functions and constants without specifyingexactly how it must be implemented. Implementation details arent provided because different entities might need to implement the published method definitions indifferent ways.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 75

interface IinterfaceName { CONST 1; ... CONST N; function methodName1(); ... function methodNameN(); } The contract is completed when a class implements the interface via the implements keyword. All methods must be implemented, or the implementing class must be declared abstract (a concept introduced in the next section); otherwise, an error similar to the following will occur: class Class_Name implements interfaceName { function methodName1() { // methodName1() implementation } function methodNameN() { // methodName1() implementation } } Implementing aSingle Interface interface IPillage { function emptyBankAccount(); function burnDocuments(); } This interface is then implemented for use by the Executive class: class Executive extends Employee implements IPillage { private $totalStockOptions; function emptyBankAccount() { echo "Call CFO and ask to transfer funds to Swiss bank account."; } function burnDocuments() { echo "Torch the office suite."; } }P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 76

Implementing Multiple Interfaces Abstract Classes An abstract class is a class that really isnt supposed to ever be instantiated but instead serves as a base class to be inherited by other classes. A class is declared abstract by prefacing the definition with the word abstract, like so: abstract class Class_Name { // insert attribute definitions here // insert method definitions here } Attempting to instantiate an abstract class results in the following error message Abstract classes ensure conformity because any classes derived from them must implement all abstract methods derived within the class. Attempting to forgo implementation of any abstract method defined in the class results in a fatal error.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 77

UNIT-V CookiesCookies are files that get written to a temporary file on a users computer by a web application. Cookies store information that can be read by the online application, thus authenticating a user as unique. By allowing a web application to identify whether a user is unique, the application can then perform login scripts and other functionality. The problem with cookies is that because they are storedon a users computer, they have developed a bad rap as being highly insecure. Andbecause of possible insecurities with cookies, users have begun to turn them off in their browser security settings; in fact, users often do not accept cookies. Cookies themselves are not bad or insecure if used correctly by a developer. However, since users have the ability to turn them off (and since the actual cookie must be stored on the users computer), most good developers have migrated their code to sessions.Setting CookiesTo be able to use cookies and store values in them, we must first set a cookie on a users computer. By using the different parameters, we can customize the way the cookie works for us. The way to set a cookie is by using the function setcookie(), which has the following prototype: bool setcookie ( string name [, stringvalue [, int expire [, string path [, string domain [, bool secure]]]]] )setcookie() ParametersExample : Reading CookiesThe PHP $_COOKIE variable is used to retrieve a cookie value. The following script allows we to determine if we are properly logged inusing a function that returns a true value upon proper validation of login.Example:

Deleting CookiesWe should note that cookies will disappear by themselves if we have set them upto do so. Cookies that have not been assigned a time to die will simply be removed when the browser window closes. Sometimes, however, a user will want to be able to clear the cookies on a site. Such functionality typically goes by the nameof logout and is a staple of a well-programmed user interface. Another example: When deleting a cookie we should assure that the expirationdate is in the past. Delete example:

HTTP HeadersHTTP headers have powerful sets of functionality. The most important aspect to remember about headers is that they can be called only before any output has beenwritten to the web page. If we attempt to call a header after output has been sent to the page, we will generate an error; hence, our script will fail on us. We can use them to control everything, including setting the current page location, finding out what file format is being displayed, and managing all aspects ofthe browser cache. The header () functions prototype is as follows: void header (string string [, bool replace [, int http_response_code]] )Redirecting to a Different LocationOne of the more common uses for HTTP headers is redirecting a script. By using headers inside processing scripts, we can force the browser to return to any pagewe want. We prefer to use headers to control exception handling within processscripts. The Ex Code: P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 81

Common File Format Content TypesForcing File Save As DownloadsWe can use the header () function to force a Save As dialog box to appear for the user to accept a download. Web browsers can output many different file types directly onto the screen, the default when we use headers to output a wide variety of file types is to make them automatically appear on the screen. The Code By making content-disposition an attachment value, the browser will force a download rather than display the file inline. By using this, we can force the download to appear with any particular filename we prefer and also with pretty much any file extension. By using content-type, we force the browser to outputa file of the requested type.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 82

SessionsCookies are getting less and less trusted as a solution, sessions created. Sessions are handled much like cookies but with a major difference. While cookies aredeclared as global members of the site, a session state must be enabled to usethem effectively. While in the session state, sessions can be accessed just likecookies, in a global sense, and can be manipulated, added to, or removed with relative ease. Sessions uses: When we are working with an application, we open it, do some changes and then we close it. This is much like a Session. The computer knows who we are. It knows when we start the application and when we end. Buton the internet there is one problem: the web server does not know who we are and what we do because the HTTP address doesn t maintain state. A PHP session solves this problem by allowing us to store user information on the server for lateruse (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If we need a permanent storage we 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 Creating Sessions: We create a session state using the session_start() function and then use andaccess these session values using the $_SESSION superglobal. Using the superglobal, we can then add to, remove, or modify the session values. We can use the sessions anywhere the session state is enabled, which means the session_start() function needs to be called at the beginning of every page where we want session access. When we have finished with the sessions,we can simply use the unset() function on the session values and finish off the session state using the session_destroy() function. The prototypes for these session-related functions are as follows: bool session_start ( void ) bool session_destroy ( void ) The Code: Storing Simple Data Types in Sessions Sessions handle simple data types, and they handle them well. Like any PHP variable, however, the data type of a current session is based upon what waslast assigned to it and can be changed quite easily. The following example passes three values by session: an integer, a string, and a floating-point value. Sessions that have been set can be called and accessed from anywhere within the scope of the session state. The Code Storing Complex Data Types in SessionsOne of the major improvements to PHP 5 is the ability to store complex data types within a session .Using this technique,we can easily store large quantities ofdata within a single object (such as a shopping cart object), use the functionality within the session for these purposes, and then pass the data along to other pages. The Code Authenticating Our UsersWe need to create a way of authenticating our users so that we know we have a valid user accessing the site. We can handle authentication in a variety of ways,but the two most common methods for securing a file or set of files is through HTTPbased authentication and through cookie authentication.Cookie AuthenticationManaging user authentication through cookies or sessions is a little harder thanusing HTTPbased Authentication. The nice features of cookie-based authentication are being able to set our own error messages, being able to control what happens upon login, and being allowed to make our login form blend seamlessly into our application. By comparing Cookies vs Sessions, the advantages of sessions being kept on the server side and working on any platform and by using sessions we will know that our script should work on pretty much any platform and will be a reliable, secure way of handling authentication. The Code Sample Sorry, we have entered an incorrect login. Congratulations,we are logged in! Username: P.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 86


Password:
If the script detects that we have submitted a username and password, it will then check for a valid match and set proper sessions upon the match. If the system detects that the sessions are already in place and are proper (as handled by the checkcookies() function), it does not display the login form and instead displays a means to log out. The logout algorithm is handled in mostly the same way. If the script detects a logout fieldis in place, it then goes through the algorithm to kill off the session variables.Using Environment and Configuration VariablesPHP provides a means to use and verify the configuration settings and environment variables relative to the server space the script is occupying. By having access to environment variables, we can customize our scripts to work optimally on the platform that is available. By having access to the configuration variables of PHP, we can customize the PHP environment our script is working in for specialoccurrences. A common use of the environment variables in PHP is for dynamic imaging. While Windows systems commonly store their fonts in one folder, Linux-based systems keep theirs in another. By using PHPs environment variables to determine the current operating system, we can make our code slightly more portable. Using configuration variables can also come in quite handy, particularly with fileupload scripts. The base PHP installation leaves only enough processing time toupload files that are generally 2MB or smaller in size. By manipulating the PHPconfiguration files temporarily, we can increase the limit enough to allow a script to process much larger files.Reading Environment and Configuration VariablesThe $_ENV superglobal is PHPs method for reading a systems environment variables and has an argument set that is based upon the current environment that is available to it. Because of its relative flexibility, there is no real set argument list, as it is generated based on the current server environment. We can use the phpinfo() function to determine the current environment variables, and we can retrieve them using the getenv() function, which needs to be supplied a valid environment variable name.P.Ravi Theja,Asst.Professor,GIST,Nellore Email:[email protected] Page 87

Reading configuration variables, takes place through two functions, ini_get() and ini_get_all(). The function ini_get() will retrieve the value of a specified configuration variable, and the function ini_get_all() will retrieve an array filled with the entire selection of configuration variables that are available. TheCode Setting Environment and Configuration VariablesTo set Environment Variables While working with environment variables, we need to assign a new value to the $_ENV superglobal to process a temporary change. Thechange will be in effect for the scripts duration. The same applies for configuration variables but with a different approach. To set a configuration variable,we have to use the PHP function ini_set(), which will allow us to set a configuration variable for the scripts duration. Once the script finishes executing, theconfiguration variable will return to its original state. The prototype for ini_set() is as follows: string ini_set ( string varname, string newvalue ) The code

P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 88

Date and Time Functionsdate() :Returns a string formatted according to the given format string using the giveninteger timestamp or the current time if no timestamp is given. In other words,timestamp is optional and defaults to the value of time(). Syn: string date ( string $format [, int $timestamp] )P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 89

formatcharacter Day d D j l (lowercase

L ) N S w z Week W Month F m M n t Year L

Description --Day of the month, 2 digits with leading zeros A textual representation of a day, three letters Day of the month without leading zeros A full textual representation of the day of the week ISO-8601 numeric representation of theday of the week (added in PHP 5.1.0) English ordinal suffix for the day of the month, 2 characters Numeric representation of the day of the week The day of theyear (starting from 0) --ISO-8601 week number of year, weeks starting on Monday(added in PHP 4.1.0) --A full textual representation of a month, such as Januaryor March Numeric representation of a month, with leading zeros A short textualrepresentation of a month, three letters Numeric representation of a month, without leading zeros Number of days in the given month --Whether it s a leap year ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) A full numeric representation of a year, 4 digits A two digit representation of a year --Lowercase Ante meridiem and Post meridiem Uppercase Ante meridiem and Post meridiem Swatch Internet timeExample returned values --01 to 31 Mon through Sun 1 to 31 Sunday through Saturday 1 (for Monday) through 7 (for Sunday) st, nd, rd or th. Works well with j 0 (for Sunday) through 6 (for Saturday) 0 through 365 --Example: 42 (the 42nd weekin the year) --January through December 01 through 12 Jan through Dec 1 through12 28 through 31 --1 if it is a leap year, 0 otherwise.oExamples: 1999 or 2003Y y Time a A BExamples: 1999 or 2003 Examples: 99 or 03 --am or pm AM or PM 000 through 999Page 90P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected]

formatcharacter g G h H i s u Timezone e I (capital i) O P T Z Full Date/Time c r UDescription 12-hour format of an hour without leading zeros 24-hour format of anhour without leading zeros 12-hour format of an hour with leading zeros 24-hourformat of an hour with leading zeros Minutes with leading zeros Seconds, with leading zeros Milliseconds (added in PHP 5.2.2) --Timezone identifier (added in PHP 5.1.0) Whether or not the date is in daylight saving time Difference to Greenwich time (GMT) in hours Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) Timezone abbreviation Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. --ISO 8601 date (added in PHP 5) RFC 2822 formatted date Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)Example returned values 1 through 12 0 through 23 01 through 12 00 through 23 00to 59 00 through 59 Example: 54321 --Examples: UTC, GMT, Atlantic/Azores 1 if Daylight Saving Time, 0 otherwise. Example: +0200 Example: +02:00 Examples: EST,MDT ... -43200 through 50400 --2004-02-12T15:19:21+00:00 Example: Thu, 21 Dec 2000 16:01:07 +0200 See also time() date("F j,Y, g:i a"); date("m.d.y"); date("j, n, Y"); date("Ymd"); date( h-i-s, j-m-y, itis w Day z ); 1618 6 Fripm01 date( \i\t \i\s \t\h\e jS \d\a\y. ); date("D M jG:i:s T Y"); date( H:m:s \m \i\s\ \m\o\n\t\h ); date("H:i:s"); // // // // // //// // // March 10, 2012, 5:16 pm 03.10.01 10, 3, 2012 20120310 05-16-17, 10-03It is the 10th day. Sat Mar 10 15:16:08 MST 2012 17:03:17 m is month 17:16:17P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 91

mktime() :This method mainly used to work with specific dateReturns the Unix timestamp corresponding to the arguments given. This timestampis a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time. Output: Today is 28 Mar 2012. The first Tuesday of next month is 03 Apr 2012. For all months: Getting the Day andWeek of the Year Obtaining the day of the year is fairly simple; you need use only a lowercase z in the first argument to the date() function. The Code Output: 01 Jan 2005: Day 0 30 Jun 2005: Day 180 31 Dec 2005: Day 364P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 94

Determining Whether a Given Year Is a Leap YearThe date() function employs another one-letter argument; it uses L to determineif a given year is a le year. When this is used, date() returns 1 if the year inquestion is a leap year and 0 if it is not. Rather than make repeated calls todate() and strtotime(), you can wrap this in a simple function that takes the year to be tested as an argument, as shown in the following example. The Code Output: 2010 is not a leap year. 2011 is not a leap year. 2012 is a leap year. 2013 is not a leap year. 2014 is not a leap year. 2015is not a leap year. 2016 is a leap year. 2017 is not a leap year. 2018 is not aleap year. 2019 is not a leap year. 2020 is a leap year.chechdate():Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined Syn: bool checkdate ( int $month, int$day, int $year )P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 95

checkdate() example The above example will output: bool(true) bool(false)date_sunrise() : returns the sunrise time for a given day (specified as a timestamp) and location.mixed date_sunrise ( int $timestamp [, int $format [, float $latitude [, float $longitude [, float $zenith [, float $gmt_offset]]]]] )ParameterstimestampThe timestamp of the day from which the sunrise time is taken.formatconstant SUNFUNCS_RET_STRING SUNFUNCS_RET_DOUBLE SUNFUNCS_RET_TIMESTAMPlatitudedescription returns the result as string returns the result as float returns theresult as integer (timestamp)example 16:46 16.78243132 1095034606Defaults to North, pass in a negative value for South. See also: date.default_latitudelongitudeDefaults to East, pass in a negative value for West. See also: date.default_longitudezenithDefault: date.sunrise_zenithgmtoffsetSpecified in hours The above example will output something similar to: Mon Dec 20 2004, sunrisetime : 08:54getdate() :array getdate ( [int $timestamp] ) Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given. Example: The above example will output something similar to: Array ( [seconds] => 40 [minutes] => 58 [hours]=> 21 [mday] => 17 [wday] => 2 [mon] => 6 [year] => 2003 [yday] => 167 [weekday] => Tuesday [month] => June [0] => 1055901520 ) Time(): int time ( void ) Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). Example: The above examplewill output something similar to: Now: 2012-03-30 Next Week: 2012-04-06 Next Week: 2012-04-06 Determining the Number of Days in the Current Month To determinethe number of days in the current month, use the date() functions t parameter. Consider the following code: printf("There are %d days in %s.", date("t"), date("F")); If this is executed in April, the following result will be output: There are 30 days in AprilDetermining the Number of Days in Any Given Month$lastday = mktime(0, 0, 0, 3, 0, 2007); printf("There are %d days in February 2007.", date("t",$lastday)); Executing this snippet produces the following output:There are 28 days in February 2007.. Calculating the Date X Days from the Present Date Its often useful to determine the precise date of some specific number ofdays into the future or past. Using the strtotime() function and GNU date syntax, such requests are trivial. Suppose you want to know what the date will be 45days into the future, based on todays date of February 25, 2007: $futuredate = strtotime("45 days"); echo date("F d, Y", $futuredate); This returns the following: April 12, 2007 By prepending a negative sign, you can determine the date 45 days into the past (today being February 25, 2007): $pastdate = strtotime("-45 days"); echo date("F d, Y", $pastdate); This returns the following: January 11, 2007P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 98

UNIT-VICreating and Using FormsFormsWhen dealing with forms, the most important aspect to remember is that we are limited to a certain variety of fields that can be applied to a form. The fields that have been created are non-negotiable and work in only the way they were created to work. HTML Form ElementsGET vs. POST When dealing with forms, we must specify the way that the information entered into the form is transmitted to its destination (method=""). The twoways available to a web developer are GET and POST. When sending data using theGET method, all fields are appended to the Uniform Resource Locator (URL) of thebrowser and sent along with the address as data. Sending data using the GET method means that fields are generally capped at 150 characters, which is certainlynot the most effective means of passing information. It is also not a secure means of passing data, because many people know how to send information to a script using an address bar. With the POST method, values are sent as standard input.Sending data using the POST method is quite a bit more secure (because the method cannot be altered by appending information to the address bar) and can contain as much information as we choose to send. Therefore, whenever possible, use the POST method for sending information and then adjust our script to handle it. PHP 5s current methods for dealing with GET and POST variables are the $_GET and $_POST superglobals, respectively. By using these two superglobals, we can designate exactly where the information should be coming from and subsequently handlethe data in the way we want.P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 99

The $_GET VariableThe $_GET variable is an array of variable names and values sent by the HTTP GETmethod. The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (itwill be displayed in the browser s address bar) and it has limits on the amountof information to send (max. 150 characters). Example Name: Age: When the user clicks the "Submit"button, the URL sent could look something like this: http://localhost/teja/welcome.php?name=raviteja&age=25 The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array):Welcome .
We are years old!Note: When using the $_GET variable all variable names and values are displayedin the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, itis possible to bookmark the page. This can be useful in some cases. Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed150 characters.The $_POST VariableThe $_POST variable is an array of variable names and values sent by the HTTP POST method. The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Example Enter our name: Enter our age: When the user clicks the "Submit" button, the URL will not contain any form data,and will look something like this: http://localhost/teja/welcome.php The "welcome.php" file can now use the $_POST variable to catch the form data (notice thatthe names of the form fields will automatically be the ID keys in the $_POST array): Welcome .
We are years old!P.Ravi Theja,Asst.Professor,GIST,NelloreEmail:[email protected] 100

Why use $_POST? Variables sent with HTTP POST are not shown in the URL Variables