Você está na página 1de 122

WEB TECHNOLOGIES

MATERIAL

By

P.Ravi Teja
Asst .Professor, C.S.E.Dept,
G.I.S.T-S.P.S.R.Nellore
Ph: 9030104017

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com

Page 1

UNIT-I
Introduction To Web Server
A web server is the combination of computer and the program installed on it. Web server 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 large number of programs installed on a computer connected to Internet or intranet for downloading
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 of server 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 is popular 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.

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com

Page 2

Web Server Operation


Clients 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 server that 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.
All the 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 to a Web server, sends
information requests and possibly data to the server, receives information from the server, and closes the
connection.
The primary task of a Web server is to monitor a communications port on its host machine, accept HTTP
commands 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 Characteristics


The file structure of a Web server has two separate directories. The root of one of 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
server root. 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 access the 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 is named 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 area
network.

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com

Page 3

Many servers can support more than one site on a computer, potentially reducing the cost of each site and
making their maintenance more convenient. Such secondary hosts are called virtual hosts.
Some servers can serve documents that are in the 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 Server


The 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
Communications Corporation 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 and maintained by an open community of developers under the auspices of the
Apache Software 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.
When Apache begins execution, it reads its configuration information from a file and sets 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. For historical 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 to httpd.conf, which is the file that contains the list of directives
that specify the 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 known as a rewrite engine,
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com

Page 4

implemented under mod_rewrite), custom log files (mod_log_config), and filtering support (mod_include
and mod_ext_filter).
Popular compression methods on Apache include the external extension module, mod_gzip, implemented
to help with reduction of the size (weight) of web pages served over HTTP. ModSecurity is an open
source 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 Apache is 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. Where compromises in performance need to be made, the design of Apache is to reduce
latency and increase throughput, relative to simply handling more requests, thus ensuring consistent and
reliable processing 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 processes and several threads per process.
While this architecture works faster than the previous multi-process based topology (because threads
have a lower overhead than processes), it does not match the performances of the event-based
architecture provided 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 Services


Internet 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 an integral part of Windows Server family of products, as well as certain editions
of Windows XP, Windows Vista and Windows 7. IIS is not turned on by default when Windows is
installed.

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com

Page 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 to set
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 as a free add-on, a set of web-based services for Windows
NT 3.51. However, IIS 2.0 was included with Windows NT 4.0. IIS 3.0, which was included with Service
Pack 3 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 WebDAV protocol, 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 included a 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 a hierarchical 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 are not 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 NT 4.0
IIS 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 Center Edition (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)

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com

Page 6

IIS 7.5, Windows Server 2008 R2 and Windows 7 (Home Premium, Professional, Enterprise
and Ultimate editions)

Usage
As of October 2011, IIS is the second most used server in the world, after Apache 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 added a 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 suspicious URLs based on a user-defined rule set.
By default IIS 5.1 and lower run websites in-process under the SYSTEM account, a default Windows
account with 'superuser' rights. Under 6.0 all request handling processes have been brought under a
Network Services account with significantly fewer privileges so that should there be a vulnerability in a
feature or in custom code it won't necessarily compromise the 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 HTTP request parser and response cache for both static and dynamic content.
According to 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 geographical location 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 the full installation. These modules are individual features that the server uses
to process requests and include the following:

HTTP modules Used to perform tasks specific 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 the request-processing
pipeline, such as specifying authentication schemes, performing URL authorization, and
filtering requests.

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com

Page 7

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
specify a resource in a request, and listing the contents of a directory.
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-processing
pipeline, 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 to
HTTP.sys for logging, reporting events, and tracking requests currently executing in worker
processes.

XAMPP
XAMPP is a free and open source cross-platform web server solution stack package, consisting mainly
of the Apache HTTP Server, MySQL database, and interpreters for 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
Perl

The 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 for Microsoft 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 features
XAMPP requires only one zip, tar, 7z, or exe file to be downloaded and run, and little or no configuration
of the various components that make up the web server is required. XAMPP is regularly updated to
incorporate the latest releases of Apache/MySQL/PHP and Perl. It also comes with a number of other
modules including OpenSSL and phpMyAdmin.
Installing XAMPP takes less time than installing each of its components separately. Self-contained,
multiple instances of XAMPP can exist on a single computer, and any given instance can be copied from
one computer to another.
It 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 own computers 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. A special tool is
provided to password-protect the most important parts of the package.
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com

Page 8

XAMPP also provides support for creating and manipulating databases in MySQL and SQLite among
others.
Once XAMPP is installed we can treat our localhost like a remote 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.

WAMP
WAMPs are packages of independently-created programs installed on computers that use a Microsoft
Windows operating system.WAMP is an acronym formed from the initials of the operating system
Microsoft Windows and the principal components of the 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 time content 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 MySQL database 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 for all 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,Nellore

Email:raviteja.pannem@gmail.com

Page 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 nicely by 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,Nellore

Email:raviteja.pannem@gmail.com Page 10

XAMPP INSTALATION PROCESS

Select English language and click ok

Click on Next button


P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 11

Select destination folder and press next

Tick check boxes install Apache as Service and MySQl as service and click install

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 12

Then installation process started wait until installing completed

After installation get completed it will check for necessary port for Apache and MySQL

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 13

After finshing installation it will lanch the XAMPP control panel

There 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,Nellore

Email:raviteja.pannem@gmail.com Page 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 to our own and place our application on that.

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 15

Next open Explorer in the url give http://localhost/teja and press enter
It will launch our application

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 16

WAMP Installation

Click on next button and select license agreement

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 17

Click on install button

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 18

After installation Click on next button then installation process get completed
In 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,Nellore

Email:raviteja.pannem@gmail.com Page 19

And follow the same process as XAMPP to launch application

The Hypertext Transfer Protocol


All 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 for the World Wide Web Consortium (W3C), http://www.w3.org.
This section provides a brief introduction to HTTP. HTTP consists of two phases: the request and the
response. Each HTTP communication (request or response) between a browser and a Web server consists
of two parts: a header and a body. The header contains information about the communication; the body
contains the data of the communication if there is any.

The Request Phase


The general form of an HTTP request is as follows:
1. HTTP method Domain part of the 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:raviteja.pannem@gmail.com 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 header fields:
1. General: For general information, such as the date
2. Request: Included in request headers
3. Response: For response headers
4. Entity: Used in both request 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 could be 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: date request 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 that body 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 send data
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 that use 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 with
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 21

a Web server; telnet can be used instead. Consider the following command, given at 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.edu server. 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.edu

The Response Phase


The 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 Table

One of the more common status codes is one users never want to see: 404 Not Found, which means the
requested file could not be found. Of course, 200 OK is what users want to see, because it means that the
request was handle without error. The 500 code means that the server has encountered a problem and was
not able to fulfill the request.

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 22

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 response header 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 followed by a blank line, as is the case for request headers. The response
data follows the 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 sending a response
to the client, the communications connection was closed. However, the default operation of HTTP 1.1 is
that the connection is kept open for a time so that 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,Nellore

Email:raviteja.pannem@gmail.com Page 23

UNIT - II
Difference 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 true JSP 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 persistence is 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 if it'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 capable of coding in C, and comes prebundled with more functionality than ASP could ever offer.

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 right into 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
PHP is 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 every waking 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,Nellore

Email:raviteja.pannem@gmail.com 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 Windows running 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 it's 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 of
databases. 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 develop using Access and when our webpage outgrows it, to switch to MSSQL, an
extremely expensive 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 bugs in 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 History
In 1995 PHP developed by a contractor named Rasmus Lerdorf developed a Perl/CGI script 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 converting data 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 November 1997 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 and rewrote 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 and analysis company, reported a
conservative estimate of a user base of more than 1 million, making PHP one of the most popular
scripting languages in the world. Its popularity surpassed even the greatest expectations of the
developers, as it soon 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, culminating in a rewriting of the PHP parser, dubbed theZend
scripting engine. The result of this work was in the PHP 4 release.
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com 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 release of 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 on more than 3.6
million domains.
PHP 4 added several enterprise-level improvements to 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 it
was 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
the reigning 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 (as of version 4.2.0).

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 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:
Vastly improved 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, class abstraction, variable scope, and interfaces, and a major
improvement regarding how PHP handles object management.
Try/catch exception handling: Devising custom error-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 the accompanying 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) is considered 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 of security-minded improvements have been made
that should greatly decrease the prevelance of securityrelated gaffes that to be frank arent so much a fault
of the language, but are due to inexperienced programmers running with scissors, so to speak. 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 PHP
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com 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 the approximately 100 mirrors residing in more
than 50 countries, a list of which is available here: http://www.php.net/mirrors.php.
Source: If Linux is our target server platform, or if we plan to compile from source for the Windows
platform, choose this distribution format. Building from source on Windows isnt recommended and 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 contents are 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 the Windows
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
that section.

Downloading Apache
Apache 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 the appropriate link. The resulting page
will consist of a list of directories representing all projects found under the Apache Software Foundation
umbrella. Enter the 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 in
learning how to compile from source will provide we with greater configuration flexibility. 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 (and
recommended) 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,
consider going with Apache 2 to take advantage of its enhanced stability. In fact, if we plan to run Apache
on Windows for either development or deployment purposes, it is recommended that we choose version 2
because it is a complete rewrite of the previous Windows distribution and is significantly more stable
than its predecessor.

Installing Apache and PHP on Windows


P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 28

The 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. Take a 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 the license 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 pertinent to the servers operation, including the network
domain, the server name, and the administrators 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 with the 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 the PHP 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 chapter for 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 them directly below the block of
LoadModule entries located in the bottom of the
Global Environment section:
LoadModule php6_module c:/php6/php6apache2.dll
AddType application/x-httpd-php .php
PHPIniDir "c:\php6"

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 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 it to the C:\php6 directory. The php.ini file contains
hundreds of directives that are 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 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.
13. Locate Apache in the list and make sure that it is started. If it is not started, highlight the label and
click Start the Service, located to the left of the label. If it is started, highlight the label and click Restart
the Service, 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 Linux


The 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 xvf httpd-2_X_XX.tar
%>gunzip php-XX.tar.gz
%>tar xvf php-XX.tar
2. 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 PHP at Build Time on Linux for
information regarding modifying installation defaults and incorporating third-party extensions into PHP).
In the following steps, APACHE_INSTALL_DIR is a placeholder for the path to Apaches installed
location, for instance /usr/local/apache2:
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com 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.inis purpose 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 latest stable 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 restart

Configuring PHP
1.Enable Short Open Tags
Search for the line that reads:
short_open_tag = Off
If short_open_tag is set to "off", tags like "<?" will not be recognised as the start tag for a PHP script. In
such a case, to begin a PHP script, you will need to code your script with an opening tag like "<?php".
Since many third party PHP scripts use "<?", setting this to "Off" will give you more problems than it's
worth, particularly since most, if not all, commercial web hosts that support PHP have no issues with
your scripts using "<?" as the open tag. To fix this, change it to the following:
short_open_tag = On
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 31

