Web Technologies Material
Web Technologies Material
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:[email protected]
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:[email protected]
Page 2
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected]
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.
Email:[email protected]
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.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected]
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
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected]
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:[email protected]
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:
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:[email protected]
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:[email protected]
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:[email protected] Page 10
Email:[email protected] Page 11
Tick check boxes install Apache as Service and MySQl as service and click install
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page 12
After installation get completed it will check for necessary port for Apache and MySQL
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page 13
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:[email protected] 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:[email protected] 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:[email protected] Page 16
WAMP Installation
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page 17
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page 18
After installation Click on next button then installation process get completed
In left corner we get wamp control panel click on that.
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page 19
Email:[email protected] Page 20
Among the methods given in Table, GET and POST are the most frequently used. POST was originally
designed for tasks such as posting a news article to a newsgroup. Its most common use now is to send
form data from a browser to a server, along with a request to execute a program on the server that will
process the data.
Following the first line of an HTTP communication is any number of header fields, most of which are
optional. The format of a header field is the field name followed by a colon and the value of the field.
There are four categories of 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:[email protected] 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
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:[email protected] 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:[email protected] 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:[email protected] Page 24
ASP is significantly slower than PHP, for obvious reasons. Primarily, PHP runs on notoriously fast
Unix and Linux servers which have for years outpaced 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:[email protected] Page 25
PHP 4
On May 22, 2000, roughly 18 months after the first official announcement of the new development effort,
PHP 4.0 was released. Many considered the 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:[email protected] 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:[email protected] Page 27
PHP comes bundled with most Linux distributions. we should download the latest stable version from the
PHP Web site. To decrease download time, choose from 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.
Email:[email protected] Page 28
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] 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.
Email:[email protected] Page 30
%>cd ../php-X_XX
%>./configure --with-apxs2=APACHE_INSTALL_DIR/bin/apxs [other options]
%>make
%>make install
5. PHP comes bundled with a configuration file that controls many aspects of PHPs behavior. This file is
known as php.ini, but it was originally named php.ini-dist. We need to copy this file to its appropriate
location and rename it php.ini. The later section Configuring PHP examines php.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:[email protected] 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:[email protected] Page 32
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 = [email protected]
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 "[email protected]", change the code to:
[mail function]
SMTP = mail.example.com
smtp_port = 25
sendmail_from = [email protected]
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] 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:[email protected] 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:[email protected] 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 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:[email protected] 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:[email protected] 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:[email protected] 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
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] 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:[email protected] 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:[email protected] Page 41
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:
Email:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] Page 51
...
$blender = new Appliance;
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:[email protected] Page 52
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:[email protected] 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 (.=)
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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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:[email protected] 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>
Email:[email protected] Page 60
Email:[email protected] 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...
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] 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:[email protected] Page 63
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] 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:[email protected] 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:[email protected] Page 66
Email:[email protected] Page 67
Email:[email protected] Page 68
<?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:[email protected] 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";
}
}
Email:[email protected] 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:[email protected] 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
Email:[email protected] 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:[email protected] 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
Email:[email protected] 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:[email protected] 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:[email protected] Page 76
Email:[email protected] 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:[email protected] 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:[email protected] Page 79
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:[email protected] Page 80
Sample.php:
<?php
if (trim ($_POST['wername']) == "")
{
header ("Location: sample12_5.html");
exit;
}
echo $_POST['wername'];
?>
Email:[email protected] 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
Email:[email protected] Page 82
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:[email protected] Page 83
Email:[email protected] Page 84
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:[email protected] 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:[email protected] 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:[email protected] Page 87
Email:[email protected] 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.
?>
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] 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
Day
---
---
01 to 31
1 to 31
l (lowercase
'L')
0 through 365
Week
---
---
Month
---
---
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page 90
format
character
Description
01 through 12
1 through 12
28 through 31
Year
---
---
1 if it is a leap year, 0
otherwise.
Examples: 99 or 03
Time
---
---
am or pm
AM or PM
1 through 12
0 through 23
01 through 12
00 through 23
00 to 59
00 through 59
Example: 54321
Timezone
---
---
I (capital i)
Example: +0200
Example: +02:00
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page 91
format
character
Description
Timezone abbreviation
Full
Date/Time
---
---
2004-02-12T15:19:21+00:00
<?php
// Assuming today is: March 10th, 2012, 5:16:18 pm
$today
$today
$today
$today
$today
ripm01
$today
$today
$today
$today
?>
=
=
=
=
=
//
//
//
//
//
=
=
=
=
//
//
//
//
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,
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:[email protected] 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:
tomorrow:
P.Ravi Theja,Asst.Professor,GIST,Nellore
Email:[email protected] Page 93
yesterday:
Thursday:
this Thursday:
last Thursday:
+2 hours:
-1 month:
+10 minutes:
30 seconds:
last month:
last year:
2 weeks ago:
Email:[email protected] Page 94
Email:[email protected] Page 95
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:[email protected] Page 96
constant
description
example
SUNFUNCS_RET_STRING
16:46
SUNFUNCS_RET_DOUBLE
16.78243132
SUNFUNCS_RET_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:[email protected] 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
Email:[email protected] Page 98
UNIT-VI
Email:[email protected] 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.
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.
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:[email protected]
Page
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.
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:[email protected]
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>
Email:[email protected]
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:[email protected]
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>
Email:[email protected]
Page
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:[email protected]
Page
Email:[email protected]
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:[email protected]
Page
P.Ravi Theja,Asst.Professor,GIST,Nellore
108
Email:[email protected]
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:[email protected]
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:[email protected]
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
Description
server name
P.Ravi Theja,Asst.Professor,GIST,Nellore
111
Email:[email protected]
Page
username
Optional. Specifies the username to log in with. Default value is the name of the user that
owns the server process
password
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);
?>
Email:[email protected]
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:[email protected]
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).
Description
int(size)
smallint(size)
tinyint(size)
mediumint(size)
bigint(size)
decimal(size,d)
double(size,d)
float(size,d)
Description
char(size)
varchar(size)
Tinytext
text
blob
mediumtext
mediumblob
longtext
longblob
Description
P.Ravi Theja,Asst.Professor,GIST,Nellore
114
Email:[email protected]
Page
date(yyyy-mm-dd)
datetime(yyyy-mm-ddhh:mm:ss)
timestamp(yyyymmddhhmmss)
time(hh:mm:ss)
Description
enum(value1,value2,ect)
Set
Email:[email protected]
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);
?>
Email:[email protected]
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)
?>
Email:[email protected]
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
Description
Email:[email protected]
Page
Equal
!=
Not equal
>
Greater than
<
Less than
>=
<=
BETWEEN
LIKE
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
Email:[email protected]
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:[email protected]
Page
LastName
Age
Ravi
Teja
25
Glenn
Hams
22
FirstName
LastName
Age
Ravi
Teja
26
Glenn
Hams
22
LastName
Age
Ravi
Teja
26
Glenn
Hams
22
P.Ravi Theja,Asst.Professor,GIST,Nellore
121
Email:[email protected]
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:[email protected]
Page