2.Magic Quotes
By default, input data is not escaped with backslashes. That is, if your visitors enter an inverted comma
(single quote) into your web form, the script will receive that unadorned inverted comma (single quote).
This is for the most part desirable unless you have special requirements. If you want your input data to
have the backslash ("\") prefix, such as, for example, to mimic your web host's settings, search for the
following:
magic_quotes_gpc = Off
and replace it with:
magic_quotes_gpc = On
Do not do this unless your web host has this setting as well. Even with the setting of "Off", you can still
use the addslashes() function in PHP to add the slashes for the specific pieces of data that need them.

3. Register Globals
A number of older scripts assume that all data sent by a form will automatically have a PHP variable of
the same name. For example, if your form has an input field with a name of "something", older PHP
scripts assume that the PHP processor will automatically create a variable called $something that contains
the value set in that field.
If you are running such scripts, you will need to look for the following field:
register_globals = Off
and change it to the following:
register_globals = On
WARNING: Do NOT do this unless you have third party scripts that need it. When writing new scripts,
it's best to always code with the assumption that the register_globals item is set to "Off".

4. Display Errors
On a "live" website, you typically want errors in your script to be silently logged to a PHP error file. On
your own local machine, however, while you are testing and debugging a PHP script, it is probably more
convenient to have error messages sent to the browser window when they appear. This way, you won't
miss errors if you forget to check the error log file.
If you want PHP to display error messages in your browser window, look for the following:
display_errors = Off
And change it to:
display_errors = On
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 32

This value should always be set to "Off" for a "live" website.

5. Session Path
If your script uses sessions, look for the following line:
;session.save_path = "/tmp"
The session.save_path sets the folder where PHP saves its session files. Since "/tmp" does not exist on
Windows, you will need to set it to a directory that does. One way is to create a folder called (say)
"c:\tmp" (the way you created c:\php earlier), and point this setting to that folder. If you do that, change
the line to the following:
session.save_path = "c:\tmp"
Notice that in addition to changing the path, I also removed the semi-colon (";") prefix from the line.
Alternatively, you can find out the current TEMP folder on your computer and use that. Or create a "tmp"
folder in your PHP directory, like "c:\php\tmp" and set the configuration file accordingly. The
possibilities are endless. If you can't decide, just create "c:\tmp" and do as I said above.

6. SMTP Server
If your script uses the mail() function, and you want the function to successfully send mail on your local
machine, look for the following section:
[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25
; For Win32 only.
;sendmail_from = me@example.com
Change it to point to your SMTP server and email account. For example, if your SMTP server is
"mail.example.com" and your email address is "youremail@example.com", change the code to:
[mail function]
SMTP = mail.example.com
smtp_port = 25
sendmail_from = youremail@example.com

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 33

UNIT-III
Embedding PHP Code in Our Web Pages
One of PHPs advantages is that we can embed PHP code directly alongside HTML. For the code to do
anything, the page must be passed to the PHP engine for interpretation. But the Web server doesnt just
pass every page; rather, it passes only those pages identified by a specific file extension (typically .php)
as configured per the instructions in php.ini. But even selectively passing only certain pages to the
engine would nonetheless be highly inefficient for the engine to consider every line as a potential PHP
command. Therefore, the engine needs some means to immediately determine which areas of the page
are PHP-enabled. This is logically accomplished by delimiting the PHP code. There are four delimitation
variants,
Default Syntax
The default delimiter syntax opens with <?php and concludes with ?>,
like this:
<h3>Welcome!</h3>
<?php
echo "<p>Some dynamic output here</p>";
?>
<p>Some static output here</p>
If we save this code as test.php and execute it from a PHP-enabled Web server,
Short-Tags
For less motivated typists an even shorter delimiter syntax is available. Known as short-tags, this syntax
forgoes the php reference required in the default syntax. However, to use this feature, we need to enable
PHPs short_open_tag directive. An example follows:
<?
print "This is another PHP example.";
?>
When short-tags syntax is enabled and we want to quickly escape to and from PHP to output a bit of
dynamic text, we can omit these statements using an output variation known as short-circuit syntax:
<?="This is another PHP example.";?>
This is functionally equivalent to both of the following variations:
<? echo "This is another PHP example."; ?>
<?php echo "This is another PHP example.";?>
Script
PHP support for another mainstream delimiter variant, <script>, is offered:
<script language="php">
print "This is another PHP example.";
</script>
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 34

ASP Style
Microsoft ASP pages employ a strategy, delimiting static from dynamic syntax by using a predefined
character pattern, opening dynamic syntax with <%, and concluding with %>. If were coming from an
ASP background and prefer to continue using this escape syntax, PHP supports it. Heres an example:
<%
print "This is another PHP example.";
%>
Embedding Multiple Code Blocks
We can escape to and from PHP as many times as required within a given page. For instance, the
following example is perfectly acceptable:
<html>
<head>
<title><?php echo "Welcome to my Web site!";?></title>
</head>
<body>
<?php
$date = "July 26, 2007";
?>
<p>Today's date is <?=$date;?></p>
</body>
</html>
Comments
Single-Line C++ Syntax
PHP supports C++ single-line comment syntax, which is prefaced with a double slash (//), like this:
<?php
// Title: My first PHP script
// Author: Jason
echo "This is a PHP program";
?>
Shell Syntax
PHP also supports an alternative to the C++-style single-line syntax, known as shell syntax, which is
prefaced with a hash mark (#)
<?php
# Title: My PHP program
# Author: Jason
echo "This is a PHP program";
?>
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 35

Multiple-Line C Syntax
PHP also offers a multiple-line variant that can open and close the comment on different lines. Heres
an example:
<?php
/*
Title: My PHP Program
Author: Jason
Date: July 26, 2007
*/
?>
Variables in PHP
Variables are used for storing values, such as numbers, strings or function results, so that they can be used
many times in a script.
All variables in PHP start with a $ sign symbol.
The correct way of setting a variable in PHP:
$var_name = value;
PHP is a Loosely Typed Language
In PHP a variable does not need to be declared before being set. PHP automatically converts the variable
to the correct data type, depending on how they are set. In a strongly typed programming language, you
have to declare (define) the type and name of the variable before using it. In PHP the variable is declared
automatically when you use it.
Variable Naming Rules

A variable name must start with a letter or an underscore "_"

A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ )

A variable name should not contain spaces. If a variable name is more than one word, it should be
separated with underscore ($my_string), or with capitalization ($myString)
Variable Scope
We can declare variables anywhere in a PHP script. The location of the declaration greatly influences the
realm in which a variable can be accessed, however. This accessibility domain is known as its scope.
PHP variables can be one of four scope types:
Local variables
Function parameters
Global variables
Static variables
Local Variables
A variable declared in a function is considered local. That is, it can be referenced only in that function.
Any assignment outside of that function will be considered to be an entirely different variable from the
one contained in the function. Note that when you exit the function in which a local variable has been
declared, that variable and its corresponding value are destroyed.
$x = 4;
function assignx () {
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 36

$x = 0;
printf("\$x inside function is %d <br />", $x);
}
assignx();
printf("\$x outside of function is %d <br />", $x);
Output:
$x inside function is 0
$x outside of function is 4
Function Parameters
As in many other programming languages, in PHP, any function that accepts arguments must declare
those arguments in the function header. Although those arguments accept values that come from outside
of the function, they are no longer accessible once the function has exited.
Function parameters are declared after the function name and inside parentheses.
They are declared much like a typical variable would be:
// multiply a value by 10 and return it to the caller
function x10 ($value) {
$value = $value * 10;
return $value;
}
Global Variables
In contrast to local variables, a global variable can be accessed in any part of the program. To modify a
global variable, however, it must be explicitly declared to be global in the function in which it is to be
modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the
variable that should be recognized as global. Placing this keyword in front of an already existing variable
tells PHP to use the variable having that name. Consider an example:
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
echo "Somevar is $somevar";
}
addit();
The displayed value of $somevar would be 16. However, if you were to omit this line, GLOBAL
$somevar; the variable $somevar would be assigned the value 1 because $somevar would then be
considered local within the addit() function. This local declaration would be implicitly set to 0 and then
incremented by 1 to display the value 1.
Static Variables
In contrast to the variables declared as function parameters, which are destroyed on the functions exit, a
static variable does not lose its value when the function exits and will still hold that value if the function
is called again. You can declare a variable as static simply by placing the keyword STATIC in front of the
variable name:
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 37

STATIC $somevar;
Consider an example:
function keep_track() {
STATIC $count = 0;
$count++;
echo $count;
echo "<br />";
}
keep_track();
keep_track();
keep_track();
Output::
1
2
3
Output Statements
PHP offers several methods that Web sites will output data to the browser.
The print() Statement
The print() statement outputs data passed to it to the browser. Its prototype looks like this:
int print(argument)
All of the following are plausible print() statements:
<?php
print("<p>I love the summertime.</p>");
?>
<?php
$season = "summertime";
print "<p>I love the $season.</p>";
?>
The echo() statement
We use the echo() statement for the same purposes as print().
echo()s prototype looks like this:
void echo(string argument1 [, ...string argumentN])
echo() is capable of outputting multiple strings.
<?php
$heavyweight = "Lennox Lewis";
$lightweight = "Floyd Mayweather";
echo $heavyweight, " and ", $lightweight, " are great fighters.";
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 38

?>
The printf() Statement
The printf() statement is ideal when you want to output a blend of static text and dynamic information
stored within one or several variables. Its ideal for two reasons. First, it neatly separates the static and
dynamic data into two distinct sections, allowing for easy maintenance. Second, printf() allows you to
wield considerable control over how the dynamic information is rendered to the screen in terms of its
type, precision, alignment, and position. Its prototype looks like this:
boolean printf(string format [, mixed args])
For example, suppose you wanted to insert a single dynamic integer value into an otherwise static string:
printf("Bar inventory: %d bottles of tonic water.", 100);
In this example, %d is a placeholder known as a type specifier, and the d indicates an integer value will
be placed in that position. When the printf() statement executes, the lone argument, 100, will be inserted
into the placeholder.
Table. Commonly Used Type Specifiers

The following printf() statement passes in an integer and float value:


printf("%d bottles of tonic water cost $%f", 100, 43.20);
When working with decimal values, you can adjust the precision using a precision specifier. An example
follows:
printf("$%.2f", 43.2); // $43.20

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 39

Datatypes
A datatype is the generic name assigned to any data sharing a common set of characteristics. Common
datatypes include Boolean, integer, float, string, and array.
Scalar Datatypes
Scalar datatypes are capable of containing a single item of information. We have scalar datatypes :
Boolean, integer, float, and string.
Boolean
A Boolean variable represents truth, supporting only two values: TRUE and FALSE. Alternatively, you
can use zero to represent FALSE, and any nonzero value to represent TRUE.
A few examples follow:
$alive = false; // $alive is false.
$alive = 1; // $alive is true.
$alive = -1; // $alive is true.
$alive = 5; // $alive is true.
$alive = 0; // $alive is false.
Integer
An integer is representative of any whole number or, in other words, a number that does not contain
fractional parts. PHP supports integer values represented in base 10 (decimal), base 8 (octal), and base 16
(hexadecimal) numbering systems.
Ex:
42 // decimal
-678900 // decimal
0755 // octal
0xC4E // hexadecimal
The maximum supported integer size is platform-dependent, although this is typically positive or
negative 231 for PHP version 5 and earlier. PHP 6 introduced a 64-bit integer value, meaning PHP will
support integer values up to positive or negative 263 in size.
Float
Floating-point numbers, also referred to as floats, doubles, or real numbers, allow you to specify numbers
that contain fractional parts. Floats are used to represent monetary values, weights, distances, and a whole
host of other representations in which a simple integer value wont suffice. PHPs floats can be specified
in a variety of ways, each of which is exemplified here:
4.5678
4.0
8.7e4
1.23E+11

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 40

String
A string is a sequence of characters treated as a contiguous group. Strings are delimited by single or
double quotes,
"PHP is a great language"
"whoop-de-do"
'*9subway\n'
"123$%^789"
PHP treated strings in the same fashion as arrays, allowing for specific characters to be accessed via array
offset notation. For example, consider the following string:
$color = "maroon";
You could retrieve a particular character of the string by treating the string as an array, like this:
$parser = $color[2]; // Assigns 'r' to $parser
Double Quotes
Strings enclosed in double quotes are the most commonly used in most PHP scripts because they offer the
most flexibility. This is because both variables and escape sequences will be parsed accordingly. Consider
the following example:
<?php
$sport = "boxing";
echo "Jason's favorite sport is $sport.";
?>
This example returns the following:
Jason's favorite sport is boxing.
Escape sequences are also parsed. Consider this example:
<?php
$output = "This is one line.\nAnd this is another line.";
echo $output;
?>
This returns the following within the browser source:
This is one line.
And this is another line.

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 41

Table. Recognized Escape Sequences

Single Quotes
Enclosing a string within single quotes is useful when the string should be interpreted exactly as stated.
This means that both variables and escape sequences will not be interpreted when the string is parsed. For
example, consider the following single quoted string:
print 'This string will $print exactly as it\'s \n declared.';
This produces the following:
This string will $print exactly as it's \n declared.
PHP String Functions
strchr() : This function returns the rest of the string (from the matching point), or FALSE, if the string to
search for is not found.
Syntax:
strchr(string,search)
Example
<?php
echo strchr("Hello world!","world");
?>
The output of the code above will be:
world!
strcmp():
The strcmp() function compares two strings.
This function returns:

0 - if the two strings are equal

<0 - if string1 is less than string2

>0 - if string1 is greater than string2


Syntax
strcmp(string1,string2)
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 42

Example
<?php
echo strcmp("Hello world!","Hello world!");
?>
The output of the code above will be:
0
strlen():
The strlen() function returns the length of a string.
Syntax
strlen(string)
Example
<?php
echo strlen("Hello world!");
?>
The output of the code above will be:
12
strpos() :
The strpos() function returns the position of the first occurrence of a string inside another string. If the
string is not found, this function returns FALSE.
Syntax
strpos(string,find,start)
Example
<?php
echo strpos("Hello world!","wo");
?>
The output of the code above will be:
6
strstr()
The strstr() function searches for the first occurrence of a string inside another string. This function
returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.
Syntax
strstr(string,search)
Example
<?php
echo strstr("Hello world!","world");
?>
The output of the code above will be:
world!
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 43

trim():
The trim() function removes whitespaces and other predefined characters from both sides of a string.
Syntax
trim(string,charlist)
Example
<html>
<body>
<?php
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br />";
echo "With trim: " . trim($str);
?>
<body>
<html>
The browser output of the code above will be:
Without trim: Hello World!
With trim: Hello World!
strrev():
The strrev() function reverses a string.
Syntax
strrev(string)
Example
<?php
echo strrev("Hello World!");
?>
The output of the code above will be:
!dlroW olleH
stristr() :
The stristr() function searches for the first occurrence of a string inside another string. This function
returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.
Syntax
stristr(string,search)
Example
<?php
echo stristr("Hello world!","WORLD");
?>
The output of the code above will be:
world!

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 44

ltrim()
The ltrim() function will remove whitespaces or other predefined character from the left side of a string.
Syntax
ltrim(string,charlist)
Example
<html>
<body>
<?php
$str = " Hello World!";
echo "Without ltrim: " . $str;
echo "<br />";
echo "With ltrim: " . ltrim($str);
?>
<body>
<html>
The browser output of the code above will be:
Without ltrim: Hello World!
With ltrim: Hello World!
rtrim()
The rtrim() function will remove whitespaces or other predefined character from the right side of a string.
Syntax
rtrim(string,charlist)
Example 1
<html>
<body>
<?php
$str = "Hello World! ";
echo "Without rtrim: " . $str;
echo "<br />";
echo "With rtrim: " . rtrim($str);
?>
<body>
<html>
The browser output of the code above will be:
Without rtrim: Hello World!
With rtrim: Hello World!
Compound Datatypes
Compound datatypes allow for multiple items of the same type to be aggregated under a single
representative entity. The array and the object are come into this category.
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 45

Array
Array, is defined as an indexed collection of data values. Each member of the array index (alsoknown as
the key) references a corresponding value and can be a simple numerical reference to the values position
in the series, or it could have some direct correlation to the value.
$state[0] = "Alabama";
$state[1] = "Alaska";
$state[2] = "Arizona";
...
$state[49] = "Wyoming";
Instead of having many similar variables, you can store the data as elements in an array. Each element in
the array has its own ID so that it can be easily accessed.
There are three different kind of arrays:
Numeric array - An array with a numeric ID key
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 element with a numeric ID key. There are different ways to create a numeric
array.
Example 1
In this example the ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");
Example 2
In this example we assign the ID key manually:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
The ID keys can be used in a script:
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " . $names[2] .
" are ". $names[0] . "'s neighbors";
?>
Associative Arrays
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 46

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:
$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.";
?>
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"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 47

);

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:
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
PHP Array Functions
The array functions allow you to manipulate arrays.
array()
array() creates an array, with keys and values. If you skip the keys when you specify an array, an integer
key is generated, starting at 0 and increases by 1 for each value.
Syntax
array(key => value)
Example
<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r($a);
?>
The output of the code above will be:
Array ( [a] => Dog [b] => Cat [c] => Horse )

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 48

sort():
The sort() function sorts an array by the values. This function assigns new keys for the elements in the
array. Existing keys will be removed. This function returns TRUE on success, or FALSE on failure.
Syntax
sort(array,sorttype)
Example
<?php
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");
sort($my_array);
print_r($my_array);
?>
The output of the code above will be:
Array
(
[0] => Cat
[1] => Dog
[2] => Horse
)
shuffle()
The shuffle() function randomizes the order of the elements in the array. This function assigns new keys
for the elements in the array. Existing keys will be removed. This function returns TRUE on success, or
FALSE on failure.
Syntax
shuffle(array)
Example
<?php
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");
shuffle($my_array);
print_r($my_array);
?>
The output of the code above could be:
Array ( [0] => Cat [1] => Horse [2] => Dog )

pos()
The pos() function returns the value of the current element in an array.
This function is an alias of the current() function.
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 49

Syntax
pos(array)
Example
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo pos($people) . "<br />";
?>
The output of the code above will be:
Peter
array_reverse()
The array_reverse() function returns an array in the reverse order.
Syntax
array_reverse(array,preserve)
Example
<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r(array_reverse($a));
?>
The output of the code above will be:
Array ( [c] => Horse [b] => Cat [a] => Dog )
sizeof()
The sizeof() function counts the elements of an array, or the properties of an object. This function is an
alias of the count() function.
Syntax
sizeof(array,mode)
Example
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = sizeof($people);
echo $result;
?>
The output of the code above will be:
4
array_key_exists()

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 50

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and
false if the key does not exist.
Syntax
array_key_exists(key,array)
Example 1
<?php
$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
The output of the code above will be:
Key exists!
array_merge()
The array_merge() function merges one ore more arrays into one array.
Syntax
array_merge(array1,array2,array3...)
<?php
$a1=array("a"=>"Horse","b"=>"Dog");
$a2=array("c"=>"Cow","b"=>"Cat");
print_r(array_merge($a1,$a2));
?>
The output of the code above will be:
Array ( [a] => Horse [b] => Cat [c] => Cow )
Object
The other compound datatype supported by PHP is the object. The object is a central concept of the
object-oriented programming paradigm.
Unlike the other datatypes, an object must be explicitly declared. This declaration of an objects
characteristics and behavior takes place within something called a class. Heres a general example of a
class definition and subsequent invocation:
class Appliance {
private $_power;
function setPower($status) {
$this->_power = $status;
}
}
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 51

...
$blender = new Appliance;

Converting Between Datatypes Using Type Casting


Converting values from one datatype to another is known as type casting. A variable can be evaluated
once as a different type by casting it to another. This is accomplished by placing the intended type in
front of the variable to be cast.
Table. Type Casting Operators

Ex:
$score = (double) 13; // $score = 13.0
Type casting a double to an integer will result in the integer value being rounded down, regardless of the
decimal value. Heres an example:
$score = (int) 14.8; // $score = 14
Constants
A constant is a value that cannot be modified throughout the execution of a program.
Constants are particularly useful when working with values that definitely will not
require modification, such as pi (3.141592) or the number of feet in a mile (5,280).
Once a constant has been defined, it cannot be changed (or redefined) at any other
point of the program. Constants are defined using the define() function.
Defining a Constant
The define() function defines a constant by assigning a value to a name. Its prototype
follows:
boolean define(string name, mixed value [, bool case_insensitive])
Ex:
define("PI", 3.141592);
The constant is subsequently used in the following listing:
printf("The value of pi is %f", PI);
$pi2 = 2 * PI;
printf("Pi doubled equals %f", $pi2);
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 52

This code produces the following results:


The value of pi is 3.141592.
Pi doubled equals 6.283184.
Expressions
An expression is a phrase representing a particular action in a program. All expressions
consist of at least one operand and one or more operators. A few examples follow:
$a = 5; // assign integer value 5 to the variable $a
$a = "5"; // assign string value "5" to the variable $a
$sum = 50 + $some_int; // assign sum of 50 + $some_int to $sum
$wine = "Zinfandel"; // assign "Zinfandel" to the variable $wine
$inventory++; // increment the variable $inventory by 1
Operands
Operands are the inputs of an expression.
$a++; // $a is the operand
$sum = $val1 + val2; // $sum, $val1 and $val2 are operands
Operators
An operator is a symbol that specifies a particular action in an expression.
Arithmetic Operators
The arithmetic operators, listed in Table 3-5, perform various mathematical operations and will probably
be used frequently in many of your PHP programs.
Table. Arithmetic Operators

Assignment Operators
The assignment operators assign a data value to a variable. The simplest form of assignment operator just
assigns some value, while perform some other operation before making the assignment.
Table. Assignment Operators

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 53

String Operators
PHPs string operators provide a convenient way in which to concatenate strings together. There are two
such operators, including the concatenation operator (.) and the concatenation assignment operator (.=)

Table. String Operators

Increment and Decrement Operators


The increment (++) and decrement (--) operators can add 1 to or subtract 1 from the current value of a
variable.
Table. Increment and Decrement Operators

Logical Operators
Much like the arithmetic operators, logical operators providing a way to make decisions based on the
values of multiple variables. Logical operators make it possible to direct the flow of a program and are
used frequently with control structures, such as the if conditional and the while and for loops.

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 54

Equality Operators
Equality operators are used to compare two values, testing for equivalence.

Comparison Operators
Comparison operators like logical operators, provide a method to ndirect program flow through an
examination of the comparative values of two or more variables

Bitwise Operators
Bitwise operators examine and manipulate integer values on the level of individual bits that make up the
integer value (thus the name).

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 55

Conditional Statements
The if Statement
The if statement is
means for conditional code execution.
The following is the syntax:
if (expression) {
statement
}
Ex:
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
?>
The else Statement
else statement
is a way to handle those not meeting the if conditional requirements,
Ex:
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
The elseif Statement
elseif statement - is used with the if...else statement to execute a set of code if one of several condition
are true
Syn:
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;
Ex:
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 56

<?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!";
?>
The switch Statement
If you want to select one of many blocks of code to be executed, use the Switch statement. The switch
statement is used to avoid long blocks of if..elseif..else code.
<?php
switch($category) {
case "news":
echo "<p>What's happening around the world</p>";
break;
case "weather":
echo "<p>Your weekly forecast</p>";
break;
case "sports":
echo "<p>Latest sports highlights</p>";
break;
default:
echo "<p>Welcome to my Web site</p>";
}
?>
Looping Statements
Very often when you write code, you want the same block of code to run a number of times. You can use
looping statements in your code to perform this.
In PHP we have the following looping statements:
while - loops through a block of code if and as long as a specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as a special
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
The while Statement
The while statement will execute a block of code if and as long as a condition is true.
Syntax
while (condition)
code to be executed;
Example
The following example demonstrates a loop that will continue to run as long as the variable i is less than,
or equal to 5. i will increase by 1 each time the loop runs:
<html>
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 57

<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
</body>
</html>
The do...while Statement
The do...while statement will execute a block of code at least once - it then will repeat the loop as long
as a condition is true.

Syntax
do{
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will continue incrementing the
variable i as long as it has a value of less than 5:
<html>
<body>
<?php
$i=0;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);
?>
</body>
</html>
The for Statement
The for statement is used when you know how many times you want to execute a statement or a list of
statements.
Syntax
for (initialization; condition; increment)
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 58

code to be executed;
Note: The for statement has three parameters. The first parameter initializes variables, the second
parameter holds the condition, and the third parameter contains the increments required to implement the
loop. If more than one variable is included in the initialization or the increment parameter, they should be
separated by commas. The condition must evaluate to true or false.
Example
The following example prints the text "Hello World!" five times:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
</body>
</html>
The foreach Statement
The foreach statement is used to loop through arrays.
For every loop, the value of the current array element is assigned to $value (and the array pointer is
moved by one) - so on the next loop, you'll be looking at the next element.
Syntax
foreach (array as value)
{
code to be executed;
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}
?>
</body>
</html>
The continue Statement
The continue statement causes execution of the current loop iteration to end and commence at the
beginning of the next iteration. For
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 59

<?php
$usernames = array("grace","doris","gary","nate","missing","tom");
for ($x=0; $x < count($usernames); $x++) {
if ($usernames[$x] == "missing") continue;
printf("Staff member: %s <br />", $usernames[$x]);
}
?>

PHP Functions
Create a PHP Function
A function is a block of code that can be executed whenever we need it.
Creating PHP functions:
All functions start with the word "function()"
Name the function - It should be possible to understand what the function does by its name. The name
can start with a letter or underscore (not a number)
Add a "{" - The function code starts after the opening curly brace
Insert the function code
Add a "}" - The function is finished by a closing curly brace
Example
A simple function that writes my name when it is called:
<html>
<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}
writeMyName();
?>
</body>
</html>

Use a PHP Function


Now we will use the function in a PHP script:
<html>
<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}
echo "Hello world!<br />";
echo "My name is ";
writeMyName();
echo ".<br />That's right, ";
writeMyName();
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 60

echo " is my name.";?>


</html>
The output of the code above will be:
Hello world!
My name is Kai Jim Refsnes.
That's right, Kai Jim Refsnes is my name.

PHP Functions - Adding parameters


Our first function (writeMyName()) is a very simple function. It only writes a static string.
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are
specified inside the parentheses.
Example 1
The following example will write different first names, but the same last name:
<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeMyName("Kai Jim");
echo "My name is ";
writeMyName("Hege");
echo "My name is ";
writeMyName("Stale");
?>
</body>
</html>
The output of the code above will be:
My name is Kai Jim Refsnes.
My name is Hege Refsnes.
My name is Stale Refsnes.
Example 2
The following function has two parameters:
<html>
<body>
<?php
function writeMyName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 61

writeMyName("Kai Jim",".");
echo "My name is ";
writeMyName("Hege","!");
echo "My name is ";
writeMyName("Stle","...");
?>
</body>
</html>
The output of the code above will be:
My name is Kai Jim Refsnes.
My name is Hege Refsnes!
My name is Stle Refsnes...

PHP Functions - Return values


Functions can also be used to return values.
Example
<html>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</html>
The output of the code above will be:
1 + 16 = 17

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 62

UNIT-IV
OOPs concepts:
Encapsulation
The practice of separating the user from the true inner workings of an application through well-known
interfaces is known as encapsulation. Object-oriented programming promotes the same notion of hiding
the inner workings of the application by publishing well-defined interfaces from which each application
component can be accessed.
Inheritance
Inheritance is the mechanism where child class inherits features from parent class. This strategy promotes
code reusability because it assumes that one will be able to use well-designed within numerous
applications.
Polymorphism
Polymorphism, a term originating from the Greek language that means having multiple forms, defines
OOPs ability to redefine, or morph, a classs characteristic or behavior depending upon the context in
which it is used.
Classes
The vocabulary of OOP, such an embodiment of an entitys defining attributes and behaviors is known as
a class. Classes are intended to represent those real-life items that youd like to manipulate within an
application. Class contain fields and methods,
class Class_Name
{
// Field declarations defined here
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 63

// Method declarations defined here


}
class Employee
{
private $name;
private $title;
protected $wage;
protected function clockIn() {
echo "Member $this->name clocked in at ".date("h:i:s");
}
protected function clockOut() {
echo "Member $this->name clocked out at ".date("h:i:s");
}
}
Objects
A class provides a basis from which you can create specific instances of the entity the class models, better
known as objects.
Objects are created using the new keyword, like this:
$employee = new Employee();
Once the object is created, all of the characteristics and behaviors defined within the class are made
available to the newly instantiated object.
Fields
Fields are attributes that are intended to describe some aspect of a class. They are quite similar to
standard PHP variables, except for a few minor differences,
Declaring Fields
The rules regarding field declaration are quite similar to those in place for variable declaration;
essentially, there are none. Because PHP is a loosely typed language, fields dont even necessarily need to
be declared; they can simply be created and assigned simultaneously by a class object.
Declare fields at the beginning of the class.
class Employee
{
public $name = "John";
private $wage;
}
In this example, the two fields, name and wage, are prefaced with a scope descriptor (public or private), a
common practice when declaring fields. Field can be used under the terms accorded to it by the scope
descriptor.
Invoking Fields

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 64

Fields are referred to using the -> operator and, unlike variables, are not prefaced with a dollar sign.
Furthermore, because a fields value typically is specific to a given object, it is correlated to that object
like this:
$object->field
Ex:
$employee->name
$employee->title
$employee->wage
When you refer to a field from within the class in which it is defined, it is still prefaced with the ->
operator, although instead of correlating it to the class name, you use the $this keyword. $this implies that
youre referring to the field residing in the same class in which the field is being accessed or manipulated.
function setName($name)
{
$this->name = $name;
}

Field Scopes
PHP supports five class field scopes: public, private, protected, final, and static.
Public
You can declare fields in the public scope by prefacing the field with the keyword public.
class Employee
{
public $name;
// Other field and method declarations follow...
}
Public fields can then be manipulated and accessed directly by a corresponding object, like so:
$employee = new Employee();
$employee->name = "Mary Swanson";
$name = $employee->name;
echo "New employee: $name";
Private
Private fields are only accessible from within the class in which they are defined. An example follows:
class Employee
{
private $name;
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 65

private $telephone;
}
Fields designated as private are not directly accessible by an instantiated object, nor are they available to
subclasses.
class Employee
{
private $name;
public function setName($name) {
$this->name = $name;
}
}
$staff = new Employee;
$staff->setName("Mary");
Protected
Protected variables intended for use only within the function, classes can include fields used for solely
internal purposes.
class Employee
{
protected $wage;
}
Protected fields are also made available to inherited classes for access and manipulation, any attempt by
an object to access a protected field will result in a fatal error
Final
Marking a field as final prevents it from being overridden by a subclass,
A finalized field is declared like so:
class Employee
{
final $ssn;
}
Properties
Setting Properties The mutator, or setter method, is responsible for both hiding property assignment
implementation and validating class data before assigning it to a class field. Its prototype follows:
boolean __set([string property name],[mixed value_to_assign])
It takes as input a property name and a corresponding value, returning TRUE if the method is
successfully executed, and FALSE otherwise. An example follows:
class Employee
{
var $name;
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 66

function __set($propName, $propValue)


{
echo "Nonexistent variable: \$$propName!";
}
}
$employee = new Employee ();
$employee->name = "Mario";
$employee->title = "Executive Chef";
This results in the following output:
Nonexistent variable: $title!
Getting Properties
The accessor, or mutator method, is responsible for encapsulating the code required for retrieving a class
variable. Its prototype follows:
boolean __get([string property name])
It takes as input one parameter, the name of the property whose value youd like to retrieve. It should
return the value TRUE on successful execution, and FALSE otherwise.
An example follows:
class Employee
{
var $name;
var $city;
protected $wage;
function __get($propName)
{
echo "__get called!<br />";
$vars = array("name","city");
if (in_array($propName, $vars))
{
return $this->$propName;
} else {
return "No such variable!";
}
}
}
$employee = new Employee();
$employee->name = "Mario";
echo $employee->name."<br />";
echo $employee->age;
This returns the following:
Mario
__get called!
No such variable!
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 67

Creating Custom Getters and Setters


<?php
class Employee
{
private $name;
// Getter
public function getName() {
return $this->name;
}
// Setter
public function setName($name) {
$this->name = $name;
}
}
?>
Constants
You can define constants, or values that are not intended to change, within a class. These values will
remain unchanged throughout the lifetime of any object instantiated from that class. Class constants are
created like so:

const NAME = 'VALUE';


class math_functions
{
const PI = '3.14159265';
const E = '2.7182818284';
const EULER = '0.5772156649';
// define other constants and methods here...
}
Methods
A method is quite similar to a function, except that it is intended to define the behavior of a particular
class. Like a function, a method can accept arguments as input and can return a value to the caller.
Methods are also invoked like functions, except that the method is prefaced with the name of the object
invoking the method, like this:
$object->method_name();
Declaring Methods
Methods are created in exactly the same fashion as functions, using identical syntax. The only difference
between methods and normal functions is that the method declaration is typically prefaced with a scope
descriptor. The generalized syntax follows: scope
function functionName()
{
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 68

// Function body goes here


}
Ex:
public function calculateSalary()
{
return $this->wage * $this->hours;
}
Invoking Methods
$employee = new Employee("Janie");
$salary = $employee->calculateSalary();
Method Scopes
PHP supports six method scopes: public, private, protected, abstract, final, and static.
Public
Public methods can be accessed from anywhere at any time. You declare a public method by prefacing it
with the keyword public

<?php
class Visitors
{
public function greetVisitor()
{
echo "Hello<br />";
}
function sayGoodbye()
{
echo "Goodbye<br />";
}
}
Visitors::greetVisitor();
$visitor = new Visitors();
$visitor->sayGoodbye();
?>
The following is the result:
Hello
Goodbye
Private
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 69

Methods marked as private are available for use only within the originating class and cannot be called by
the instantiated object, nor by any of the originating classs subclasses
private function validateCardNumber($number)
{
if (($a<$b) return FALSE;
else return TRUE;
}
Attempts to call this method from an instantiated object result in a fatal error.
Protected
Class methods marked as protected are available only to the originating class and its subclasses. Such
methods might be used for helping the class or subclass perform internal computations.
<?php
class Employee
{
private $ein;
function __construct($ein)
{
if ($this->verifyEIN($ein)) {
echo "EIN verified. Finish";
}
}

protected function verifyEIN($ein)


{
return TRUE;
}
}
$employee = new Employee("123-45-6789");
?>
Abstract
Abstract methods are special in that they are declared only within a parent class but are implemented in
child classes. Only classes declared as abstract can contain abstract methods.
Abstract methods are declared like this:
abstract function methodName()
Ex:
abstract class Employee
{
abstract function hire();
abstract function fire();
abstract function promote();
abstract demote();
}
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 70

Final
Marking a method as final prevents it from being overridden by 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 is indeed a member of the expected class.
For example, it makes sense that only objects of class Employee should be passed to the
takeLunchbreak() method.
private function takeLunchbreak(Employee $employee)
{
...
}

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 the class parent.
PHP recognizes constructors by the name __construct. The general syntax for constructor declaration
follows:
function __construct([argument1, argument2, ..., argumentN])
{
// Class initialization code
}
<?php
class Book
{
private $title;
private $isbn;
private $copies;
public function _construct($isbn)
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 71

{
$this->setIsbn($isbn);
$this->getTitle();
$this->getNumberCopies();
}
public function setIsbn($isbn)
{
$this->isbn = $isbn;
}
public function getTitle() {
$this->title = "Beginning Python";
print "Title: ".$this->title."<br />";
}
public function getNumberCopies() {
$this->copies = "5";
print "Number copies available: ".$this->copies."<br />";
}
}
$book = new book("159059519X");
?>
This results in the following:
Title: Beginning Python
Number copies available: 5

Invoking Parent Constructors


PHP does not automatically call the parent constructor; you must call it explicitly using the parent
keyword. An example follows:
<?php
class Employee
{
protected $name;
protected $title;
function __construct()
{
echo "<p>Staff constructor called!</p>";
}
}
class Manager extends Employee
{
function __construct()
{
parent::__construct();
echo "<p>Manager constructor called!</p>";
}
}
$employee = new Manager();
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 72

?>
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 other
method but must be titled __destruct ().
An example follows:
<?php
class Book
{
private $title;
private $isbn;
private $copies;
function __construct($isbn)
{
echo "<p>Book class instance created.</p>";
}
function __destruct()
{
echo "<p>Book class instance destroyed.</p>";
}
}
$book = new Book("1893115852");
?>
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 and any information created as a result of the instantiation reside in memory, youre not
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.
<?php
class Visitor
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 73

{
private static $visitors = 0;
function __construct()
{
self::$visitors++;
}
static function getVisitors()
{
return self::$visitors;
}
}
/* Instantiate the Visitor class. */
$visits = new Visitor();
echo Visitor::getVisitors()."<br />";
/* Instantiate another Visitor class. */
$visits2 = new Visitor();
echo Visitor::getVisitors()."<br />";
?>
The results are as follows:
1
2

The instanceof Keyword


The instanceof keyword was introduced with PHP 5. With it you can determine whether an object is an
instance of a class, is a subclass of a class, or implements a particular interface, and do something
accordingly.
For example, suppose you want to learn whether an object called manager is derived from the class
Employee:
$manager = new Employee();
...
if ($manager instanceof Employee) 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 that inherits from Employee.
<?php
class Employee {
private $name;
function setName($name) {
if ($name == "") echo "Name cannot be blank!";
else $this->name = $name;
}
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 74

function getName() {
return "My name is ".$this->name."<br />";
}
}
class Executive extends Employee {
function pillageCompany() {
echo "I'm selling company assets to finance my yacht!";
}
} $exec = new Executive();
$exec->setName("Richard");
echo $exec->getName();
$exec->pillageCompany();
?>
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 also have a constructor.
function __construct($name) {
$this->setName($name);
}
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 "<p>CEO object created!</p>";
}
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
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 75

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 "<p>CEO object created!</p>";
}
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 Dennis
Interfaces
An interface defines a general specification for implementing a particular service, declaring the required
functions and constants without specifying exactly how it must be implemented. Implementation details
arent provided because different entities might need to implement the published method definitions in
different ways.

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
}
}
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 76

Implementing a Single 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.";
}
}

Implementing Multiple Interfaces


<?php
interface IEmployee {...}
interface IDeveloper {...}
interface IPillage {...}
class Employee implements IEmployee, IDeveloper, iPillage {
...
}
class Contractor implements IEmployee, IDeveloper {
...
}
?>
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
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 77

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.

UNIT-V
Cookies
Cookies 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 stored on a users computer, they have developed a bad
rap as being highly insecure. And because 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 Cookies
To 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:
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 78

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]]
)
setcookie() Parameters

Example :
<?php
$GLOBALS['username'] = "test";
$GLOBALS['password'] = "test";
function validatelogin ($username, $password){
if (strcmp ($username, $GLOBALS['username']) == 0
&& strcmp ($password, $GLOBALS['password']) == 0){
setcookie ("cookie_user", $username, time()+60*60*24*30);
setcookie ("cookie_pass", md5 ($password), time()+60*60*24*30);
return true;
} else {return false;
}
}
if (validatelogin ("test","test")){
echo "Successfully logged in.";
} else {
echo "Sorry, invalid login.";
}
?>

Reading Cookies
The 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:

<?php
$GLOBALS['username'] = "test";
$GLOBALS['password'] = "test";
setcookie ("cookie_user", "test", time()+60*60*24*30);
setcookie ("cookie_pass", md5 ("test"), time()+60*60*24*30);
function validatelogin (){
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 79

if (strcmp ($_COOKIE['cookie_user'], $GLOBALS['username']) == 0


&& strcmp ($_COOKIE['cookie_pass'], md5 ($GLOBALS['password'])) == 0){
return true;
} else {
return false;
}
}
if (validatelogin ()){
echo "Successfully logged in.";
} else
{
echo "Sorry, invalid login.";}
?>

Deleting Cookies
We should note that cookies will disappear by themselves if we have set them up to 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 name of logout and is a staple of a well-programmed user interface.
<?php
setcookie ("cookie_user", "test", time()+60*60*24*30);
setcookie ("cookie_pass", md5 ("test"), time()+60*60*24*30);
function logout (){
//To remove a cookie, we simply set the value of the cookie to blank.
setcookie ("cookie_user", "", time()+60*60*24*30);
setcookie ("cookie_pass", "", time()+60*60*24*30);
}
//We call the logout script.
logout();
//We can no longer access the cookies.
echo $_COOKIE['cookie_user'] . "<br />";
echo "We have successfully logged out.";
?>
Another example:
When deleting a cookie we 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);
?>

HTTP Headers
HTTP 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 been written 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 of the browser cache.
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 80

The header () functions prototype is as follows:


void header ( string string [, bool replace [, int http_response_code]] )

Redirecting to a Different Location


One 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 page we want. We prefer to use headers to
control exception handling within process scripts.
The Ex Code:
<html
<title>Sample </title>
</head>
<body>
<form action="sample.php" method="post">
Name: <input type="text" name="wername" maxlength="150" /><br />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
</body>
</html>
The form in the previous block of code will then call the processing statement as follows:

Sample.php:
<?php
if (trim ($_POST['wername']) == "")
{
header ("Location: sample12_5.html");
exit;
}
echo $_POST['wername'];
?>

Sending Content Types Other Than HTML


We will want to use the header () function to output a type of file format that may not be an actual web
page. To make the most out of this function, we can effectively output other file types by simply
declaring the content type we want to output. This functionality can be handy in circumstances where we
want to deploy a document to a user or perhaps even output a dynamic image.
Example :
<html >
<title>Sample </title>
</head>
<body>
<div align="center">
<img src="sample1.php" alt="" title="" style="border: none;" />
</div>
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 81

</body>
</html>
Sample1.php
<?php
$path = "images/winter.jpg";
try {
if (is_file ($path)){
if ($file = fopen($path, 'rb')) {
while(!feof($file) and (connection_status()==0)) {
$f .= fread($file, 1024*8);
}
fclose($file);
}
header ("Content-type: image/jpeg");
print $f;
} else {
throw new exception ("Sorry, file path is not valid.");
}
} catch (exception $e){
echo exception.$e;
}
?>
Common File Format Content Types

Forcing File Save As Downloads


We 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
<?php
//The location of the image.
$path = "images/winter.jpg";
try {
if (is_file ($path)){
if ($file = fopen($path, 'rb')) {
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 82

while(!feof($file) and (connection_status()==0)) {


$f .= fread($file, 1024*8);
}
fclose($file);
}
//Use the header function to output an image of .jpg.
$outputname = "myimage";
header ("Content-type: image/jpeg");
//This will force a download.
header("Content-disposition: attachment; filename=".$outputname.".jpg");
print $f;
} else {
throw new exception ("Sorry, file path is not valid.");
}
} catch (exception $e){
echo $e->getmessage();
}
?>
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
output a file of the requested type.

Sessions
Cookies are getting less and less trusted as a solution, sessions created. Sessions are handled much like
cookies but with a major difference. While cookies are declared as global members of the site, a session
state must be enabled to use them effectively. While in the session state, sessions can be accessed just like
cookies, 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. But on 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 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 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 and access
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 )
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 83

bool session_destroy ( void )


The Code:
<?php
//First, create a session states.
session_start();
$GLOBALS['user'] = "test";
$GLOBALS['pass'] = "test";
//Now, here is a function that will log we in.
function login ($username, $password)
{
if (strcmp ($username, $GLOBALS['user']) == 0
&& strcmp ($password, $GLOBALS['pass']) == 0){
$_SESSION['user'] = $username;
$_SESSION['pass'] = md5 ($password);
return true;
} else {
return false;
}
}
//Function to logout.
function logout (){
unset ($_SESSION['user']);
unset ($_SESSION['pass']);
session_destroy();
}
//Now, we can login.
if (login("test","test")){
echo "Successfully logged in with user: " . $_SESSION['user']. " and pass: " . $_SESSION['pass'];
} else {
echo "Could not login.";
}
//Now, we logout.
logout();
if (isset ($_SESSION['user'])){
echo $_SESSION['user']; //Outputs nothing.
}
?>
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 was last 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
<?php
//First, create a session states.
session_start();
(int) $_SESSION['integer_value'] = "115";
(string) $_SESSION['string_value'] = "Hello World";
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 84

(float) $_SESSION['float_value'] = "1.07";


function outputsessions (){
echo $_SESSION['integer_value'] . "<br />"; //Outputs 115.
echo $_SESSION['string_value'] . "<br />"; //Outputs Hello World.
echo $_SESSION['float_value'] . "<br />"; //Outputs 1.07.
}
//Then we can call the function from here:
outputsessions();
?>

Storing Complex Data Types in Sessions


One 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 of data 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
<?php
//First, create a session states.
session_start();
class myclass
{
protected $myvalue;
public function setmyvalue ($newvalue)
{
$this->myvalue = $newvalue;
}
public function getmyvalue (){
return $this->myvalue;
}
}
$_SESSION['myclass_value'] = new myclass ();
function outputsessions (){
$_SESSION['myclass_value']->setmyvalue ("Hello World");
echo $_SESSION['myclass_value']->getmyvalue ();
}
//Then we can call the function from here:
outputsessions();
?>

Authenticating Our Users


We 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 Authentication
Managing user authentication through cookies or sessions is a little harder than using 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
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 85

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
<?php
session_start();
?>
<html >
<title>Sample </title>
<?php
//Normally wer username and pass would be stored in a database.
//For this example we will assume that we have already retrieved them.
$GLOBALS['user'] = "test";
$GLOBALS['pass'] = "test";
if (isset ($_POST['user']) && isset ($_POST['pass']))
{
if (strcmp ($_POST['user'], $GLOBALS['user']) == 0
&& strcmp ($_POST['pass'], $GLOBALS['pass']) == 0)
{
$_SESSION['user'] = $_POST['user'];
$_SESSION['pass'] = $_POST['pass'];
} else {
?><div align="center"><p style="color: #FF0000;">
Sorry, we have entered an incorrect login.</p></div><?php
}
}
//Check if we need to logout.
if ($_POST['logout'] == "yes")
{
unset ($_SESSION['user']);
unset ($_SESSION['pass']);
session_destroy();
}
//We then use this function on every page to check for a valid login at all
times.
function checkcookies ()
{
if (strcmp ($_SESSION['user'], $GLOBALS['user']) == 0
&& strcmp ($_SESSION['pass'], $GLOBALS['pass']) == 0){
return true;
} else {
return false;
}
}
?>
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 86

</head>
<body>
<div align="center">
<?php
//Check if we have a valid login.
if (checkcookies())
{
?>
<p>Congratulations, we are logged in!</p>
<form action="sample12_17.html" method="post" style="margin: 0px;">
<input type="hidden" name="logout" value="yes" />
<input type="submit" value="Logout" />
</form>
<?php
//Or else present a login form.
} else {
?>
<form action="sample12_17.html" method="post" style="margin: 0px;">
<div style="width: 500px; margin-bottom: 10px;">
<div style="width: 35%; float: left; text-align: left;">
Username:
</div>
<div style="width: 64%; float: right; text-align: left;">
<input type="text" name="user" maxlength="25" />
</div>
<br style="clear: both;" />
</div>
<div style="width: 500px; margin-bottom: 10px;">
<div style="width: 35%; float: left; text-align: left;">
Password:
</div>
<div style="width: 64%; float: right; text-align: left;">
<input type="password" name="pass" maxlength="25" />
</div>
<br style="clear: both;" />
</div>
<div style="width: 500px; text-align: left;">
<input type="submit" value="Login" /></div>
</form>
<?php
}
?>
</div>
</body>
</html>
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 field is in place, it then goes through the algorithm to kill off the session variables.
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 87

Using Environment and Configuration Variables


PHP provides a means to use and verify the configuration settings and environment variables relative to
the server space the script is occupying. 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 special
occurrences.
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 file upload scripts. The
base PHP installation leaves only enough processing time to upload files that are generally 2MB or
smaller in size. By manipulating the PHP configuration files temporarily, we can increase the limit
enough to allow a script to process much larger files.

Reading Environment and Configuration Variables


The $_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.
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.
The Code
<?php
//Here is an example of retrieving an environmental variable or two.
echo $_ENV['ProgramFiles'] . "<br />"; //Outputs C:\Program Files.
echo $_ENV['COMPUTERNAME'] . "<br />"; //Outputs RAVI TEJA.
echo getenv("COMPUTERNAME") . "<br />"; //Also Outputs RAVI TEJA.
//Now, let's look at reading configuration variables.
echo ini_get ("post_max_size") . "<br />"; //Outputs 8MB.
//And we can output the entire listing with this function.
print_r (ini_get_all());
?>

Setting Environment and Configuration Variables


To set Environment Variables While working with environment variables, we need to assign a new value
to the $_ENV superglobal to process a temporary change. The change will be in effect for the scripts
duration.
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 88

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, the configuration variable will return to its
original state.
The prototype for ini_set() is as follows:
string ini_set ( string varname, string newvalue )
The code
<?php
//Setting an environment variable in php is as easy as assigning it.
echo $_ENV['COMPUTERNAME'] . "<br />"; // Echoes BABINZ-CODEZ.
$_ENV['COMPUTERNAME'] = "Hello World!";
echo $_ENV['COMPUTERNAME'] . "<br />"; //Echoes the new COMPUTERNAME.
echo ini_get ('post_max_size'); //Echoes 8MB.
//Then we set it to 200M for the duration of the script.
ini_set('post_max_size','200M');
//Any files that are to be uploaded in this script will be OK up to 200M.
?>

Date and Time Functions

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 89

date() :
Returns a string formatted according to the given format string using the given integer timestamp or the
current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of
time().
Syn:
string date ( string $format [, int $timestamp] )

format

character

Description

Example returned values

Day

---

---

Day of the month, 2 digits with leading zeros

01 to 31

A textual representation of a day, three letters

Mon through Sun

Day of the month without leading zeros

1 to 31

l (lowercase
'L')

A full textual representation of the day of the


week

Sunday through Saturday

ISO-8601 numeric representation of the day of


the week (added in PHP 5.1.0)

1 (for Monday) through 7 (for


Sunday)

English ordinal suffix for the day of the


month, 2 characters

st, nd, rd or th. Works well


with j

Numeric representation of the day of the week

0 (for Sunday) through 6 (for


Saturday)

The day of the year (starting from 0)

0 through 365

Week

---

---

ISO-8601 week number of year, weeks


starting on Monday (added in PHP 4.1.0)

Example: 42 (the 42nd week


in the year)

Month

---

---

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 90

format

character

Description

Example returned values

A full textual representation of a month, such


as January or March

January through December

Numeric representation of a month, with


leading zeros

01 through 12

A short textual representation of a month,


three letters

Jan through Dec

Numeric representation of a month, without


leading zeros

1 through 12

Number of days in the given month

28 through 31

Year

---

---

Whether it's a leap year

1 if it is a leap year, 0
otherwise.

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)

Examples: 1999 or 2003

A full numeric representation of a year, 4


digits

Examples: 1999 or 2003

A two digit representation of a year

Examples: 99 or 03

Time

---

---

Lowercase Ante meridiem and Post meridiem

am or pm

Uppercase Ante meridiem and Post meridiem

AM or PM

Swatch Internet time

000 through 999

12-hour format of an hour without leading


zeros

1 through 12

24-hour format of an hour without leading


zeros

0 through 23

12-hour format of an hour with leading zeros

01 through 12

24-hour format of an hour with leading zeros

00 through 23

Minutes with leading zeros

00 to 59

Seconds, with leading zeros

00 through 59

Milliseconds (added in PHP 5.2.2)

Example: 54321

Timezone

---

---

Timezone identifier (added in PHP 5.1.0)

Examples: UTC, GMT,


Atlantic/Azores

I (capital i)

Whether or not the date is in daylight saving


time

1 if Daylight Saving Time, 0


otherwise.

Difference to Greenwich time (GMT) in hours

Example: +0200

Difference to Greenwich time (GMT) with


colon between hours and minutes (added in
PHP 5.1.3)

Example: +02:00

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 91

format

character

Description

Example returned values

Timezone abbreviation

Examples: EST, MDT ...

Timezone offset in seconds. The offset for


timezones west of UTC is always negative,
and for those east of UTC is always positive.

-43200 through 50400

Full
Date/Time

---

---

ISO 8601 date (added in PHP 5)

2004-02-12T15:19:21+00:00

RFC 2822 formatted date

Example: Thu, 21 Dec 2000


16:01:07 +0200

Seconds since the Unix Epoch (January 1


1970 00:00:00 GMT)

See also time()

<?php
// Assuming today is: March 10th, 2012, 5:16:18 pm
$today
$today
$today
$today
$today
ripm01
$today
$today
$today
$today
?>

=
=
=
=
=

date("F j, Y, g:i a");


date("m.d.y");
date("j, n, Y");
date("Ymd");
date('h-i-s, j-m-y, it is w Day z ');

//
//
//
//
//

March 10, 2012, 5:16 pm


03.10.01
10, 3, 2012
20120310
05-16-17, 10-03-01, 1631 1618 6 F

=
=
=
=

date('\i\t \i\s \t\h\e jS \d\a\y.');


date("D M j G:i:s T Y");
date('H:m:s \m \i\s\ \m\o\n\t\h');
date("H:i:s");

//
//
//
//

It is the 10th day.


Sat Mar 10 15:16:08 MST 2012
17:03:17 m is month
17:16:17

mktime() :This method mainly used to work with specific date


Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer
containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time
specified.
Arguments may be left out in order from right to left; any arguments thus omitted will be set to the
current value according to the local date and time.
<?php
echo
echo
echo
echo
?>

date("M-d-Y",
date("M-d-Y",
date("M-d-Y",
date("M-d-Y",

mktime(0,
mktime(0,
mktime(0,
mktime(0,

0,
0,
0,
0,

0,
0,
0,
0,

12, 32, 2012));


13, 1, 2014));
1, 1, 2018));
1, 1, 1990));

strtotime() : convert dates in the form of English-language strings into Unix timestamps using the
strtotime() function.
We can use two-digit years (0069 = 2000s, 7099 = 1900s) and four-digit years. An unformatted fourdigit number in isolation will be treated as a time; that is, 2004 used by itself will be interpreted as 20:04
(8:04 p.m.).
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 92

Numeric days and months are accepted in either one- or two-digit formats. Note that numbers cannot be
spelled out.
We can use names of months in full or the standard three- and four-letter abbreviations for months. For
instance, both 24 Sep 1990 and 24 September 1990 will be interpreted correctly.
Days of the week are allowed, either spelled out in full or as three-letter abbreviations.
Numeric dates in the formats [[yy]y]y-[m]m-[d]d or [m]m/[d]d/[yy]yy are permitted. That is, 05-01-25,
05-1-5, and 2005-1-05 are all interpreted as January 5, 2005, and so are 01/05/05 and 1/5/2005.
Unformatted five- or six-digit numbers will be interpreted as a date in (y)y-mm-dd format; 020430 and
20430 will both be resolved to the timestamp equivalent of April 30, 2002. (A single digit in the year
position will be taken to mean the year ending in that digit from the current decade.)
If we need a timestamp for the beginning of a month, do not use a zero for the day of the month; this
will be parsed as the last day of the previous month. Use 1 or 01 as the first day of the month.
We can use 24-hour times and 12-hour times with the am/pm or AM/PM indicator. Leading zeroes are
optional for hours, minutes, and seconds, which must be separated with a colon (:).
We can use units such as hour, day, week, fortnight, month, year, and so on, and the symbols + and (the + is optional) along with numerals to indicate future and past. Note that any numbers we use in this
fashion cannot be spelled out.
We can use many (English-speaking!) ordinary words relating to dates and times, such as now, last,
today, yesterday, ago, and so on. The following example shows how this works.

The output of this loop in a browser is as follows (for the time, date, and time zone shown in the first
line):
now:
Wed, 28 Mar 2012 17:05:56 +0200
today:

Wed, 28 Mar 2012 00:00:00 +0200

tomorrow:

Thu, 29 Mar 2012 00:00:00 +0200

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 93

yesterday:

Tue, 27 Mar 2012 00:00:00 +0200

Thursday:

Thu, 29 Mar 2012 00:00:00 +0200

this Thursday:

Thu, 29 Mar 2012 00:00:00 +0200

last Thursday:

Thu, 22 Mar 2012 00:00:00 +0100

+2 hours:

Wed, 28 Mar 2012 19:05:56 +0200

-1 month:

Tue, 28 Feb 2012 17:05:56 +0100

+10 minutes:

Wed, 28 Mar 2012 17:15:56 +0200

30 seconds:

Wed, 28 Mar 2012 17:06:26 +0200

+2 years -1 month: Fri, 28 Feb 2014 17:05:56 +0100


next week:

Mon, 02 Apr 2012 17:05:56 +0200

last month:

Tue, 28 Feb 2012 17:05:56 +0100

last year:

Mon, 28 Mar 2011 17:05:56 +0200

2 weeks ago:

Wed, 14 Mar 2012 17:05:56 +0100

Finding the Date for a Weekday


By combining date() and strtotime(), it is possible get the day for any desired weekday in a given month.
The following example shows how you can determine the date of the first Tuesday in the month
following the current one.
The Code
<?php
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo 'Today is ' . date('d M Y') . '.<br />\n';
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';
?>
Output:
Today is 28 Mar 2012.
The first Tuesday of next month is 03 Apr 2012.
For all months:
<?php
echo 'Today is ' . date('d M Y') . '.';
for($i = 1; $i <= 12; $i++)
{
$nextmonth = date('Y-' . (date('n') + $i) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo '\n<br />The first Tuesday in ' . date('F', $firsttue_ts)
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 94

. ' is ' . date('d M Y', $firsttue_ts) . '.';


}
?>
Getting the Day and Week 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
<?php
$mydates = array('2005-01-01', '2005-06-30', '2005-12-31');
foreach($mydates as $mydate)
{
$ts = strtotime($mydate);
echo 'Day ' . date('d M Y: z', $ts) . "<br />\n";
}
?>
Output:
01 Jan 2005: Day 0
30 Jun 2005: Day 180
31 Dec 2005: Day 364

Determining Whether a Given Year Is a Leap Year


The date() function employs another one-letter argument; it uses L to determine if a given year is a le
year. When this is used, date() returns 1 if the year in question is a leap year and 0 if it is not. Rather than
make repeated calls to date() 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
<?php
// takes a 2- or 4-digit year,
// returns 1 or 0
function is_leap_year($year)
{
$ts = strtotime("$year-01-01");
return date('L', $ts);
}
// test the function for a set of 11 consecutive years
for($i = 2010; $i <= 2020; $i++)
{
$output = "$i is ";
if( !is_leap_year($i) )
$output .= "not ";
$output .= "a leap year.<br />\n";
echo $output;
}
?>
Output:
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 95

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.
2015 is not a leap year.
2016 is a leap year.
2017 is not a leap year.
2018 is not a leap 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 )

checkdate() example
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>
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]]]]] )

Parameters
timestamp

The timestamp of the day from which the sunrise time is taken.
format

P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 96

constant

description

example

SUNFUNCS_RET_STRING

returns the result as string

16:46

SUNFUNCS_RET_DOUBLE

returns the result as float

16.78243132

SUNFUNCS_RET_TIMESTAMP

returns the result as integer


(timestamp)

1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude
longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude
zenith

Default: date.sunrise_zenith
gmtoffset

Specified in hours
<?php
/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90,
1);
echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 3
8.4, -9, 90, 1);

?>
The above example will output something similar to:
Mon Dec 20 2004, sunrise time : 08:54

getdate() :
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:
<?php
$today = getdate();
print_r($today);
?>
The above example will output something similar to:
Array
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 97

(
[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:
<?php
$nextWeek = time() + (7 * 24 * 60 * 60); // 7 days; 24 hours; 60 mins; 60secs
echo 'Now:
'. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>
The above example will 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 determine the 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 April

Determining 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:
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 98

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 of days 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 45 days 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, 2007

UNIT-VI

Creating and Using Forms


Forms
When 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 Elements

GET vs. POST


When dealing with forms, we must specify the way that the information entered into the form is
transmitted to its destination (method="").
P.Ravi Theja,Asst.Professor,GIST,Nellore

Email:raviteja.pannem@gmail.com Page 99

The two ways available to a web developer are GET and POST.

When sending data using the GET method, all fields are appended to the Uniform Resource Locator
(URL) of the browser and sent along with the address as data.

Sending data using the GET method means that fields are generally capped at 150 characters, which
is certainly not the most effective means of passing information.

It is also not a secure means of passing data, because many people know how to send information to a
script using an address bar.

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 handle the data in the way we want.

The $_GET Variable


The $_GET variable is an array of variable names and values sent by the HTTP GET method.
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 (it will be displayed in the browser's address bar) and it
has limits on the amount of information to send (max. 150 characters).
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
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 <?php echo $_GET["name"]; ?>.<br />
We are <?php echo $_GET["age"]; ?> years old!

Note: When using the $_GET variable all variable names and values are displayed in 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, it is 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 exceed 150
characters.
P.Ravi Theja,Asst.Professor,GIST,Nellore
100

Email:raviteja.pannem@gmail.com

Page

The $_POST Variable


The $_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
<form action="welcome.php" method="post">
Enter our name: <input type="text" name="name" />
Enter our age: <input type="text" name="age" />
<input type="submit" />
</form>
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 that the names
of the form fields will automatically be the ID keys in the $_POST array):
Welcome <?php echo $_POST["name"]; ?>.<br />
We are <?php echo $_POST["age"]; ?> years old!

Why use $_POST?

Variables sent with HTTP POST are not shown in the URL
Variables have no length limit

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

The $_REQUEST Variable


The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and
POST methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br />
We are <?php echo $_REQUEST["age"]; ?> years old!

Superglobals vs.Globals
Data was passed along from script to script with loose security.In the php.ini file, we can change a value
called register_globals to either on or off.If we leave it on, then whenever we pass a value using the GET
or POST method, we can access the variable simply by putting an ampersand (&) character in front of the
name of the element we are passing. The problem with this method is that malicious users can insert
values into our code to bypass the form entirely.
Therefore, if we want our code to be as secure as possible (and who doesnt?), we should definitely code
our applications with register_globals turned off and ensure that we receive our values from where we
expect them to come. Using superglobals allows us to do this. The following example shows how we can
P.Ravi Theja,Asst.Professor,GIST,Nellore
101

Email:raviteja.pannem@gmail.com

Page

submit values using globals or superglobals. Note that for this example to work properly, we must
temporarily switch our register_globals value to on
<html
<title>Sample title>
</head>
<body>
<div style="width: 500px; text-align: left;">
<?php
//Handle the incoming data.
//Here is how we could handle it with register_globals turned on.
if ($submitted == "yes"){
if (trim ($ourname) != ""){
echo "Our Name: $ourname.";
} else {
echo "We must submit a value.";
}
?><br /><a href="sample.php">Try Again</a><br /><?php
}
//Now, here is how it SHOULD be handled with register_globals turned off.
if ($_POST['submitted'] == "yes"){
if (trim ($_POST['ourname']) != ""){
echo "Our Name: " . $_POST['ourname'] . ".";
} else {
echo "We must submit a value.";
}
?><br /><a href="sample.php">Try Again</a><br /><?php
}
?>
<?php
//Show the forms only if we don't already have a submittal.
if ($_POST['submitted'] != "yes"){
?>
<form action="sample13_2.php" method="post">
<p>Example:</p>
<input type="hidden" name="submitted" value="yes" />
Our Name: <input type="text" name="ourname" maxlength="150" /><br />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
<?php
}
?>
</div>
</body>
</html>

Validating Form Input


In attacks on websites, one of the biggest issues is attacking forms directly. To ensure a suitable
submission of form data, validation is key. We have many ways to validate a form and many form
elements to consider. Generally, we need to determine what qualities we want a piece of data to adhere to
and then ensure that the submitted data comes in the correct form. If the data comes in a format that is not
P.Ravi Theja,Asst.Professor,GIST,Nellore
102

Email:raviteja.pannem@gmail.com

Page

to our liking, we must be ready to take care of this. The following example shows a few examples of
form validation using PHP.
The Code
<html >
<title>Sample </title>
</head>
<body>
<div style="width: 500px; text-align: left;">
<?php
//Function to determine a valid e-mail address.
function validemail($email){
return preg_match("/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])
+(.[a-zA-Z0-9_-]+)+[a-zA-Z0-9_-]$/",$email);
}
//Handle the incoming data.
if ($_POST['submitted'] == "yes"){
$goodtogo = true;
//Validate the name.
try {
if (trim ($_POST['ourname']) == ""){
$goodtogo = false;
throw new exception ("Sorry, we must enter our name.<br />");
}
} catch (exception $e) {
echo $e->getmessage();
}
//Validate the select box.
try {
if ($_POST['myselection'] == "nogo"){
$goodtogo = false;
throw new exception ("Please make a selection.<br />");
}
} catch (exception $e) {
echo $e->getmessage();
}
//And lastly, validate for a proper e-mail addy.
try {
if (!validemail (trim ($_POST['ouremail']))){
$goodtogo = false;
throw new exception ("Please enter a valid email address.<br />");
}
}
catch (exception $e) {
echo $e->getmessage();
}
//Now, if there were no errors, we can output the results.
P.Ravi Theja,Asst.Professor,GIST,Nellore
103

Email:raviteja.pannem@gmail.com

Page

if ($goodtogo){
echo "Our Name: " . $_POST['ourname'] . "<br />";
echo "Our Selection: " . $_POST['myselection'] . "<br />";
echo "Our Email Address: " . $_POST['ouremail'] . "<br />";
}
?><br /><a href="sample13_3.php">Try Again</a><br /><?php
}
?>
<?php
//Show the forms only if we don't already have a submittal.
if ($_POST['submitted'] != "yes"){
?>
<form action="sample.php" method="post">
<p>Example :</p>
<input type="hidden" name="submitted" value="yes" />
Our Name: <input type="text" name="ourname"
maxlength="150" /><br /><br />
Selection:
<select name="myselection">
<option value="nogo">make a selection...</option>
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
<option value="3">Choice 3</option>
</select><br /><br />
Our Email: <input type="text" name="ouremail" maxlength="150" /><br />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
<?php
}
?>
</div>
</body>
</html>

Working with Multipage Forms


Sometimes we will need to collect values from more than one page. We do this by providing forms on
more than one page, we can separate blocks of information and thus create an ergonomic experience for
the user. The problem, therefore, is how to get values from each page onto the next page and finally to the
processing script. We can solve this problem and use the hidden input form type. When each page loads,
we merely load the values from the previous pages into hidden form elements and submit them.
Page1.php
<html >
<title>page1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div style="width: 500px; text-align: left;">
<form action=" page2.php" method="post">
<p>Page 1 Data Collection:</p>
<input type="hidden" name="submitted" value="yes" />
P.Ravi Theja,Asst.Professor,GIST,Nellore
104

Email:raviteja.pannem@gmail.com

Page

Our Name: <input type="text" name="uname" maxlength="150" /><br /><br />


<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
</div>
</body>
</html>
Page2.php
<html >
<title> Page 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div style="width: 500px; text-align: left;">
<form action=" page3.php" method="post">
<p>Page 2 Data Collection:</p>
Phone No:<input type="text" name="phno" maxlength="150" /><br /><br />
<input type="hidden" name="uname" value="<?php echo $_POST['uname']; ?>" />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
</div>
</body>
</html>

Page3.php
<html >
<title> Page 3</title>
</head>
<body>
<div style="width: 500px; text-align: left;">
<form action=" page4.php" method="post">
<p>Page 3 Data Collection:</p>
Our Email: <input type="text" name="email" maxlength="150" /><br />
<input type="hidden" name="uname" value="<?php echo $_POST['ourname']; ?>" />
<input type="hidden" name="phno value="<?php echo _POST['ourselection']; ?>" />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
</div>
</body>
</html>
Page4.php
<html >
<title> Page 4</title>
</head>
<body>
<div style="width: 500px; text-align: left;">
<?php
//Display the results.
P.Ravi Theja,Asst.Professor,GIST,Nellore
105

Email:raviteja.pannem@gmail.com

Page

echo "Our Name: " . $_POST['uname'] . "<br />";


echo "Our Selection: " . $_POST['phno'] . "<br />";
echo "Our Email: " . $_POST['email'] . "<br />";
?>
<a href=" page1.php">Try Again</a>
</div>
</body></html>

Preventing Multiple Submissions of a Form


One possible occurrence that happens often is that users become impatient when waiting for our script to
do what it is doing, and hence they click the submit button on a form repeatedly. This can wreak havoc on
our script because, while the user may not see anything happening, our script is probably going ahead
with whatever it has been programmed to do. Of particular danger are credit card number submittals. If a
user continually hits the submit button on a credit card submittal form, their card may be charged
multiple times if the developer has not taken the time to validate against such an eventuality.
Preventing Multiple Submissions on the Server Side
We can deal with multiple submittal validation in two ways. The first occurs on the server. Server side
refers to a script located on the server that is receiving the data; client side is more browsers related.
Because the server has no actual access to the browser, validating multiple submissions can be a bit
trickier. While we can accomplish this goal in a number of ways from a server-side perspective, we prefer
to use a session-based method. Basically, once the submit button has been clicked; the server logs the
request from the individual user. If the user attempts to resubmit a request, the script notes a request is
already in motion from this user and denies the subsequent request. Once the script has finished
processing, the session is unset, and we have no more worries
Multi.php
<?php
/*** begin the session ***/
session_start();
/*** create the form token ***/
$form_token = uniqid();
/*** add the form token to the session ***/
$_SESSION['form_token'] = $form_token;
?>
<html >
<head>
<title>My Form</title>
</head>
<body>
<form action="submit.php" method="post">
<dl>
<dt>Name</dt>
<dd>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<input type="text" name="first_name" />
P.Ravi Theja,Asst.Professor,GIST,Nellore
106

Email:raviteja.pannem@gmail.com

Page

</dd>
</dl>
<p><input type="submit" value="Add Name" /></p>
</form>
</body>
</html>
Submit.php
<?php
/*** begin the session ***/
session_start();
/*** check all expected variables are set ***/
if(!isset($_POST['first_name'], $_POST['form_token'], $_SESSION['form_token']))
{
$message = 'Invalid Submission';
}
/*** check the form tokens match ***/
elseif($_POST['form_token'] != $_SESSION['form_token'])
{
$message = 'Access denied';
}
/*** check the input name is a string between 1 and 50 characters ***/
elseif(strlen(trim($_POST['first_name'])) == 0 || strlen(trim($_POST['first_name'])) > 50)
{
$message = 'Invalid First Name';
}
else
{
/*** assign the input ***/
$message = 'Thank you ' . $first_name;
/*** unset the form token in the session ***/
unset( $_SESSION['form_token']);
}
?>
<html >
<head>
<title>My Form</title>
</head>
<body>
<h1>Submit Page</h1>
<p><?php echo $message; ?></p>
</body>
</html>
P.Ravi Theja,Asst.Professor,GIST,Nellore
107

Email:raviteja.pannem@gmail.com

Page

Preventing Multiple Submissions on the Client Side


Handling multiple submittals from a client-side perspective is actually much simpler than doing it on the
server side. With well-placed JavaScript, we can ensure that the browser will not let the submittal go
through more than once. The problem with this method, of course, is that JavaScript is not always
foolproof because of the users ability to turn it off. That being said, however, most users will have
JavaScript enabled, so this script will likely work for 90 percent of web users. The following example
uses JavaScript to cut off multiple submittals from a client-side (browser) level.
<html >
<title>Sample </title>
<script language="javascript" type="text/javascript">
function checkandsubmit() {
//Disable the submit button.
document.test.submitbut.disabled = true;
//Then submit the form.
document.test.submit();
}
</script>
</head>
<body>
<div style="width: 500px; text-align: left;">
<form action="sample.php" method="post" name="test" onsubmit="return checkandsubmit ()">
<p>Example:</p>
<input type="hidden" name="submitted" value="yes" />
Your Name: <input type="text" name="yourname" maxlength="150" /><br />
<input type="submit" value="Submit" style="margin-top: 10px;" id="submitbut" name"submitbut" />
</form>
</div>
</body>
</html>

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

P.Ravi Theja,Asst.Professor,GIST,Nellore
108

Email:raviteja.pannem@gmail.com

Page

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"];
}
?>
By using the global PHP $_FILES array we 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, we 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))
{
P.Ravi Theja,Asst.Professor,GIST,Nellore
109

Email:raviteja.pannem@gmail.com

Page

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"];
}
}
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 disappear 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. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
P.Ravi Theja,Asst.Professor,GIST,Nellore
110

Email:raviteja.pannem@gmail.com

Page

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

UNIT-VII

Using MySQL Databases


MySQL Database
One great thing about MySQL is that it can be scaled down to support embedded database applications.
Perhaps it is because of this reputation that many people believe that MySQL can only handle small to
medium-sized systems.
The truth is that MySQL is the de-facto standard database for web sites that support huge volumes of
both data and end users (like Friendster, Yahoo, and Google).
Connecting to a MySQL Database
Before you can access and work with 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

server name

Optional. Specifies the server to connect to. Default value is "localhost:3306"

P.Ravi Theja,Asst.Professor,GIST,Nellore
111

Email:raviteja.pannem@gmail.com

Page

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

Note: There are more available parameters, but the ones listed above are the most important.
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","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
?>
else
{
echo unable to connect to the database;
The mysql_connect() method and pass it the connection information. This gives you access to any
databases that are assigned to the root user. If you were to supply an invalid login set, we would generate
an error.
Closing a Connection
The connection will be closed as soon as 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);
?>

Querying the Database


SQL allows you to perform common functionality such as insert, which allows us to enter data into a
row; alter, which allows us to change the format of a table; select, which allows us to return a row set
from a table in the database; and delete, which allows us to remove a row in the database.
We do our SQLqueries in MySQL environment.
To perform a query in PHP, you can use the function mysql_query(). It allows us to perform a myriad of
SQL functions and is quite simple to use. The prototype for
mysql_query() is as follows:
resource mysql_query ( string query [, resource link_identifier] )
P.Ravi Theja,Asst.Professor,GIST,Nellore
112

Email:raviteja.pannem@gmail.com

Page

Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
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
In the following example we create a database called "TEJA":
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE TEJA ",$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 database table in MySQL.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
We must add the CREATE TABLE statement to the mysql_query() function to execute the command.
Example
The following example shows how you can create a table named "person", with three columns. The
column names will be "FirstName", "LastName" and "Age":
The following example shows how you can create a table named "person", with three columns. The
column names will be "FirstName", "LastName" and "Age":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
P.Ravi Theja,Asst.Professor,GIST,Nellore
113

Email:raviteja.pannem@gmail.com

Page

{
die('Could not connect: ' . mysql_error());
}
// Create table in TEJA database
mysql_select_db("TEJA", $con);
$sql = "CREATE TABLE person
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
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).

MySQL Data Types


Below are the different MySQL data types that can be used:
Numeric Data Types

Description

int(size)
smallint(size)
tinyint(size)
mediumint(size)
bigint(size)

Hold integers only. The maximum number of digits can be specified


in the size parameter

decimal(size,d)
double(size,d)
float(size,d)

Hold numbers with fractions. The maximum number of digits can


be specified in the size parameter. The maximum number of digits
to the right of the decimal is specified in the d parameter

Textual Data Types

Description

char(size)

Holds a fixed length string (can contain letters, numbers, and


special characters). The fixed size is specified in parenthesis

varchar(size)

Holds a variable length string (can contain letters, numbers, and


special characters). The maximum size is specified in parenthesis

Tinytext

Holds a variable string with a maximum length of 255 characters

text
blob

Holds a variable string with a maximum length of 65535


characters

mediumtext
mediumblob

Holds a variable string with a maximum length of 16777215


characters

longtext
longblob

Holds a variable string with a maximum length of 4294967295


characters

Date Data Types

Description

P.Ravi Theja,Asst.Professor,GIST,Nellore
114

Email:raviteja.pannem@gmail.com

Page

date(yyyy-mm-dd)
datetime(yyyy-mm-ddhh:mm:ss)
timestamp(yyyymmddhhmmss)
time(hh:mm:ss)

Holds date and/or time

Misc. Data Types

Description

enum(value1,value2,ect)

ENUM is short for ENUMERATED list. Can store one of up to


65535 values listed within the ( ) brackets. If a value is inserted
that is not in the list, a blank value will be inserted

Set

SET is similar to ENUM. However, SET can have up to 64 list


items and can store more than one choice

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 primary key field is always indexed. There is no exception to this rule! You must index the primary
key field so the database engine can quickly locate rows based on the key's value.
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 person
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);

Insert Data into a Database Table


The INSERT INTO statement is used to add new records to a database table.
Syntax
INSERT INTO table_name
VALUES (value1, value2,....)
You can also specify the columns where you want to insert the data:
INSERT INTO table_name (column1, column2,...)
P.Ravi Theja,Asst.Professor,GIST,Nellore
115

Email:raviteja.pannem@gmail.com

Page

VALUES (value1,value2,....)
Note: SQL statements are not case sensitive. INSERT INTO is the same as insert into.
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.
Example
In the previous chapter we created a table named "Person", 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 "Person" table:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("TEJA", $con);
mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO person 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 "Person" 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>
</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 database table.
Below is the code in the "insert.php" page:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
P.Ravi Theja,Asst.Professor,GIST,Nellore
116

Email:raviteja.pannem@gmail.com

Page

mysql_select_db("TEJA", $con);
$sql="INSERT INTO person (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)
?>

Select Data from a Database Table


The SELECT statement is used to select data from a database.
Syntax
SELECT column_name(s)
FROM table_name
Note: SQL statements are not case sensitive. SELECT is the same as select.
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 "Person" table (The * character selects all of the
data in the table):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("TEJA", $con);
$result = mysql_query("SELECT * FROM person");
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. Next,
we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each
subsequent 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:
P.Ravi Theja,Asst.Professor,GIST,Nellore
117

Email:raviteja.pannem@gmail.com

Page

Ravi Teja
Glenn Hams
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","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("TEJA", $con);
$result = mysql_query("SELECT * FROM person");
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>";
}
echo "</table>";
mysql_close($con);
?>
The output of the code above will be:
Firstname

Lastname

Ravi

Teja

Glenn

Hams

The WHERE clause


To select only data that matches a specific criteria, add a WHERE clause to the SELECT statement.
Syntax
SELECT column FROM table
WHERE column operator value
The following operators can be used with the WHERE clause:
Operator
P.Ravi Theja,Asst.Professor,GIST,Nellore
118

Description
Email:raviteja.pannem@gmail.com

Page

Equal

!=

Not equal

>

Greater than

<

Less than

>=

Greater than or equal

<=

Less than or equal

BETWEEN

Between an inclusive range

LIKE

Search for a pattern

Note: SQL statements are not case sensitive. WHERE is the same as where.
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 will select all rows from the "Person" table, where FirstName='Ravi':
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("TEJA", $con);
$result = mysql_query("SELECT * FROM person
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
The output of the code above will be:
Ravi Teja

The ORDER BY Keyword


The ORDER BY keyword is used to sort the data in a record set.
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name
Note: SQL statements are not case sensitive. ORDER BY is the same as order by.
P.Ravi Theja,Asst.Professor,GIST,Nellore
119

Email:raviteja.pannem@gmail.com

Page

Example
The following example selects all the data stored in the "Person" table, and sorts the result by the "Age"
column:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("TEJA", $con);
$result = mysql_query("SELECT * FROM person 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:
Ravi Teja 25
Glenn Hams 22
Sort Ascending or Descending
If you use the ORDER BY keyword, the sort-order of the recordset is ascending by default (1 before 9
and "a" before "p").
Use the DESC keyword to specify a descending sort-order (9 before 1 and "p" before "a"):
SELECT column_name(s)
FROM table_name
ORDER BY column_name DESC
Order by Two Columns
It is 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 identical:
SELECT column_name(s)
FROM table_name
ORDER BY column_name1, column_name2
Update Data In a Database
The UPDATE statement is used to modify data in a database table.
Syntax
UPDATE table_name
SET column_name = new_value
P.Ravi Theja,Asst.Professor,GIST,Nellore
120

Email:raviteja.pannem@gmail.com

Page

WHERE column_name = some_value


Note: SQL statements are not case sensitive. UPDATE is the same as update.
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 "Person". Here is how it looks:
FirstName

LastName

Age

Ravi

Teja

25

Glenn

Hams

22

FirstName

LastName

Age

Ravi

Teja

26

Glenn

Hams

22

The following example updates some data in the "Person" table:


<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("TEJA", $con);
mysql_query("UPDATE Person SET Age = '26'
WHERE FirstName = 'Ravi' AND LastName = 'Teja'");
mysql_close($con);
?>
After the update, the "Person" table will look like this:

Delete Data in a Database


The DELETE FROM statement is used to delete records from a database table.
Syntax
DELETE FROM table_name
WHERE column_name = some_value
Note: SQL statements are not case sensitive. DELETE FROM is the same as delete from.
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 "Person". Here is how it looks:
FirstName

LastName

Age

Ravi

Teja

26

Glenn

Hams

22

P.Ravi Theja,Asst.Professor,GIST,Nellore
121

Email:raviteja.pannem@gmail.com

Page

The following example deletes all the records in the "Person" table where LastName=Teja':
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("TEJA", $con);
mysql_query("DELETE FROM Person WHERE LastName='Teja'");
mysql_close($con);
?>
After the deletion, the table will look like this:
FirstName

LastName

Age

Glenn

Hams

22

P.Ravi Theja,Asst.Professor,GIST,Nellore
122

Email:raviteja.pannem@gmail.com

Page

Você também pode gostar