lamprevised
lamprevised
LAMP TECHNOLOGY
BCA V Semester
Compiled by
Prof. Sridhara Acharya
SIMS, Mangalore
--------------
2015-16
Srinivas Institute of Management Studies BCA Vsem
LAMP TECHNOLOGY
CONTENTS
Unit 1
Chapter Number Page Number
1 Linux Operating System 4
1.1 Introduction
1.2 Linux Distribution
1.3 Download and Install
1.4 Decissions
1.5 Linux Partition Size
1.6 Accounts
1.7 Basic Unix
1.8 Owner, Group Permission, ownership
1.9 Processes and Demons
1.10 Commands
1.11 Basic File System Essentials
Unit 2
2 Apache Web Server 17
2.1 Linux Distribution
2.2 Apache Installation
2.3 Starting and stopping Web server Apache
2.4 <Directory>, Access control, URL Pathnames
2.5 MIME types
2.6 CGI Files
2.7 Automatic directory indexing
2.8 Authentication and log files
3 Virtual Hosting 24
3.1 IP Address Virtual Host
3.2 Name based Virtual Host
3.3 Dynamic Virtual Hosting
3.4 Server side includes
3.5 Assignment Questions on Unit 2
Unit 3
4 HTML/XHTML and HTTP 28
4.1 Basics review
4.2 PHP and the web server architecture model
4.3 Over view of PHP capabilities
4.4 CGI vs Shared object Model
5 MYSQL Database Server 34
5.1 Installation- pre compiled packages and post installed configuration
5.2 Post installed trouble shooting
1
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Unit 4
8 Files and directory operations 90
8.1 File and directory access operations
8.2 Processing HTML from input from the user
8.3 Creating a dynamic HTML Form with PHP
8.4 Using GET, POST, SESSION and COOKIES variable
2
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Chapter 1.
LINUX OPERATING SYSTEM
1.1 Introduction
Linux is an Open Source version of Unix developed by Linus Torvalds to port Unix to the
Intel x86 processor. This made Unix available on the most ubiquitous computer hardware
that has ever existed, and therefore available to almost everyone. Linux has since been ported
to almost every processor and function one could imagine, including game boxes, personal
digital assistants (PDAs), personal digital video recorders, and IBM mainframes, expanding
the original concept of Unix for x86 to Unix for everything. Linux isn't the only version of
Unix available to most people (also notable are the various BSD variants, also Open Source),
but it's by far the most popular.
In this chapter, we discuss how to get Linux, how to install it, and some of the basic
commands. Here we are caught in a familiar bind: If you are familiar with Linux, this will be
too simplistic, and if you are not, it will not be nearly enough. If you are in the former
category, you can skim or skip this chapter; if the latter, we try to point you in the right
direction.
Although Linux is free and Open Source, and you can download individual packages and
compile them all yourself, that's rather masochistic. Most people get Linux as a pac1ql.ged
distribution from a vendor, either by paying for a CD or downloading it. The distribution
route is fast and easy and resolves many hardware and software dependency issues (though
not all of them). Paying for a CD both gives the prospective user the documentation and
usually some degree of technical support, and supports the companies that propagate and
improve Linux. Many individuals, organizations, and companies make Linux distributions
for different purposes and with different philosophies. The following is a quick list of the
main ones, in no particular order (see www.distrowatch.com to keep up with them):
Red Hat This is probably the most popular Linux distribution in the United States. Red Hat
has worked with a number of vendors to provide Red Hat Linux preinstalled on PCs. Red Hat
is feature and application rich, and easy-for new Linux users to learn. Red Hat created the
Red Hat Package Manager (RPM) system, a system similar to apt to keep software up to
date, which is used by many distributions. The Red Hat up2date mechanism provides a
package dependency resolution similar to apt-get. For what it's worth, apt-get has been ported
to Red Hat, and you can update your distribution in that manner. Red Hat boasts a number of
high-profile Open Source software employees.
Slackware One of the first Linux distributions, Slackware is still used by many hard-core
Linux users; It contains user-friendly interfaces similar to other Linux distributions, but it
3
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
generally goes for "power over pretty." SuSE The most popular distribution in Europe,
especially Germany, SuSE has become more popular in the United States as well. It uses a
variant of the RPM package format and includes a sophisticated system configuration tool
called YaST (Yet another Setup Tool) to make administration easier. SuSE supports many
types of hardware and many configurations not available in other distributions, and includes
several security scripts and tools that can be run to inform you of problems.
Mandrake Mandrake took the Red Hat distribution, added an easy-to-use installer, and
changed the default desktop from Gnome to KDE, thus arriving at one of the more popular
distributions. It has a reputation for being easy to use, easy to install, and cutting-edge.
There's also lmmunix, a distribution based on Red Hat, which is hardened for security. The
NSA also makes a secure version of Linux. Because we have to choose something, Red Hat
Linux version 7 will be our base. Aside from the usual holy wars about Linux distributions
or Linux versus BSD, we've found that Red Hat is the one you're most likely to be able to
walk into a store in the United Sates and buy. Although this is not an endorsement,2 Red Hat
does a good job of keeping up to date with bug fixes and security issues and making its
distribution relatively painless. Many resources are available for Red Hat, and one of our
favourites, the Unix System Administration Handbook, Third Edition [Nemeth+ 01]' now
includes Red Hat Linux explicitly, which is very nice since Red Hat, like all the other
distributions of Linux, does things slightly different from other Unices.
The directory structure referenced here is based on Red Hat. The Red Hat structure differs
slightly from the File system Hierarchy Standard, aka Linux File system Standard
(www.pathname.com/fhs/) . All the configurations and directory structures we discuss in this
book are based on the standard Red Hat RPMs.
However, you can use any other Linux distributi9n or package manager if you prefer,
including ./configure; make; make install. If you've already installed a non-Red Hat Linux,
you should be able to translate these instructions to another distribution with little difficulty.
The easiest way to get this free software is to: pony up a sawbuck or two for a shrink-
wrapped CD with instructions-this might seem an oxymoron, but it's a capitalistic society. Or
get it from www. cheapbytes.com for a very minimal cost. Because most of this is Open
Source software, you don't have to buy any of it-you can download it for free. But free might
not be cheap, depending on how you value your time. Failing that, you can download the
software from Red Hat (or whatever distribution you choose) or a mirror under your existing
non-Linux software and burn a CD or do a network install. Having a CD around is nice for
reinstalling, fixing problems, having a backup, and other necessary tasks.
One issue to consider if you aren't purchasing a distribution with a CD, printed instructions,
and so forth, is that the computer won't have a network connection or browser or printer
while you are doing the installation, so you have to be prepared and have access to the
instructions, documentation, etc., beforehand-it's not always feasible to stop in the middle
because you don't know the answer to a question. Once you start installing Linux, you can't
click on the browser (on that machine--if you have another no problem) and look up the
answer-the browser won't be installed yet.
4
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
We're going assume you have a CD in hand, because otherwise the options branch too much
for us to cover all the complications, and if you aren't installing from a CD, you aren't going
to take our advice anyway you know what you are doing.
Once you have the software in hand, you can run the installer (whether Red Hat or not, most
are fairly painless these days), following either the instructions you printed or the book you
got with your distribution. Having learned from experience, we highly recommend keeping
an old fashioned paper logbook of your setup, starting with how your disk is partitioned. If
you have to tweak some odd configuration, you'll be very happy two years from now when
you're installing your new system on your 5GHz Pentium 9 if you've written it down and
very frustrated if you haven't especially when you're trying to recover your system after that
hard disk that you got for $50 from Joe Bob's Computer Hut dies. The utility of keeping it on
paper should be obvious, as is the canard about computers making for a paperless society.
Back up your important data, and keep track of changes made to system configuration files
somewhere other than on your system.
It's also a really good idea to make a copy of any configuration file before you change it,
renaming it with the date, and placing it out of the install path. Extensions-.orig, .bak, etc. are
not recommended because many install scripts use those to save the files they're about to
overwrite. Consider keeping a directory in your home path with the latest version of working
configuration files, in addition to backups and paper copies, or better yet, on another
computer entirely. You could also use something more technical for this purpose, such as
CVS.
1.4 Decisions
Before you start the installation, you must make some important decisions about your
installation. Do you want to have a dual Windows/Linux boot or run strictly Linux? If you
dual boot, do you want to put both operating systems on one disk, or do you want to install
another hard drive for Linux? Is this going to be a workstation in addition to being a server,
or strictly a command line interface (CLI) accessed server?
One advantage of dual booting is that you get to keep all the Windows software you already
paid for, because of the non monopolistic practices that make it easy for you to buy a
computer without a Microsoft operating system preinstalled (sarcasm alert!). With dual
booting, you can even run Windows under an emulator in Linux. But if this machine is to be
a full-time web server, not a user machine, you may want to keep things simple and go with
Linux as your only operating system. This does make installation much simpler.
As always, before you start any major system task like this, back up Back your system up-
you can lose everything when you start playing with fundamental things like disk partitions.
At the very least, copy your important files to another computer, a CD-ROM, a tape,' or an
.external disk. Therefore, there are several installation options.
Single disk, Linux boot Simple enough-just insert the installation disk and follow the
instructions. Single disk, dual boot In a dual boot system, Windows must reside on its own
partition-not least because Windows and Linux use incompatible file systems. The Red Hat
installer comes with a disk utility, called fips that allows you to shrink the existing Windows
partition of your disk without destroying the existing data, though the disk must be
5
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
A program called Partition Magic does alter NTFS partitions, but it costs between $50 and
$75, so you are left with the choice of ponying up for the software or just getting a cheap
10GB or 20GB disk and installing Linux on that. The cost is roughly the same, plus or minus
an Andy Jackson. We recommend the latter, if your computer supports an extra hard drive.
Same cost, much simpler, more flexible.
Multiple disks, dual boot If you decide to go with the two-disk method, Linux installation is
simple enough. When you boot from the installation disk, it asks which disk you want to
install on, hda or hdb (or something similar). Your Windows software will be on the former,
so pick the latter and install Linux on that.
You should create several partitions for Linux (see Table 1.1). You could use a single
partition, but your life as a sysadmin and webmaster will be easier if you create several. The
advantage to having several partitions is that it provides a degree of protection against filling
up a disk, or accidently overwriting data, or should you need to reinstall the system, losing
user data. It also makes for simpler upgrades because the system software will be installed
into its own partition and will leave /home alone.
Red Hat uses software called Disk Druid to partition the disk during installation. You can
have the Red Hat installer automatically partition the disk if you wish.
Assuming you have a 10GB disk, we recommend making these partitions. If you have a
larger disk, you could add extra partitions for such things as /web and /root, and add more
space in /home and /usr.
After you've backed up and partitioned, the next thing to do is insert the Linux installation
CD and reboot from it. Follow the directions included with your distribution, and install
everything. You probably have no need for Samba, cluster software, multiple language
support, etc., but you can turn this stuff off and remove it later after reading HLE. It's
possible to install Linux using a very small amount of disk space (a few megabytes), but this
requires some know-how, and if you really have gigabytes of disk space, it's not worth doing-
it isn't Linux that'll be using it up, it's your MP3s. You do need to install the development
packages so that you will have a compiler environment because some of the software that
will be installed later will have to be compiled. If this is to be a user machine in addition to a
web server, install one or more of the graphical user interfaces (GUIs). KDE or Gnome.
In the best of all possible worlds, the web server itself would be separate from the machine
on which code is developed and tested, and the web server would run only the necessary
daemons to be a secure server, and all the X 'Windows and Gnome/KDE GUI and
development code would be necessary only on the development machine.
For most of us. however, the server and development box will be one and the same meaning
that you should install everything you want on this one machine.
1.6 Accouns
The installer will ask you to create at least one account, the root account. The root account, or
superuser, is the godlike figure of the system. Just like the real Supreme Being, as countless
explanatory tales from Paradise Lost onward tell, it's easy to use your rootly powers for
destructive purposes, and it requires care to use your superpowers only for good-that is, you
can screw up your system royally if you rm -rf * under the # prompt. At this time. it would be
convenient to create at least one other user account for yourself and an account for any other
user of the system. Other users can be added later. As a general practice, you should not log
in as root but as a user; then su to a root account.
The Red Hat installer creates several other users for specific purposes:
Apache will be owned by the apache user, Squid under squid, etc. This is part of a strategy to
keep powerful daemons that run on low ports walled away from the root account. Ports
numbered under 1024 are owned by root, and by accessing one of these ports, a cracker could
compromise your system. Apache runs on port 80 and thus must have this sort of access, but
it can be walled off from an actual root account by running under its own user, which has
certain powers but isn't root.
7
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
This section should provide a basic overview of Unix for someone who doesn't know
anything about it. If you do, you can skip to the next chapter. If you don't, this will only be a
snippet of knowledge, and you need to get a real Unix book to put by your bedside, alongside
the USAH (which covers this ground most excellently), HLE, and Unix Power Tools
[Powers+ 02] (hereafter called UPT). The goal here is not to explain every nuance of Unix
but to make the first-time user aware and knowledgeable enough to ask the right questions.
We hope that sometimes simply a mention is enough to get you to ask the right questions.
First, Linux is primarily used through a command line interface. You open a terminal shell
and enter text commands on the command line interface You probably installed one or more
of the Linux desktop graphical interfaces, Gnome or KDE. When your Linux system boots, it
will probably come up with a login to this graphical interface. After logging in to the GUI as
a normal user, you can open a terminal shell (look in the menus), work from there, and log in
as root from there. Once you open a terminal shell, you can get information on any of the
commands by using the Unix man (short for manual) system. The command man man gives
you information on how man works. Each of these pages gives information on the valid
options for the command. Some provide examples and pointers' to other, similar commands.
If you don't know the name of the command, you can do man -k commandname. This often
gets you much more information than you want, so you can pipe it through a pager such as
less or more: man -k commandname I 1ess.
Most Linux distributions come with some sort of desktop to give you that Apple/Windows
feel, and these work fine even better than Apple/ Windows in some respects, because as x
and XP have yet to come up with anything equivalent to the multiple virtual desktops that are
standard in Gnome and KDE. But since much of the work that has to be done in website
development and administration has to be done as root, it's still better to do most things in a
shell through the command line. You can move files and folders (in Unix, folders are really
direct pries) via a graphical window interface, but you typically don't want to do this as root.
It's better to learn how to drive a stick-you have more control.
Everything in Unix is a file, and each 01 the files has associated with it an owner and a
group. If you do an 1s - 1 in a directory, you might see something like Table 2.2, though it
won't have column titles like those shown here.
The long listing shows that J. Random Luser (jrl) owns three files (junk.txt, foo.html, and
bar.cgi) and one directory (bin) in this directory. The permissions of junk. txt are such that
the owner of the file (j rl) and the group associated with the file (j rl) can read and write the
file, and the rest of the world can read it. The file foo. html is a bit more private, and only j rl
can alter it, though staff members may view its contents. The world cannot see it at all. The
file bar. cgi appears to be an executable, and J. Random Luser can change it, staff can view
it, and' both staff and he can execute it.
8
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The ownership of a file can be changed using the chown command, and the permissions
changed via chmod. A typical thing to do would be chmod a+x bar. cgi, which would change
the permissions to allow all to execute it. Similarly, one could change the permissions via
chmod go- r junk. txt to allow only the owner to read the file.
Old-school Unix types like to use the octal numeric mode to change file permissions, thus
leading to such commands as chmod 666 foo. bar. The value666 is an octal number
representing the three permission groups: user/group/world. If the value of one of the groups
is 6, the permissions are "readon, write on, execute off," represented as rw-. Therefore, 666
represents rw-rw-rw-. The value 751 would be rwxr-x--x. Other file attributes, such as the
sticky bit, can be changed with these commands; use man chmod to see all the possibilities.
A process is an executing (i.e., running) instance of a program. Processes are also frequently
referred to as tasks.
A program is an executable file that is held in storage. Storage refers to devices or media that can
retain data for relatively long periods of time (e.g., years or even decades), such as hard disk
drives (HDDs), optical disks and magnetic tape. This contrasts with memory, whose contents can
be accessed (i.e., read and written to) at extremely high speeds but which are retained only
temporarily (i.e., while in use or only as long as the power supply remains on).
A program is a passive entity until it is launched, and a process can be thought of as a program in
action. Processes are dynamic entities in that they are constantly changing as their machine code
instructions are executed by the CPU. Each process consists of (1) system resources that are
allocated to it, (2) a section of memory, (3) security attributes (such as its owner and its set of
permissions) and (4) the processor state.
An alternative definition of a process is the execution context of a running program, i.e., all of
the activity in the current time slot in the CPU. A time slot, also called a time slice or a quantum,
is the length of time that each process is permitted to run in the CPU until it is preempted (i.e.,
replaced) by another process in a time sharing operating system.
A daemon is a type of program on Unix-like operating systems that runs unobtrusively in the
background, rather than under the direct control of a user, waiting to be activated by the
occurrence of a specific event or condition.
9
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Unix-like systems typically run numerous daemons, mainly to accommodate requests for
services from other computers on a network, but also to respond to other programs and to
hardware activity. Examples of actions or conditions that can trigger daemons into activity are a
specific time or date, passage of a specified time interval, a file landing in a particular directory,
receipt of an e-mail or a Web request made through a particular communication line. It is not
necessary that the perpetrator of the action or condition be aware that a daemon is listening,
although programs frequently will perform an action only because they are aware that they will
implicitly arouse a daemon.
Daemons are usually instantiated as processes. A process is an executing (i.e., running) instance
of a program. Processes are managed by the kernel (i.e., the core of the operating system), which
assigns each a unique process identification number (PID).
1.10 Commnads
Next we provide a short introduction to commands we use in this book, and we leave you to man
to find out more about them. Raising your awareness is all we can achieve here. Also, be aware
that any problem you've had, any trick you seek to accomplish has probably been tried by
someone else. USAH, UPT, and/or Google can ease your efforts.
Man The first command to know is man, your friend and helper, the manual command-that is,
show the manual for this command, the options, and typical usage. Use it. The command man
man is a good place to start. Most man pages have usage examples and further links at the
bottom. You can use man -k foo when you don't know exactly what you are looking for.
cd Change directory. It operates either on a fixed path (cd /usr/share/misc) or on a relative path
(cd bi n. would take you to the bi n directory below your current working directory, if that
directory exists). The following are a few standard shortcuts:
ls List the files in the current directory. The options 15 -1, 15 -a, and ls- F are very useful.
grep Find a string within a file. The command grep -i string *. Text finds all the occurrences of
string regardless of case (-i) in any or all of the files ending with . text (* is a wildcarff) in the
current directory. The grep command has amazing power, and it is well worth spending some
time learning regular expressions to use it.
10
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
more Page through a file without using an editor. It also can be used to view multiple pages-for
example, locate config | more generates pages and pages of output that normally scroll past, but
when piped (the | character is a pipe) through more, the output shows up one terminal screen at a
time. A similar command is 1ess.
find
will display the pathnames of all files in the current directory and all subdirectories. The
commands
find . -print
find -print
find .
do the exact same thing. Here's an example find command using a search criterion and the
default action:
This will search the whole system for any files named foo and display their pathnames. Here we
are using the criterion -name with the argument foo to tell find to perform a name search for the
filename foo. The output might look like this:
/home/wpollock/foo
/home/ua02/foo
/tmp/foo
cat stands for "catenate." It reads data from files, and outputs their contents. It is the simplest
way to display the contents of a file at the command line.
Syntax
Examples
Reads and outputs the contents, in sequence, of file1.txt and file2.txt, respectively.
Syntax
Description
less is a program similar to more, but it has many more features. less does not have to read the
entire input file before starting, so with large input files it starts up faster than text editors like vi.
less uses termcap (or terminfo on some systems), so it can run on a variety of terminals. There
is even limited support for hardcopy terminals. On a hardcopy terminal, lines which should be
printed at the top of the screen are prefixed with a caret ("^").
Commands are based on both more and vi. Commands may be preceded by a decimal number,
called N in the descriptions below. The number is used by some commands, as indicated.
Syntax
example
sort -r file.txt
/usr/bin The main executables are here. This should be in your path.
/bin Boot-level executables are here, and this should be in your path.
/usr/sbin The main superuser commands. This should be in the root path but not in a user path.
/sbin Basic boot-level superuser commands. Ditto.
/usr/1ib Contains dynamic libraries and static files for the 'executables in /usr/bin and /usr/sbin.
12
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
/tmp Temporary files are stored here. In most Unices, cron runs a daemon that eventually deletes
anything here, and some systems delete these files every time the system is rebooted.
/var/tmp/ Another place for temporary files, which will not be deleted automatically.
/var/spool Mail, printer, and other spools. Mail that is sent to J. Random Luser comes to
/var/spool /mai1/jrl until J. Random transfers the mail to another directory.
/var/log Log files. These files keep track of what's gone on your system. Do a tail -50
/var/log/maillog to see an example, or do a less /var /1og/boot.log. Log watch and other tripwire
security programs watch these files to see what's going on-so should you. What is written here is
determined by /ete/syslog. conf.
/boot Basic Linux boot files. The Linux kernel lives here. The kernel is the basic executable that
runs everything else in Linux. Generally, the kernel is very stable, and the average non-power
user never has to deal with it (unless you want to get into the fun business of compiling your own
kernels).
/etc System wide configuration files. For example, Apache configuration files are under
/etc/httpd/conf/ and send mail is under /etc/mail/. Studying /etc is an excellent start to a
sysadmin education.
/etc/init.d A link to /etc/rc.d/init. d, and the place where the startup configuration files live. For
instance, this is where you can execute /etc/init.d/httpd status.
/mnt Mount points for removable media (CD-ROMs, floppies). Do a man mount.
/dev The Unix device directory, which yOll will probably not have to deal with until you have
some advanced problem. such as your mouse not working.
/proc The Unix process directory, which acts as an interface to the internal data structures of the
kernel. Some of these are readable directories and you can do such things as cat/proc/uptime. Try
it and see what happens.
13
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
15
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Unit 2
Chapter 2 Apache Web Server
2.1 Linux Distribution
A Linux distribution (often called distro for short) is an operating system built on top of the
Linux kernel and often around a package management system. Linux distributions are usually
targeted at common hardware like personal computers, but are available for a wide variety of
systems up to the most powerful supercomputers (for example, Rocks Cluster Distribution
distribution), or down to small embedded systems (for example, OpenWrt distribution). Most
distributions come ready to use and pre-compiled for a specific instruction set, while others (such
as Gentoo) are distributed in source code form and compiled locally during installation.
Linux distributions are primarily based on free and open-source software, at least partially; that
part includes the Linux kernel and usually a very large collection of software of all sorts. They
usually come with a graphical user interface, by adapting and packaging free and open-source
implementations of one or more of the available windowing systems, the most common being
the X Window System. Usually, Linux distributions include some proprietary software that may
be optional, such as binary blobs required for some device drivers. Because of the huge
availability of software, distributions have taken a wide variety of forms – including fully
featured desktop, server, laptop, netbook, mobile phone, and tablet operating systems, as well as
minimal environments typically for use in embedded systems.
There are currently over six hundred Linux distributions; over three hundred of those are in
active development, constantly being revised and improved. One can distinguish between
commercially backed distributions, such as Fedora (Red Hat), openSUSE (SUSE), Ubuntu
(Canonical Ltd.), and Mandriva Linux (Mandriva), and entirely community-driven distributions,
such as Debian, Slackware, Gentoo and Arch Linux.
When Rob McCool, who had developed NCSA HTTPd, left NCSA in 1994, the project fizzled
out Since the source code was publicly available, many people using it had developed their own
bug fixes and additional features that they needed for their own sites. The patches were shared
via Usenet, without any centralized place for collecting and distributing these patches.
Brian Behlendorf and Cliff Skolnick had put up a mailing list and Brain set up a CVS
(Concurrent Versioning System) tree, now anyone who wanted to could contribute new features
and bug fixes. This led to place where a group of developers could collect and distribute the
patches and bug fixes. Thus came into existence - Apache.
Since it was a patchy Web server, the name APACHE got from A PAtCHy sErver. The Apache
version 0.6.2 was released in April 1995. Currently there are two versions of Apache available
the first is 1.3.X.XX-X the most popular and tried and test and completely stable. Apache.org,
the Apache website indicates that there will be no enhancements made to 1.3.X.XX-X on bug
fixes done. The second is 2.0.X.XX, which is the latest version of Apache, which is being
constantly being bug fixed and enhanced (when creating this material). Either version can be use
as a full fledged production Web Server when required.
16
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Apache is the hottest Web server for the internet. Apache is the world's largest used Web server.
Apache is a freely available Web server. It can be downloaded from http://www.apache.org.
Getting started:
This release fixes security problems described in CAN-2003-0789 and CAN-2003-0542. It also
contains bug fixes and some new features. For details see the Official Announcement and the
CHANGES 2.0 list
Apache2.0 add-in modules are not compatible with Apache 1.3 modules. If third party add-in
modules are currently being run using Apache 1.3, obtain new modules written for Apache 2.0
from that third party before attempting to upgrade from Apache 1.3 to Apache 2.0.
It is essential that integrity of the downloaded Files are verified using the PGP or MDS
signatures. Please read Verifying Apache HTIP Server Releases for more information on why
Apache releases should be verified.
The PGP signatures can be verified using PGP or GPG. First download the KEYS as well as the
asc signature file for the particular distribution. Make sure these Files are obtained from the main
distribution directory, rather than from a mirror. Then verify the signatures using:
% pgpk -a KEYS
% pgpv apache_1.3.24.tar.gz.asc
Or
% pgp -ka KEYS
% pgp apache_1.3.24.tar.gz.asc
Or
% gpg --import KEYS
% gpg --verify apache_1.3.24.tar.gz.asc
httpd-2.0.48.tar.gz is signed by Sander Striker DE88SDD3
httpd-1.3.29.tar.gz is signed by Jim Jagielski 08C97SES
Alternatively, verify the MDS signature on the files. A unix program called mdS or mdSsum is
included in many Unix distributions. It is also available as part of GNU Textutils
Installation procedure:
Login as root. Make a directory /apache2. Copy the downloaded File httpd-2.0A8.tar.gz there.
Once done, its time to unzip the File and extract its contents. To do so:
17
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
# gunzip httpd-2.0.48.tar.gz
The httpd-2.0.48.tar.gz file gets replaced by httpd-2.0.48.tar in the same directory. The content of
httpd-2.0.48.tar must be extracted after which the actual install process can begin. To extract the
content of httpd-2.0.48.tar:
The extraction process creates a directory called httpd-2.0.48 into which the contents of the tar
file are extracted. This is just one level below the japache2 subdirectory. Change to this sub-
directory:
# cd httpd-2.0.48
For Example:
# ./configure --prefix=/usr/local/apache2
The configuration routine commences. The time taken depends upon the amount of memory
available and the processor speed. After the configuration runs successfully:
# make
# make install
#/usr/local/apache2/bin/apachectl start
# /usr/local/apache2/bin/apachectl stop
The main configuration file for configuring Apache is httpd.conf, which contains directives
written in plain text. The location of this file is set at compile-time. When required this may be
overridden with the -f command line flag.
18
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The srm.conf and access.conf files can also be used to configure Apache. Other configuration
files may be added and their instructions passed to Apache by using the Include directive
followed the path that points to where the additional configuration files are.
Any directive may be placed in any of these configuration files. Apache is pretty flexible like
that. Changes made to the main configuration files are only recognized by Apache when it is
Started or restarted. If any configuration file is actually a directory, Apache will enter that
directory and parse any files (and sub-directories) found there as configuration files.
Apache works best if there is only one configuration file used and all its directives are placed in
that file (i:e. httpd.conf). Apache also reads a file containing document mime types. This
filename is set by the Types Config directive, and is mime.types by default.
Apache configuration files contain one directive per line. If a directive must continue onto the
next line use back-slash '\' as the last character on the previous line. Directives in configuration
files are case-insensitive, but arguments to directives are often case-sensitive. Any line beginning
with a hash (#) character is ignored. Blank lines and white spaces before a directive are ignored.
Configuration files can be checked for syntax errors without starting the server by using
apachectl configest or the -t command line option.
Global Environment
Server Type standalone The two server types are standalone and inetd. Usually it is always
standalone. Setting it to inetd causes a new server to be started to handle every incoming HTTP
request, which will die as soon as the request is served. This makes things slower because of re-
reading the configuration file and the overhead of server startup with every request.
This sets the absolute path to the server directory. Generally, the argument 'of Server Root
should be the path to where Apache is installed.
ErrorLog /logs/error_log
The various directives that end in Log control indicate whether log files exist at all. Directives
also indicate exactly where the log files exist in the Linux file system.
LockFile /var/run/httpd.lock
The LockFile directive sets the path to the lockfile used when Apache is compiled. This directive
should normally be left at its default value.
PidFile /var/run/httpd.pid
19
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
It is a file in which the server should record its process identification number when it starts.
It is a file used to store internal server process information. Not air architectures require this But
if local architecture does (This will be known because this file will be created when Apache run)
then ensure that no two invocations of Apache share the same Scoreboardfile.
Timeout 300
Indicates the number of seconds before Apach.ereceives and senqs a time out.
KeepAlive On
Indicates whether or not to allow persistent connections (more than one request per connection
MaxKeepAliveRequests 100
Indicates the maximum number of requests to allow during a persistent connection. Set it to
allow an unlimited amount. It is recommended that this number is set high, for maximum
performance.
KeepAliveTimeout 15
Indicates the number of seconds to wait for the next request from the same client on the same
connection.
MinSpareServers 5
MaxSpareServers 20
Indicates the Server-pool size regulation. Rather than making a user guess how many server
processes are required, Apache dynamically adapts to the load it sees - that is, it tries to maintain
enough server processes to handle the current load, plus a few spare servers to handle transient
load spikes (e.g., multiple simultaneous requests from a single Netscape browser).
It does this by periodically checking how many servers are waiting for a request If there are
fewer than MinSpareServers, it creates a new spare. If there are more than MaxSpareServers,
some of the spares die off. The default values are probably OK for most sites.
StartServers 8
Port 80
This indicates the port on which the server should run on.
20
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The Web server's user and group values are denoted by the User and Group settings. This should
be set to User ID and Group ID that the server will use to process requests. If the server runs as
root, some hacker could exploit the privilege. Normally, people want to run Apache as an
underprivileged user for security reasons. On Linux, this can be done, by setting both to nobody.
ServerAdmin root@localhost
Accepts the Email address, where problems with the server should be e-mailed. This address
appears on some server-generated pages, such as error documents.
ServerName localhost
This sets the hostname the server will return. Set the name of the server using the ServerName
directive. This is especially useful when the computer has multiple names or IP addresses.
DocumentRoot /var/www/html
This indicates the absolute path of the document tree, which is the top directory from which
Apache will serve files. The DocumentRoot is the root of the Web tree and it defaults to
/usr/local/apache2/htdocs. Assuming that Apache is installed in/usr/local/apche2/, this can be
changed if required.
UserDir public_html
Indicates the name of the directory that is appended onto a user's home directory if a N user
request is received. This is the directly relative to a local user's home directory where that user
can put public HTML documents. Documents placed in that directory will be available as:
http://servemame/~Nusername
After these settings are complete, HTML pages can be published, directories configured so that
users can set up personal Web pages, and some form of dynamic or interactive content provided
for.
21
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Apache allows for decentralized management of configuration via special files placed inside the
web tree. The special files are usually called htaccess, but any name can be specified in the
AccessFlleName directive.
Directives placed in .htaccess files apply to the directory where the file is placed, and all sub
directories. .htaccess files follow the same syntax as main configuration files. Since htaccessfiles
are read on every request, changes made in these files take immediate effect, What directives
may be placed in .htaccess files can be controlled by configuring the AllowOverride directive in
the main configuration file httpd.conf.
22
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Chapter 3
VIRTUAL HOSTING
23
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
find the entry WS200 corresponding to the IP 192.168.0.200. Replacews200 with the name of
the interface, (in this case reviews). Restart named using the command:
# /etc/rc.d/init.d/named restart
Alternately, create an entry in the /etc/hosts file for the virtual interface. Now any computer on
the network should be able to ping the interface by name.
The final step is to create a file to add the interface and route automatically at boot time, Create a
file (For example: rc.virtual) in the /etc/rc.d directory and add the two lines to it. The first line of
the script should be #!/bin/sh. Mark it executable (chmod +x rc.virtual), and edit the file rc.local
in the same directory. At the last line of that file, add the line /etc/rc.d/rc.virtual. That will ensure
that rc.virtual is run automatically at bootup. Similarly add as many virtual domains as required.
Add the correct domain name to the virtual host tag and specify a document root path, which
defines where the HTML files are stored for that host. The correct permissions on this directory
are important. Make sure that the root directory is universally· readable. For example:
<VirtualHost 192.168.0.200>
ServerAdminwebmaster@lansmart.com
DocumentRoot /var/www/lansmart
</VirtuaIHost>
24
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
source files on Linux. The tool called apxs (APache eXtension) tool, allows the building and
installation of an Apache extension module during source compile time.
Alternatively Apache modules can be dynamically loaded via Apache's httpd.conf configuration
file, also known as DSO (Dynamic Shared Object) loading, which is a fine feature of Apache.
DSO allows the extension of the features and capabilities of Apache by adding specific modules
on demand, without recompiling Apache's binary executable. Use the Load Module directive
placed within Apache's httpd.conf file to load a Dynamic Shared Object into Apache Web Server
namespace at startup time.
For all this to work properly the O/s platform on which Apache is installed has to support DSO
features and the Apache httpd binary has to be built (i.e. compiled from source) along with the
mod_so module.
After making any changes to the httpd.conf ensure to restart the apache server to apply
new changes. This can be done by:
# /usr/local/apache2/bin/apachectl stop
# /usr/local/apache2/bin/apachectl start
25
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
26
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Unit 3
Chapter 4
HTML/XHTML and HTTP
4.1 Basics review
Most multi user, commercial applications are developed using an Ethernet backbone in mind as
the framework to which connects multiple computers together on the network. This is because
the commercial application requires multiple users each having their own computing resources
connected together on a network to run successfully.
The commercial applications are built using either two-tier or three-tier, Client/Server
architecture. The architecture of the commercial application determines the tools used to craft the
application. Standard two-tier, Client/Server architecture based commercial applications can be
crafted from homogeneous tools such as Oracle Developer 2000 (Forms 6) as the client side
forms development tool and Oracle 9i as the database engine of choice run in the server.
Alternatively, a heterogeneous tool set can be chosen such as Microsoft's Visual Basic 6 as the
client side forms development tool and Oracle9i as the database engine of choice run in the
server.
What remains unchanged is that each client on which the application's data entry forms will run
will be connected to the sever using an Ethernet backbone.
Database Server
The Ethernet backbone could be cabled, fiber optic, wireless, infrared, with hub, without hub and
so depending on whether the network topology should be bus or star.
In this type of architecture the clients and servers are always connected to one another when
switched on and active.
This architecture undergoes a huge change when the very same commercial applications are
mounted on the Internet. This is because, while the Internet uses TCPIP to connect computers
across the Internet, it's application development architecture does not permit the clients and
servers from being always connected.
27
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
When the Internet is used as a framework for connecting clients and servers, an application must
run on a client called a Web browser, (Internet Explorer Mozilla, Netscape Communicator Opera
are examples) another application must run on the servers appropriately called a Web server
(Internet Information Server (IIS), Apache, Java Web Server are examples)
It is these two applications that setup a link between themselves when a client and server have to
talk to one another. The most common protocol (language of communication) used to set up this
link is HTIP. The two applications i.e. Web browsers and Web servers communicate using a
Request /Response paradigm. What this really means is that when a Web browser wishes to
communicate with a Web server it broadcasts such a request blindly to port 80 on which all Web
servers listen. The broadcast will contain the IP address of the Web server with which the Web
browser wishes to communicate. All Web servers hear the broadcast but only the Web server
whose IP is contained within the broadcast replies.
Once the Web server replies it immediately terminates the link setup between the Web browser
and itself. In fact the Web server immediately forgets which Web browser contacted it, hence the
term Reply/Response communication paradigm.
This really means that there is no permanent link setup between the client and server computers.
Any link setup is valid only for the duration of the Request and Reply paradigm. Primarily this is
done to decongest network bandwidth and permit the millions of Web Browsers and Web servers
to communicate freely and effectively on the Internet.
As can be seen this really is a huge change from a standard wired Ethernet backbone used for
commercial applications.
As mentioned earlier: the architecture (framework) of the commercial application determines the
tools used to craft the application. The framework of the Internet has changed the architecture on
which the commercial application runs hence the tools used to craft the commercial application
must change.
Essentially, all the forms of the commercial application must run in a Web browser. They cannot
run in an executable at operating system level as was done in the past. The natural language of
everyWeb browser is HTML, hence a commercial application's forms must be crafted in HTML
only then will they run successfully in a Web browser.
The applications HTML based forms will have to be served by a Web server, on demand by a
client via a Web browser. Hence all the data entry forms will be located in one place i.e. the
computer on which the Web server software runs.
Since the communication paradigm between Web browser and Web server on the Internet is
Reply/Response, additional coding will have to be done to take care of continuity of a session
between the client and the server. Something taken totally for granted on a wired Ethernet
backbone.
28
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Hence, some data validation can be done at HTML form level and most other validation will
have to be done by bringing the data back to the server and validating it there and if invalid
returning an error message back to Web browser from where the data originated and discarding
the data at the server. All this necessarily has to be bound to extra program code that manages
sessions between the client's Web browser and the Web server.
Finally, valid application data needs to be stored in a database management system. The database
system can be mounted on the same server on which the Web server software runs or the
database management system could be mounted on a separate server and communications setup
between the server on which the Web server software runs and the server on which the database
management software runs.
All Web servers cannot talk directly to any database management system. Hence a Web server's
functionality has to be extended by plugging in appropriate modules that will permit effective
communication between the Web server and the DBMS. All Web server software permits this.
The DBMS specific, plug in modules, for' a Web server is generally provided by the DBMS
vendors themselves.
The most commonly used Web server is Apache. Available for download, completely free, from
http://www.apache.org. The latest, stable release of Apache being release 2.X.X. The most
commonly used database management system used is MySQL (or Postgre SQL) available from
http://www.mysql.com. The latest stable, production release, at the time of creating this material
being 4.X.X. Apache and either MySQL or Postgre SQL are from the open source domain,
which means they can be freely downloaded and used. These are fully functional products.
Since the Web server and the database management system are both open source products, its
reasonable to assume that they will run best with an open source operating system such as Linux.
There are several flavours of Linux available for free download and use, the commonly known
flavours are, RedHat, Mandrake, SuSE, Debain and so on. This frame work, i.e. open source
operating system, Web server and DBMS needs to be mounted on appropriate hardware. A list of
supported hardware is available on all the o/s. web sites.
Web Server And DBMS Middleware Finally, never forget that Apache Web server's
functionality has to be extended to allow it to communicate freely with a DBMS.
PHP is one such module (others are PERL, Python and so on). This is freely downloadable from
http://www.php.net. At the time of creating this material the latest stable production, version of
PHP was 4.X.X. Hence, the server side framework that allows the creation of Internet based
commercial applications will be, Linux as the 0/5 of choice, Apache as the Web server, MySQL
the DBMS of choice and PHP and PERL the programming environment of choice (i.e.
L.A.M.P.P).
The most commonly used framework on the Internet, for building interactive, database driven
websites is L.A.M.P.P. as mentioned earlier this is an acronym for Linux, Apache, MySQL, PHP
and PERL. Here the operating system of the framework is Linux. Common flavors being
RedHat, Mandrake, SuSE, Debian and so on. The Web server is Apache. MySQL is a production
quality, Linux based, RDBMS in which user information is stored and finally, PHP and PERL
are the programming
29
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Environment of choice that acts as a go between Apache Web server and the MySQL database
engine, which protects user information.
Apache is the Web server responsible for responding to requests received from cIient browsers
for information. MySQL is the database in which such information is stored. PHP and PERL are
the middleware, programming environment of choice that can:
1. Respond to such information requests being processed by the Web server
Apache
2. Access the MySQL database tables where the information requested is
stored
3. Convert this to HTML
4. Return this HTML to the client browser via Apache Web server
Now that the request/response paradigm of the Internet and the framework on which this
paradigm can be implemented is known, it is necessary to actually create such a framework
on a Linux box to work on.
This will involve the installation (and configuration, where applicable) of:
Linux as an O/S. (RedHat Linux 9 is the 0/5 of choice)
• ApacheWeb Server
• MySQL
• PHP
• PERL
30
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Thus servicing the client's request for information. All this is because a Web server
(Apache2) cannot communicate directly with a database management system (MySQL)
hence PHP and PERL program codes plays the role of mediator.
Figure shown below depicts what happens during the request and execution of a CGI
program. The web server recognizes a CGI request by the location of the thing requested (or
by the file name extension). For instance, if we load the URL www.example.com/cgi-
bin/a.cgi into the browser, the web server contacted, www.example.com. receives a request
such as the following:
GET /cgi-bin/a.cgi HTTP/1.0
The server notices that the directory that contains the thing requested is cgi -bin. It is
configured to take the object requested, here a. cgi, which is a program located on the server,
and execute it as a stand-alone program. The program generates standard output (in Perl, we
would use print()). This output is in an important format: a header, a blank line, and the body.
31
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
displays the data that follows as plain text. If the header contains Content type: text/html, the
browser treats the data that follows as
HTML and renders it appropriately. And this is what is really important: Programs must output
the header, then a blank line, and then the content to be displayed. The blank line is essential-it
tells the browser that the header is complete and the body is about to begin.
It is easy to see the header, blank line, and body output from a CGI program by using a shell and
telnetting to a server. The following code is an example of connecting to a CGI program named
test. cgi, which simply prints the content type, the blank line, and some important text:
$ telnet www.not_a_real_web_server.com 80
Trying 1.299.299.1
Connected to www.not_a_real_web_server.com (1.299.299.1)
Escape character is '-'.
GET /cgi-bin/test.cgi HTTP/l.0
HTTP/I.1 200 OK
Date: Thu, 17 Jan 2002 19:57:05 GMT
Server: Acme Web Server Version 0.001b
Connection: close
Content-Type: text/plain
There's more than one way to do it.
Connection closed by foreign host.
When the server accepts the connection, it tells the client so. Then we see the HTTP request:
followed by a blank line. The webserver prints some header stuff, including the content type that
the program prints, followed by a blank line that the program prints, followed by an important
philosophical assertion in the next-to-last line. Then, had we used a browser instead of a telnet
session ,it would have taken the information in the header and the body and rendered it
appropriately based on the content type in the header. Again, that blank line that separates the
header and the body is important. If it is not present, a server error will result.
32
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Chapter 5
MYSQL DATABASE SERVER
5.1 Installation- pre compiled packages and post installed configuration
MySQL is a Relational DataBase Mangement System (RDBMS) that is great for energizing a
Web site, managing personal data, or any of the everyday uses of a database.
MySQL is hugely popular with both the open source and Web-based communities and can
essentially be considered the de facto standard for database software. One reason could be that it
is a real solution, appealing to various kinds of database users and administrators. Another reason
for MySQL's success is that it is widely accessible. The Gnu Public License (GPL) is a standard
licensing agreement for participating in open source software. It dictates that software (in this
case, MySQL) can be used at no cost, as long as any source code containing the GPL product is
also made available under GPL. MySQL is freely available in the net for download.
However, MySQL is great. The system is ideally suited for PHP, Perl Python, and Pascal
developers due to syntax support that is familiar to those languages. If the technical skills exist in
the organization of adoption, take advantage of having access to the source code of MySQL to
make MySQL do whatever is required of it.
If the organization is just getting into DBMS, (perhaps having worked with compilers and flat
find before), MySQL does nicely. It's widely supported, supports forgiving syntax, and has
error messaging. The manual is accurate and up to date, and, again, a variety of GUls are
available, including MySQLCC, phpMyAdmin, MySQLdb for Python, MySQL Ruby, and many
more.
MySQL is geared towards Selecting and Updating data over Inserting and Deleting. It is a good
choice for data storage and reference, but it is not necessarily the best for creating and deleting
tables on the fly. For the Web, it is almost perfect for tracking users and creating dynamic page
on the fly.
Getting Started
The simplest way to install MySQL on a Linux box is to use RPMs. These will be found on the
MySQL web site http://www.mysql.com.
Navigate to the Downloads page on the website. Scroll down the page and midway, just below
Mirrors, will be the heading MySQL Database server and Standard Clients below this head the
current production release of MySQL and future Alpha and future releases of MySQL are
available.
This will navigate to the MySQL <Current Production Number> Downloads page
Scroll half way down this page until the Linux x86 RPM downloads head is reached.
Download all the RPMs in the group under this head. They are required for a complete install of
MySQL on a Linux box.
33
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
After downloading the required RPM packages before installing the same we have to check out
the earlier version of the same if exists. To do so use the following command
Protocol version 10
34
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
If there is any earlier version present in the server we have to remove using the following
command
This will forcibly remove the RPM without the requirement of removing the dependencies.
MySQL-4.0MySQL-server-4.0.17-0.i386.rpm
MySQL-client-4.0.17-0.i386.rpm
MySQL-shared-4.0.17-0.i386.rpm
MySQL-shared-compat-4.0.17-0.i386.rpm
MySQL-embedded-4.0.17-0.i386.rpm
MySQL -devel-4.0.17-0.i386.rpm
MySQL-bench-4.0.17-0.i386.rpm
MySQL-Max-4.0.17-0.i386.rpm
This installs MySQL database engine. During this procedure the system will ask the password
for the MySQL root user. We have to provide the same and only the administrator should know
the password.
If the error displayed at RPM install time cannot be corrected easily, then log onto the MySQL
website and first refer to their MySQL install FAQs. Often this will provide a solution. If that
does not work then log onto any of the MySQL forums on the Internet and post the following
details:
o The Operating System, and its version number
o The full name of the MySQL RPM causing the error
o Details of the error message displayed
And request a solution.
During the installation the following directories will be created
To show the database created inside MYSQL the show command is used.
Syntax of the same is as follows
Mysql> SHOW DATABASES;
This query will show all the databases present inside.
36
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
SQL commands and sub commands (in the previous example, CREATE is a command;
DATABASE is its subcommand) are case-insensitive. The name of the database (and table and
field) are case sensitive. It's a matter of style whether one uses uppercase or lowercase, but
traditionally the SQL commands are distinguished by uppercase.
One way to think of a database is as a container for related tables. A table is a collection of rows,
each row holding data for one record. Each record containing chunks of information called
fields.
USE Command
Before anything can be done with the newly created database, MySQL has to connect to it.
That’s done with the USE command.
It appears that the table was created properly (it says OK after all), but this can be checked by
executing the SHOWTABLES command. If an error is made, the table can be removed with
DROP TABLE.
When a database in MySQL is created, a directory is created with the same name as the database
(people, in this example):
SHOW TABLES is used to show all the tables present in the database.
The syntax of the same is
37
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
SMALLINT -32768 to 32767 for signed and 0 to 65535 for unsigned integer.
MEDIUMINT -8388608 to 8388607 for signed and 0 to 16777215 for unsigned
INT or INTEGER -2147483648 to 2147483647 for signed and
0 to 429467295 for unsigned.
BIGINT -9223372036854775808 to 9223372036854775807 for signed and
0 to 18446744073709551615 for unsigned
Floating point numbers
FLOAT
DOUBLE
REAL same as FLOAT
DECIMAL
NUMERIC Same as DECIMAL
38
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The command SHOW COLUMNS FROM age_information· gives the same information as
DESCRIBE age_ information; but DESCRIBE involves less typing.
INSERT Command
This command is used to insert the records into the table created using CREATE command. The
syntax of the same is
Mysql> INSERT INTO name of the table VALUES (the necessary values);
mysql> INSERT INTO age_information
-> (1astname , firstname, age)
-> VALUES ('Wall', 'Larry', 46);
Query OK, 1 row affected (0.00 sec)
The syntax of the command is INSERT INTO, followed by the table in which to insert, a list
within parentheses of the fields into which information is to be inserted, and the qualifier
VALUES followed by the list of values in parentheses in the same order as the respective fields.
SELECT command
SELECT selects records from the database. When this command is executed from the command
line, MySQL prints all the records that match the query.
The simplest use of SELECT is shown in this example
39
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The * means "show values for all fields in the table"; FROM specifies the table from which to
extract the information.
The previous output shows that the record for Larry Wall was added successfully.
There are many ways to use the SELECT command-it's very flexible.
First, the table based on 1astname:
40
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
41
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
42
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Be sure to use that WHERE clause; otherwise if we had only entered UPDATE age_information
SET age = 47, all the records in the database would have been given the age of 47!
Although this might be good news for some people in these records (how often have the old-
timers said "Oh, to be 47 years old again"-OK, probably not), it might be shocking news to
others.
This method works, but it requires the database to know that Larry is 46, turning 47. Instead of
keeping track of this, for Larry's next birthday we simply increment his age:
43
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
44
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Administrative Details
All these examples have been executed as the root MySQL user, which, as we might imagine, is
not optimal from a security standpoint. A better practice is to create a MySQL user who can
create and update tables as needed.
45
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
First, as a security measure, change the MySQL root password when logging in to the server:
Now when mysql executes, a password must be provided using the –p switch. Here is what
would happen if we forgot the -p:
S mysql -u root
ERROR 1045: Access denied for user: 'root@localhost' (Using password: NO)
Try again using –p When prompted for the password, enter the one given
previously:
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Command send with ; or \g.
Your MySQL connection id is 15 to server version: 3.23.36
Type 'help;' or '\h' for help. Type '\c' to clear the buffer
mysq1>
Doing all the SQL queries in the people database as the MySQL root user is a Bad Idea (see HLE
if you want proof of this). So let's create a new user. This involves modifying the database
named mysql, which contains all the administrative information for the MySQL server, so first
we use the mysql database and then grant privileges for a new user:
The user apache (the same user that runs the webserver) is being granted the ability to do most
everything within the database, including being able to delete entries in tables within the people
database. However, apache cannot delete the people database only entries within the tables in the
database. The user apache can access the people database from 1oca 1host only (instead of being
able to log in over the network from another machine).
The IDENTIFIED BY clause in the SQL command sets the apache user's password to
LampIsCool. Setting the password is necessary only the first time permissions are granted for
46
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
this user-later, when the apache user is given permissions in other databases, the password
doesn't need to be reset.
To verify that these changes were made, log in as apache:
47
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Chapter 6
PHP
• Only install either the static module or the dynamic one. Do not install both.
• If there are shared libraries installed on Linux, make sure the location of these shared
libraries is listed in the /etc/ld.so.conf file.
Download the latest stable version of PHP from http://www.php.net/downloads.php
Latest stableVersion Of PHP Complete Source Code
PHP4.3.4 (tar.bz2) [3,686Kb] - 03 November 2003
md5: b9dd601863e08eS2e3c4dSe02c2627cf
PHP4.3.4 (tar.gz) [4,S22Kb] - 03 November 2003
md5: cOe7f7388fadacbf4948391c6d93dcSe
See the ChangeLog for a complete list of changes, or the release notes for more Information on
this particular release. Daily snapshots are also available from snaps. php.net (not intended for
production use!). The file chosen for download is php-4.3.4.tar.gz
6.2 Installing PHP from binary package
First the user has to login as a root
Create a directory /php4
Copy the downloaded file php-4.3.4.tar.gz here
# gunzip php-4.3.4.tar.gz
# cd php-4.3.4
48
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Make sure to specify the version of apxs that is actually installed on the system and not the one
that is in the apache source tarball.
For example:
# ./configure --with-mysql--with-apxs2=/usr/local/apache2/bin/apxs
--with-mysql specifies that PHP should be build with MySQL support.
--with-apxs specifies the path to apache web server's apxs script.
The configuration routine commences. The time taken depends upon the amount of memory
available and the processor speed. After the configuration runs successfully:
# make.
Finally run the:
# make install
This completes the installation of PHP4
The php files will be served up after restarting the apache server.
49
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Chapter 7
PHP LANGUAGE CORE
$name= 'Jitesh';
The variable name is on the left of the = sign (i.e. assignment operator) and the value of the
variable is on its right. Here 18 is assigned as a value to the variable $age:
$age= 18;
There are several different types of variables. The integer and string types have already been
demonstrated.
NUMBERS
Dealing with numbers is easy with PHP. Just use them as required. All the normal rules about
precedence apply:
$a = 4;
$b = 7;
$c=2+3*$a+5*$b; ( This is evaluated as 2+(3'*4)+(5*7) = 49 )
Everything works as expected. Any variable is automatically substituted with its value. This is
done before the new value is stored in the variable on the left side of the = sign. This means that
something like this can be done:
$a = 5;
$b = 10;
$a= (2 * $a + 5)/$b; ( Evaluated as $a (2*5+5) /10= 1.5)
STRINGS
To assign a string to a variable, the string must be enclosed in quotes. Either single quotes(' ) or
double quotes ( " ) can be used. The kind of quotes chosen depends on the string being worked
with in a given situation.
There are some differences between the two types of quotes. The following code should
demonstrate the differences:
50
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$first_name = 'Chhaya';
$greeting1 = "Hello, my first name is $first_name. ";
echo $greeting1;
$Iast_name = 'Bankar';
$greeting2 = 'Hello, my last name is $Iast_name. ';
echo $greeting2;
When double quotes are used, PHP performs what is known as variable expansion. That
means that PHP expands (substitutes) $first_name with it's value. The result is that the string
stored in $greetingl is Hello, my name is Chhaya with variable expansion being done on the
variable $firsCname. When assigning a value to the variable $greeting2, using single quotes,
PHP does not do any variable expansion hence $greeting2 ends up with Hello, my last name is
$Iast_name, (i.e. anything enclosed in single quotes is treated as a string constant and not to be
changed in anyway by PHP)
Double quotes also expand other special characters such as newline characters (\n)
This means that the following string:
echo “Chhaya\nBankar";
will look like this when rendered in the client browser:
Chhaya
Bankar
The echo statement just outputs the string after it to the Web browser. As said earlier there's no
trace of the PHP code, but notice that there's a newline character between the two words. The
newline character can only be seen in the source code of the HTML page, because the Web
browser treats the newline character as a normal space. Notice that there's no space before or
after the \n character.
This is because the ( \ ) backslash is used to indicate that the next character is special. In
The code spec write ( \ \ ) when a single ( \ ) is required. The backslash ( \ ) is called an escape
character, i.e. it makes characters escape from their normal role.
Its only when expressions are evaluated (i.e. such as in assignments and echo statements) that the
difference between single and double quotes comes into play. After the assignment is done, no
one can tell how the string was produced. Consider this code.
$first_name = 'Chhaya';
$Iast_name = "Bankar";
$varl = "$firsCname $lasCname";
$var2= 'Chhaya Bankar';
The two variables $varl and $var2 will both contain the string Chhaya Bankar after the
evaluation, PHP will not make any distinction between the values stored in the two variables.
To concatenate (add together) strings use the ( • ) period character (i.e. a dot or full stop)
this:
$first_name = 'Chhaya';
$Iast_name = 'Bankar';
51
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$furr_name = $first_name.$last_name;
Now $full_name will contain the string "ChhayaBankar". That's probably not what is wanted it
would be better with a space between the two words. To do this, execute the following code:
$full_name = ‘$first_name ' , ‘ $last_name’;
Notice that the space between the variable $first_name and the dot is ignored, it's the string with
the space that's important. Use the dot (i.e. period character) each time two strings have to be
concatenated.
But it is also seen how this could be solved using variable substitution. This is often easier to
read, just remember to use double-quotes around the string. So this code gives the same result:
$full_name = "$first_name $Iast_name";
When using variable substitution a little problem will be encountered. The problem occurs where
substitution of a variable in a string is required having text immediately after the variable. The
name of the variable has to be delimited somehow. Using curly braces is the solution as shown in
this code:
$noun = 'car';
echo "A $noun, two ${noun}s";
The above code shows playing around with English words in plural form. The first occurrence of
$noun is substituted correctly, even when it's followed immediately by a comma because a
comma cannot be a part of a name. But certainly there can be a variable called $nouns, so curly
braces can be used to indicate that the variable called $noun is required and not some nonexistent
variable called $nouns
Operators
Operators are used to operate on values. The various operators are listed below
The example below shows the different results of using the different arithmetic operators:
<!DOCTYPE html>
<html>
<body>
<?php
$x=10;
$y=6;
52
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
echo "<br>";
echo ($x * $y);
echo "<br>";
echo ($x / $y);
echo "<br>";
echo ($x % $y);
?>
</body>
</html>
The example below shows the different results of using the different assignment operators:
<!DOCTYPE html>
<html>
<body>
<?php
$x=10;
echo $x;
echo "<br>";
$y=20;
53
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$y += 100;
echo $y;
echo "<br>";
$z=50;
$z -= 25;
echo $z;
echo "<br>";
$i=5;
$i *= 6;
echo $i;
echo "<br>";
$j=10;
$j /= 5;
echo $j;
echo "<br>";
$k=15;
$k %= 4;
echo $k;
?>
</body>
</html>
The example below shows the results of using the string operators:
54
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
<!DOCTYPE html>
<html>
<body>
<?php
$a = "Hello";
$b = $a . " world!";
echo $b; // outputs Hello world!
echo "<br>";
$x="Hello";
$x .= " world!";
echo $x; // outputs Hello world!
?>
</body>
</html>
Hello world!
Hello world!
The example below shows the different results of using the different increment/decrement
operators:
<!DOCTYPE html>
<html>
<body>
<?php
$x=10;
echo ++$x;
echo "<br>";
$y=10;
echo $y++;
echo "<br>";
55
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$z=5;
echo --$z;
echo "<br>";
$i=5;
echo $i--;
?>
</body>
</html>
11
10
4
5
The PHP comparison operators are used to compare two values (number or string):
The example below shows the different results of using some of the comparison operators:
<!DOCTYPE html>
<html>
<body>
<?php
$x=100;
$y="100";
56
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$a=50;
$b=90;
</body>
</html>
bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)
57
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The example below shows the different results of using the different array operators:
<!DOCTYPE html>
<html>
<body>
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$z = $x + $y; // union of $x and $y
var_dump($z);
echo "<br>";
var_dump($x == $y);
echo "<br>";
var_dump($x === $y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x <> $y);
echo "<br>";
var_dump($x !== $y);
?>
</body>
</html>
array(4) { ["a"]=> string(3) "red" ["b"]=> string(5) "green" ["c"]=> string(4) "blue"
["d"]=> string(6) "yellow" }
58
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
The if statement
Use the if-statement to execute different parts of PHP script code based on what is return when
an expression is evaluated (i.e. either TRUE or FALSE) is returned by the evaluation
Syntax:
if (<condition>)
<code block to be executed if condition returns TRUE>;
else
<code block to be executed if condition returns FALSE>;
Example1
The following example will output Have a nice Sunday! If the current day is Sunday,
otherwise it will output Have a nice day!:
<HTML>
<HEAD><TITLE>Nice Day Test Using If statement</TITLE> </HEAD>
<BODY>
<?php
$d=date("D");
if ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</BODY>
</HTML>
59
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Example 2
<!DOCTYPE html>
<html>
<body>
<?php
$t=date("H");
if ($t<"20") {
echo "Have a good day!";
}
?>
</body>
</html>
Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
<!DOCTYPE html>
<html>
<body>
60
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
<?php
$t=date("H");
if ($t<"20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
</body>
</html>
The output will be
Have a good day!
If the condition between the parenthesis, ( ) is TRUE, then the statements between the first pair
of curly braces, { •••} is executed. Else the part in the curly brackets after the else keyword is
executed
All kinds of statements can be used between the parenthesis and the curly braces. PHP is a
language where almost every statement has a value. A value can be used together with other
values to build complex expressions.
Take an assignment for example. The statement $b = $a actually has a value, namely the value of
$a. This means that this value can be used in another assignment, like this:
$c= ($b = $a);
The assignment in the parenthesis has the value of $a, which is then assigned to $c. The
parenthesis can actually be dropped and the result is the same. All three variables have the value
of $a. This explains the following statement:
/* Initialize counters: */
$i = $j = $k = $1 = 0;
Using comparison operators any kind of Boolean expression can be constructed. Take for
example the following if statement:
if ($a <= $b &&. ($array[$a] <= $array[$b] || $array[$a+$b] > $array[$a-$b]))
{
/* Do something useful - this is a comment, it won't be executed */
}
This if-statement first tests to see if the variable $a is smaller or equal to the variable $b. If
TRUE, the first part of the second section (i.e. after the && ) is executed to see if it is also
TRUE.
This happens because the && is being used, which means that the first section and the second
section should both be TRUE. The first part of the second section (Le. after the && ) uses $a and
61
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$b as indexes in an array, If the first part of the second section (i.e. after the && ) is TRUE, then
the second part of the second section (Le. after the II ) will not be executed. What is of interest is
whether the entire test is TRUE, which it is. This means that the following statement will execute
correctly:
mysql_connect() or die('Could not connect to the database!');
The function mysql_connect() tries to make a connection to a MySQL database. It returns TRUE
if it was able to make a connection. PHP evaluates the line as a Boolean expression. That means
that it starts by executing mysql_connect(). If that returns TRUE, then PHP skips the next
statement, because the or operator is used. The second statement makes PHP stop with a user
defined error message, if the first statement fails.
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically. The default statement is used
if no match is found.
Example
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor="red";
switch ($favcolor) {
case "red":
62
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task like this.
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
The while-loop
The while-loop is very similar to the for-loop. The while statement will execute a block of code
as long the condition is true.
syntax
{ <code to be executed>; }
The following example demonstrates a loop that will continue to run as long as the variable $i is
less than, or equal to 5. The variable $i will increase by 1 each time the loop runs:
<HTML>
<HEAD> <TITLE> Number Range</TITLE> </HEAD>
<BODY>
63
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
<?php
$i=1;
while($i<=5)
{
echo "The nu'mber is " . $i • "<BR>";
$i++;
}
?>
</BODY>
</HTML>
Often a while-loop is used to run though an array like this
The condition in the while loop uses several functions and an assignment. Each time the function
each() is called, it returns an array with the key and value from $array. When there are no
elements left in $array, each() returns false. This is what makes the whole condition false and
makes while loop stop.
The list() function can be used on the left side of an assignment to extract values from an array.
Use list() like this, although it would be much easier to assign the variables one at a time:
So the condition in the while-loop prepares $key and $val for the body of the loop. When all
key-value pairs have been examined, the loop terminates because each() return false, while then
becomes the value of the assignment, and therefore the value of the condition.
After an array has been run through like this, each() will return false if used it on the same array.
Call reset($array) to make each() start from the beginning again.
After an array has been run through like this, each() will return false if used it on the same array.
Call reset($array) to make each() start from the beginning again.
Here is an example with reset() and each() that will build a table that shows the keys and values
of an array:
$array = array('Sharanam' => 23, 'Hansel' => 22, 'Ivan' => 52);
reset($array);
while (list($key, $value) = each($array))
{
/ / Print a single row
echo "<TR>\n";
echo "<TD>$keY</TD>\n";
echo "<TD>$value</TD>\n";
echo "</TR>\n";
}
/ / End the table
echo "</TABLE>\n";
This code will roduce a table like this one:
Name Age
Sharanam 23
Hansel 22
Ivan 52
The important thing to notice in the above code is the way HTML tables can be built up in PHP.
Tables in HTML start with the <table> opening tag. Then comes any number of rows, each row
consists of any number of cells. Finally the </table> tag closes the HTML table.
When building HTML tables using PHP, remember that they always start in the upper left-hand
corner (the cell that says Name in this example) and then continue to the right along the same
row. Then come the rows below in the same way, left-to-right, until one ends up in the lower
right hand corner (that's the cell that holds 52 in this example).
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than,
or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
65
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
<!DOCTYPE html>
<html>
<body>
<?php
$x=1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
</body>
</html>
Notice that in a do while loop the condition is tested AFTER executing the statements within the
loop. This means that the do while loop would execute its statements at least once, even if the
condition fails the first time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is
checked:
The for loop is used when you know in advance how many times the script should run.
Syntax
Parameters:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x=0; $x<=10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array
($colors):
This loops over the array given by array_expression. On each loop, the value of the current element is assigned to
$vafue and the internal array pointer is advanced by one.
67
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
This does the same thing, except that. the current element's key will be assigned to the variable $key on each loop.
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red","green","blue","yellow");
</body>
</html>
red
green
blue
yellow
Example 2
<HTML>
<HEAD> <TITLE>Using foreach with value on ly</TITLE > </HEAD>
<BODY>
<?php
$age = array(23, 22, 52);
foreach ($age as $value)
{
echo “ The age is: $value. \n”;
}
?>
</BODY>
</HTML>
The following example demonstrates using key and value:
<HTML>
<HEAD>
<TITLE> Using foreach with key and value</TITLE>
</HEAD>
<BODY>
<?php
$age =.array( "Sharanam" => 23, "Hansel" => 22, "Ivan" => 52);
68
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
<HTML>
<HEAD><TITLE> Using foreach with multi-dimensional arrays </TITLE></HEAD>
<BODY>
<?php
$staff [0][0] = "Sharanam";
$staff [0][1] = "Hansel";
$staff [1][0] = "Ivan";
$staff [1][1] = "Chhaya";
·foreach ($staff as $value1)
{
foreach ($value1 as $value2)
{
echo $value2\n
}
}
?>
</BODY>
</HTML>
PHP understands multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.
69
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
</body>
</html>
The output will be
Row number 0
70
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
• Volvo
• 22
• 18
Row number 1
• BMW
• 15
• 13
Row number 2
• Saab
• 5
• 2
Row number 3
• Land Rover
• 17
• 15
To get access to the elements of the $cars array we must point to the two indices (row and
column):
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
</body>
</html>
The output will be
71
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
</body>
</html>
The output will be
Row number 0
• Volvo
• 22
• 18
Row number 1
• BMW
• 15
• 13
Row number 2
72
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
• Saab
• 5
• 2
Row number 3
• Land Rover
• 17
• 15
The strlen() function returns the length of a string, in characters. The example below returns the
length of the string "Hello world!": strlen() is often used in loops or other functions, when it is
important to know when a string ends. (i.e. in a loop, we might want to stop the loop after the last
character in a string).
<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello world!");
?>
</body>
</html>
12
The strpos() function is used to search for a specified character or text within a string.
If a match is found, it will return the character position of the first match. If no match is found, it
will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
<!DOCTYPE html>
<html>
<body>
73
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
<?php
echo strpos("Hello world!","world");
?>
</body>
</html>
Function Description
74
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>
75
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
76
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
77
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Besides the built-in PHP functions, we can create our own functions. A function is a block of
statements that can be used repeatedly in a program. A function will not execute immediately
when a page loads. A function will be executed by a call to the function.
Syntax
function functionName() {
code to be executed;
}
78
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Note: A function name can start with a letter or underscore (not a number). Give the function a
name that reflects what the function does!
In the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of
the function. The function outputs "Hello world!". To call the function, just write its name:
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just seperate them with a comma.
The following example has a function with one argument ($fname). When the familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the function,
which outputs several different first names, but an equal last name:
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
79
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
</body>
</html>
The following example has a function with two arguments ($fname and $year):
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname,$year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>
</body>
</html>
The output will be
Hege Refsnes. Born in 1975
Stale Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983
The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight($minheight=50) {
80
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x,$y) {
$z=$x+$y;
return $z;
}
</body>
</html>
5 + 10 = 15
7 + 13 = 20
2+4=6
81
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The DATE()function
Syntax:
Date Formats
The table below shows the characters that may be used in the format string
82
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Example:.
<?php
//Prints something like: Thursday
echo date{"I");
//Prints something like: Thursday 1st of April 2004 05:51:38 AM
echo date{"1 dS of F Y h:i:s A");
//Prints something like: Thursday the 1st
echo date{"1 \ \t\h\e jS");
?>
Example:
<HTML>
<BODY>
<?php
// Shows all PHP information
Phpinfo();
?>
<?php
//Shows only the general information
phpinfo(INFO _GEN ERAL)i
?>
</BODY>
</HTML>
PHP Server variables
All servers hold information such as which URL the user came from, which browser is used by
the user, and other information. This information is stored in variables.
In PHP, the $_SERVER is a reserved variable that contains all server information. The
$_SERVER is a global variable, which means that it's available in all scopes of any PHP script.
The following example will output which URL the user came from, the user's browser, and the
user's IP address:
<HTML>
<BODY>
<?php
echo "Referer: " • $_SERVER["HTTP _REFERER"] • "<BR>";
echo "Browser: " • $_SERVER["HTTP _USER_AGENT"] • "<BR>";
echo "User's IP address: " • $_SERVER["REMOTE_ADDR"];
?>
</BODY>
</HTML>
83
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
It is possible to insert the content of one PHP file into another PHP file (before the server
executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is
missing, use the include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP
application coding, always use the require statement to include a key file to the flow of
execution. This will help avoid compromising your application's security and integrity, just in-
case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard header, footer, or
menu file for all your web pages. Then, when the header needs to be updated, you can only
update the header include file.
Syntax
include 'filename';
or
require 'filename';
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
<!DOCTYPE html>
<html>
<body>
84
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
</body>
</html>
The output will be
Example 2
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done
<!DOCTYPE html>
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>
The output will be
Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP Tutorial
Example 3
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling file:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is included with
the include statement and PHP cannot find it, the script will continue to execute:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
86
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
If we do the same example using the require statement, the echo statement will not be executed
because the script execution dies after the require statement returned a fatal error:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
The output will be
87
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
88
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Unit 4
Chapter 8
FILES AND DIRECTORY OPERATIONS
8.1 File and directory access operations
File Handling is a pretty useful aspect of PHP. Data input and output flows are put to
considerable use in the development of Web applications. File Handling in PHP is not limited to
simple reading and writing of files but also support for viewing and modifying Web server
information, in addition to executing third party programs is provided.
is_file()
The is_file() function will return true if file exists and is a readable/writable file. Essentially,
is_file() is a bulletproof version of file_exists(), verifying not only the file's existence but also
whether it can be read from or written to.
Syntax
bool is_file(string file)
verifying the existence and validity of a file syntax example: .
$file= "somefilename.txt";
if (is_file($file))
{ print ''The file $file is valid and exists!"; }
else
{ print "Either $fiIe does not exist or it is not a valid file!"; }
verified that the desired file exists and is capable of having various I/O operations
89
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
once verified that the desired file exists and is capable of having various I/O operations
performed on it, it can then be opened to work with.
Opening a file
A better method to open files is with the fopen() function. This function gives you more options
than the readfile() function.
The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened. The following example also
generates a message if the fopen() function is unable to open the specified file:
The syntax is
int fopen (string file, string mode [, int use_include_path])
The first parameter of this function contains the name of the file to be opened and the second
parameter specifies in the mode in which the file should be opened:
<HTML>
<BODY>
<?php
$f=fopen("welcome.txt". "r");
?>
</BODY>
</HTML>
The file may be opened in one of the following modes:
90
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
If the file already exists, the fopen() call will fail and generate an error. If
the file does not
exist, fopen() will try to create it
x+ Create and open for read/write. File pointer at the beginning of the file.
If the file already exists, the fopen() call will fail and generate an error. If
the file does not exist, fopen() will try to create it
The following example generates a message if the fopen() is unable to open the specified file.
<HTML>
<BODY>
<?php
if (!($f=fopen ("welcome. txt" ,IIr") ) )
exit("Unable to open file!");
?>
</BODY>
</HTML>
The fcIose() function is used to close a file. The fclose()function closes the file designated by
filepointer, returning true on success and false otherwise.
Syntax
int fclose(int fpointer)
fclose($f);
syntax:
The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
Example:
$fh = fopen('lampp.txt', "r") or die("Can't open file!");
91
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
92
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
}
Else
{ print "Could not open $filename for writing"; }
?>
</body>
</html>
The output will be
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks
like this:
<html>
<body>
</body>
</html>
Welcome John
Your email address is john.doe@example.com
93
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The same result could also be achieved using the HTTP GET method:
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to validate form
data to protect your script from malicious code.
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3,
...)). This array holds key/value pairs, where keys are the names of the form controls and values
are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means
that they are always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.
94
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to send.
The limitation is about 2000 characters. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some cases.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send.
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.
95
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
• The get method sends all of the form information embedded into the URL. This method is
rarely used, due to various language and length restrictions.
• The post method sends all of the form information in the request body. This method is
usually preferred over get.
A powerful feature of PHP is the way it handles HTML forms. The basic concept that is that
any element in an HTML form will automatically be available to PHP scripts located at the
Web server.
Here is an example of a basic HTML form:
<FORM Action="action.php" Method="post">
Your name: <INPUT Type="text" Name="name">
Your age: <INPUT Type="text" Name="age">
<INPUT Type="submit" Value="Submit">
</FORM>
This is a simple HTML form with no special tags of any kind. When a user fills in this form and
hits the submit button, the data captured by the form elements is dispatched to action.php by the
client browser located at the Web server.
In this file the code spec could be like:
Hi <?php echo $_POST['name']; ?>.
You are <?php echo $_POST['age']; ?> years old.
Hi Hansel. You are 22 years old.
The $_POST['name'] and LPOST['age'] variables are automatically set by PHP. In the above
codespec, the $_POST auto global variable contains all POST data that has been introduced.
Notice the method in the HTML form is POST, if the method in the HTML form was GET then
the form information would be contained in the $_GET auto global instead.
The $_REQUEST auto global variable can also be used, if the source of the requested data
unknown. The LREQUEST auto global variable contains the merged information of GET,POST
and COOKIE data.
So, using $_POST['variable'] is the best option. However, nothing works if the web site, hosting
company, puts off the track_vars option in the php.ini file.
For example, if a page has a form to allow users to pass their comments to the web master, the
should use POST. If Reload or Refresh is clicked on a page that is reached through a POST, it
almost always is an error, same comment should not be posted twice, which is why these pages
are not book marked or cached.
Use the GET method with an HTML form when the form provides something to the Web server,
it does not actually change anything at the Web server. One disadvantage of the POST method is
that the URL cannot be book marked.
Now that the basic form creation is in place, have a look at a form that will accept user
information and send the information captured via email to the web master:
<HTML> <BODY>
<FORMAction = "emailinfo.php" Method = "post">
<b>Please take a moment to tell us what you think about our web site:</b><p>
<b>Your Name:</b><BR>
<INPUT Type="text" Name="name" Size="15" Maxlength="25" Value=""><BR>
<b>Your Email Address: </b><BR>
<INPUT Type = "text" Name="email" Size="15" Maxlength="75" value=""><BR>
<b>I frequently purchase the following products from our site:</b><BR>
<TEXTAREA Name="products" Rows="3" Cols="40"></TEXTAREA><BR>
<b>Comments: </b><BR>
<TEXTAREA Name="comments" Rows="3" Cols="40"></TEXTAREA><BR>
<INPUT Type="submit" Value="Submit">
</FORM>
</BODY> </HTML>
The output will look like
Mail() function
The mail() function is used to mail information to a given recipient.
Syntax:
97
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Output:
Thank you Sharanam Shah for taking a moment to send us your comments!
{
// Change $recipient to be the recipient of the form information
$recipient = "admin@ivanbayross.com";
// Email subject
$subject = "User Comments from $_POST['name']";
// Extra email headers
$headers = "From: LPOST[.email '] ";
// Create a message
$message = "Messagefrom LPOST['name'] \n\n Most PurchasedProduct:
$_POST['products'] \n\n Comments: \n\n LPOST['comments']";
// Send the email or produce an error
mail($recipient, $subject, $message, $headers) or die("Could not send email!");
// Send the user an appropriate message
print "Thank you $_POST['name'] for taking a moment to send us your
comments!";
}
?>
The above codespec ensures that the form fields, in this case name and email address, is not
empty. If any of the data checks out as invalid, the appropriate error messages are displayed, and
the processing stops i.e. the email is not send.
?>
<HTML>
<BODY>
<P>A cookie was set via this HTML page! The cookie will be active for 10 hours after its
set, after which it will automatically expire.</P>
</BODY>
</HTML>
How to retrieve a cookie Value?
When a cookie is set, PHP uses the cookie name as a variable. To access a cookie just refer to a
server side variable using the cookie name.
The following example tests if the uname cookie has been set, and prints an appropriate
message.
<HTML>
<BODY>
<?php
if (isset($_COOKIE["uname"]))
echo "Welcome” • $_COOKIE["uname"] • "!<BR>";
else
echo "You are not logged in!<BR>";
?>
</BODY>
</HTML>
PHP include files
One of the powerful aspects of PHP is the ability to build templates and code libraries that can
easily inserted into new scripts. In the long run, using code libraries can drastically minimize and
tears when you need to reuse common functionality across Web sites. Those backgrounds in
other languages (such as C, C++, or Java) will be familiar with this concept code libraries and
including them in a program to extend functionality.
Basic templates can be easily build by including one or a series of files via two of predefined
functions, require() and include(). Each has its specific application.
The include() function does exactly what its name implies; it includes a file.
Syntax:
include (file insertion_file)
An interesting characteristic of inciude() is that it can be executed conditionally.
For example, if an include is placed in an if statement, insertion_file will be included only if the
if statement in which it is enclosed evaluates to true. Keep in mind that if it is decided to use
include() in a conditional, the include() construct must be enclosed in statement block curly
brackets or in the alternative statement enclosure.
The following examples show including header, body and footer in an HTML page:
header.inf .
<?php
// Filename: header. inf
$site_title = "Ivan Bayross ";
$contact_email = “ivan@ivanbayross.com” ;
$contact_name = "Ivan";
?>
<html>
<head>
100
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
footer.inf
Best Viewed @ 1024 by 768 resolution I © copyright 2003 Ivan Bayross I all rights
reserved
</body>
</html>
index.php
<?php
//File: index.php
// Purpose: Home page of Ivan Bayross
// Date: January 03, 2003
// Include the header
include ("header.inf');
// Include the index body
include ("body.inf');
// Include the footer
include ("footer.inf');
?>
The require() operates like include(), including a template into the file in which the require() call
is located.
Syntax:
require(file insertion_file)
The require() function is used to create functions, headers, footers, or elements that will be
reused on multiple pages. However, there is one important difference between require() and
include(). The insertion_file will be included in the script in which the require() construct
appears regardless of where require() is located. For instance, if require() were placed in an if
statement that evaluated to false, insertion_file would be included anyway!
This can save the developer a considerable amount of time. If all of the pages on the site have a
similar header, include a single file containing the header into the pages. When the header needs
updating, only update the header file. All the HTML page headers, bound to this header file, will
be automatically updated. A really convenient, time saving technique.
The following examples show including header.htm as a header file in an HTML page:
101
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
header.inf
<?php
$site_title = "Ivan Bayross";
$contact_email = .. ivan@ivanbayross.com •• ;
$contact_name = "Ivan";
?>
index.php
<HTML><BODY>
<?php require{"header.inf')i ?>
<P>Some text</P>
<P>Some text</P>
</BODY> </HTML>
102
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Chapter 9
DATABASE OPERATIONS WITH PHP
9.1 Built in database functions
For many people, the main reason to learn a scripting language like PHP is to interact with
databases. PHP and MySQL make up what must be the best combination for data-driven Web
sites on the planet. MySQL is a small, compact database server ideal for small and not so small
applications. In addition to supporting standard SQL (ANSI), it compiles on a number of
platforms and has multithreading abilities on Unix servers, which make for great performance.
For non-Unix people, MySQL can be run as a service on Windows NT and as a normal process
in Windows 95/98 machines.
In addition to being free, the PHP-MySQL combination is also cross-platform, which means
application can be developed in Windows and copied to a Unix platform. Also, PHP can be run
as an external CGI process, a standalone script interpreter, or an embedded Apache module. The
ability to efficiently store and retrieve large amounts of information has contributed enormously
to the success of the Internet. Usually this information storage is implemented through the use of
a database. Sites such as Yahoo, Bazee, and Ebay depend heavily on the reliability of their
databases for storing enormous amounts of information.
It is actually surprising how useful a database can be when used with a website. There area huge
variety of things that can be done when both interact with each other, from displaying simple
lists to running a complete website from a database.
Some examples of PHP and MySQL being used together are:
• Banner Rotation: Here each banner is a PHP script. Using database random banners are
picked up and shown to the visitor. In addition to that a track of the number of times the
banner has been viewed can be kept. Banners can be added, changed or edited just by
making changes in the database and the script picks the correct banners for all the pages
on the site:
• Forums: Hundreds of forums (message boards) on the internet are run using PHP and
MySQL. These are much more efficient than other systems that create a page for each
message and offer a wide variety of options. All the pages in the forum can be updated by
changing one script.
• Databases: One quite obvious example is sites, which get all there information from a
database. For example Script Avenue is run by a few scripts, which gain all their
information from a large database. All the different script categories can be accessed in
one script by just changing the URL to access a different part of the database.
• Web sites: For a large website and changing the design can take a very long time to
update and upload all the pages. With PHP and MySQL the whole website could be just
one or two PHP scripts. These would access a MySQL database to get the information for
the pages. To update the website's design just change one page.
When a database properly implemented, using it to store data results in faster and more flexible
retrieval of data. Adding, searching and sorting features to the site is greatly simplified, and
control over viewing permissions becomes a nonissue by way of the privilege control features in
many database systems. Data replication and backup are also simplified.
103
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
104
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
For Example:
<?php
$username="root";
$password="";
$database="inventory" ;
// connect to the server and select a database.
@mysql_connect(localhost, $username,$password)
or die("Could not connect to MySQL server!");
105
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
HTML Input
Inputting the data using HTML pages is almost identical to inserting it using a PHP script. To
benefit, though, is that the script need not be changed for each block of data that has to be input
into custmast. Users can also be allowed to input their own data using this technique.
The following code spec will display an HTML page with textboxes, via which appropriate data
can be entered into the table custmast:
106
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
It works because, instead of the data being entered locally, it is being entered into the HTML
form and stored in variables, which are then passed to the PHP interpreter for further processing.
Counting rows
Before the data in the result ID can be navigated through, exactly how many rows are returned
must be known. Instead of hard coding a number use the command
$num=mysql_numrows($result);
This will set the value of the number of rows retrieved in the variable $num. This value can then
be used as a loop control value, a loop being the technique used to navigate through the record to
get all the data contained in it and output it to the VDU.
Setting up the loop
Set up a loop to take each row of the $result array and print out the data held there to the VDU.
By using $num, created earlier loop through all the rows of the $result array easily. In the code
below, $i is the number of times the loop has run and is used to make sure the loop stops at the
end of the $result array so there are no errors.
$i=0;
while ($i < $num)
{
PHP code spec to extract an array record and print this to the VDU
++$i;
}
This is a basic PHP loop, which will execute the code the correct number of times. Each time $i
will be one greater than the time before. This is useful, as $i can be used to tell the script which
line of the results should be read. As the first line in MySQL output is 0, this will work correctly.
So to pick each individual block of data from the result use the following
$custid =mysq_result( $result,$i,"custid");
107
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
108
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
109
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
6. Explain date() function with its syntax. List and explain any eight format strings which
can be used with it
7. Write a note on arrays in PHP
8. Explain mail() function with its syntax. Give example.
9. What is the need of validation of form information? How it is done in PHP. Give
example
10. What is a cookie? Explain how to create and retrieve cookies in PHP
11. List and explain any five file handling functions in PHP
12. Explain the following functions with syntax (6)
a. fopen() b. fread() c. fwrite()
13. Explain the following functions with syntax (6)
a. mysql_connect() b. mysql_connect_db() c. mysql_query()
14. Explain how to establish connection to database and execute query on database in
PHP? Give example
110
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Chapter 10
VALUE ADDED CHAPTER
Introduction on Pearl
Perl is a general-purpose programming language originally developed for text manipulation and
now used for a wide range of tasks including system administration, web development, network
programming, GUI development, and more.
Perl Features
• Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC,
among others.
• Perls database integration interface DBI supports third-party databases including Oracle,
Sybase, Postgres, MySQL and others.
• Perl works with HTML, XML, and other mark-up languages.
• Perl supports Unicode.
• Perl is Y2K compliant.
• Perl supports both procedural and object-oriented programming.
• Perl interfaces with external C/C++ libraries through XS or SWIG.
• Perl is extensible. There are over 20,000 third party modules available from the
Comprehensive Perl Archive Network (CPAN).
• The Perl interpreter can be embedded into other systems.
• Perl used to be the most popular web programming language due to its text
manipulation capabilities and rapid development cycle.
• Perl is widely known as " the duct-tape of the Internet".
• Perl can handle encrypted Web data, including e-commerce transactions.
• Perl can be embedded into web servers to speed up processing by as much as 2000%.
• Perl's mod_perl allows the Apache web server to embed a Perl interpreter.
111
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Perl is an interpreted, which means that your code can be run as is, without a compilation stage
that creates a non portable executable program.
Traditional compilers convert programs into machine language. When you run a Perl program,
it's first compiled into a byte code, which is then converted ( as the program runs) into machine
instructions. So it is not quite the same as shells, or Tcl, which are strictly interpreted without an
intermediate representation.
Neither it is like most versions of C or C++, which are compiled directly into a machine
dependent format. It is somewhere in between, along with Python and awk and Emacs .elc files.
The most up-to-date and current source code, binaries, documentation, news, etc. is available at
the official website of Perl:
Install Perl:
Perl distribution is available for a wide variety of platforms. You need to download only the
binary code applicable for your platform and install Perl.
If the binary code for your platform is not available, you need a C compiler to compile the source
code manually. Compiling the source code offers more flexibility in terms of choice of features
that you require in your installation.
112
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
NOTE: Here $ is Unix prompt where you type your command, so make sure you are not typing
$ while typing above mentioned commands.
This will install Perl in a standard location /usr/local/bin and its libraries are installed in
/usr/local/lib/perlXX where XX is the version of Perl that you are using.
It will take a while to compile the source code after issuing make command. Once installation is
done, you can issue perl -v command at $ prompt to check perl installation. If everything is fine
then it will display message like I have shown above
Running Perl
There are following different ways to start Perl:
You can enter perl and start coding right away in the interactive interpreter by starting it from
the command line. You can do this from Unix, DOS, or any other system which provides you a
command-line interpreter or shell window.
Option Description
-d[:debugger] Run program under debugger
-Idirectory Specify @INC/#include directory
-T Enable tainting checks
-t Enable tainting warnings
-U Allow unsafe operations
-w Enable many useful warnings
-W Enable all warnings
-X Disable all warnings
113
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
A Perl script is a text file which keeps perl code in it and it can be executed at command line by
invoking the interpreter on your application, as in the following:
You can run Perl from a graphical user interface (GUI) environment as well. All you need is a
GUI application on your system that supports Perl. You can download Padre, the Perl IDE. You
can also use Eclipse Plug-in EPIC - Perl Editor and IDE for Eclipse if you are familiar with
Eclipse.
Before proceeding to next chapter, make sure your environment is properly setup and working
perfectly fine. If you are not able to setup the environment properly then you can take help from
your system administrator.
Al the examples given in subsequent chapters have been executed with v5.16.2 version available
on CentOS flavour of Linux.
Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk,
Lisp and even English. However, there are some definite differences between the languages. This
chapter is designed to quickly get you up to speed on the syntax that is expected in Perl.
A Perl program consists of a sequence of declarations and statements which run from the top to
the bottom. Loops, subroutines, and other control structures allow you to jump around within the
code. Every simple statement must end with a semicolon (;).
Perl is a free-form language: you can format and indent it however you like. Whitespace serves
mostly to separate tokens, unlike languages like Python where it is an important part of the
syntax, or Fortran where it is immaterial.
You can use Perl interpreter with -e option at command line which lets you execute Perl
statements from the command line. Let's try something at $ prompt as follows:
114
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Hello, world
Assuming you are already on $ prompt. So let's open a text file hello.pl using vi or vim editor
and put the following lines inside your file.
#!/usr/bin/perl
Here /usr/bin/perl is actual perl interpreter binary. Before you execute your script be sure to
change the mode of the script file and give execution priviledge, generally a setting of 0755
works perfectly and finally and finally you execute above script as follows:
Hello, world
You can use parentheses for functions arguments or omit them according to your personal taste.
They are only required occasionally to clarify issues of precedence. Following two statements
produce same result.
print("Hello, world\n");
print "Hello, world\n";
As a Perl convention, a Perl file must be saved with a .pl or .PL file extension in order to be
recognized as a functioning Perl script. File names can contain numbers, symbols, and letters but
must not contain a space. Use an underscore (_) in places of spaces.
Comments in Perl
Comments in any programming language are friends of developers. Comments can be used to
make program user friendly and they are simply skipped by the interpreter without impacting
code functionality. For example, in the above program a line starting with hash # is a comment.
Simply saying comments in Perl start with a hash symbol and run to the end of the line:
115
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Lines starting with = are interpreted as the start of a section of embedded documentation (pod),
and all subsequent lines until the next =cut are ignored by the compiler. Following is the
example:
#!/usr/bin/perl
=begin comment
This is all part of multiline comment.
You can use as many lines as you like
These comments will be ignored by the
compiler until the next =cut is encountered.
=cut
Hello, world
Whitespaces in Perl
A Perl program does not care about whitespaces. Following program works perfectly fine:
#!/usr/bin/perl
But if spaces are inside the quoted strings then they would be printed as is. For example:
#!/usr/bin/perl
Hello
world
All types of whitespace like spaces, tabs, newlines, etc. are equivalent for the interpreter when
they are used outside of the quotes. A line containing only whitespace, possibly with a comment,
is known as a blank line, and Perl totally ignores it.
You can use double quotes or single quotes around literal strings as follows:
#!/usr/bin/perl
116
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Hello, world
Hello, world\n$
There is important different in single and double quotes. Only double quotes interpolate
variables and special characters such as newlines \n where as single quote does not interpolate
any variable or special character. Check below example where we are using $a as a variable to
store a value and later printing that value:
#!/usr/bin/perl
$a = 10;
print "Value of a = $a\n";
print 'Value of a = $a\n';
Value of a = 10
Value of a = $a\n$
"Here" Documents
You can store or print multiline text with a great comfort. Even you can make use of variables
inside "here" document. Below is a simple syntax, check carefully there must be no space
between the << and the identifier.
An identifier may be either a bare word or some quoted text like we used EOF below. If
identifier is quoted, the type of quote you use determines the treatment of the text inside the here
docoment, just as in regular quoting. An unquoted identifier works like double quotes.
#!/usr/bin/perl
$a = 10;
$var = <<"EOF";
This is the syntax for here document and it will continue
until it encounters a EOF in the first line.
This is case of double quote so variable value will be
interpolated. For example value of a = $a
EOF
print "$var\n";
$var = <<'EOF';
This is case of single quote so variable value will not be
interpolated. For example value of a = $a
EOF
print "$var\n";
117
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Escaping Characters
Perl uses the backslash (\) character to escape any type of character that might interfere with our
code. Let's take one example where we want to print double quote and $ sign:
#!/usr/bin/perl
This is "number"
$result
Perl Identifiers:
A Perl identifier is a name used to identify a variable, function, class, module, or other object. A
Perl variable name starts with either $, @ or % followed by zero or more letters, underscores,
and digits (0 to 9).
Perl does not allow punctuation characters such as @, $, and % within identifiers. Perl is a case
sensitive programming language. Thus $Manpower and $manpower are two different
identifiers in Perl.
Perl is loosely typed language and there is no need to specify a type for your data while using in
your program. The Perl interpreter will choose the type based on the context of the data itself.
Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars, also known as
associative arrays. Here is little detail about these data types.
Numeric Literals
118
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Perl stores all the numbers internally as either signed integers or double-precision floating-point
values. Numeric literals are specified in any of the following floating-point or integer formats:
Type Value
Integer 1234
Negative integer -100
Floating point 2000
Scientific notation 16.12E14
Hexadecimal 0xffff
Octal 0577
String Literals
Strings are sequences of characters. They are usually alphanumeric values delimited by either
single (') or double (") quotes. They work much like UNIX shell quotes where you can use single
quoted strings and double quoted strings.
Double-quoted string literals allows variable interpolation, and single-quoted strings are not.
There are certain characters when they are proceeded by a back slash they will have special
meaning and they are used to represent like newline (\n) or tab (\t).
You can embed newlines or any of the following Escape sequences directly in your double
quoted strings:
119
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Example
Let's see again how strings behaves with single quotation and double quotation. Here we will use
string escapes mentioned in the above table and will make use of scalar variable to assign string
values.
#!/usr/bin/perl
Welcome to
tutorialspoint.com!
Welcome to \ntutorialspoint.com!
Welcome to tutorialspoint.com!
WELCOME TO TUTORIALSPOINT.COM!
Welcome to TUTORIALSPOINT.com!
Welcome\ to\ tutorialspoint\'s\ family
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can
store integers, decimals, or strings in these variables.
We have learnt that Perl has following three basic data types:
• Scalars
120
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
• Arrays
• Hashes
Accordingly we are going to use three types of variables in Perl. A scalar variable will precede
by a dollar sign ($) and it can store either a number, a string, or a reference. A array variable
will precede by sign @ and it will store ordered lists of scalars. Finaly Hash variable will
precede by sign % and will be used to store sets of key/value pairs.
Perl maintains every variable type in a separate namespace. So you can, without fear of conflict,
use the same name for a scalar variable, an array, or a hash. This means that $foo and @foo are
two different variables.
Creating Variables
Perl variables do not have to be explicitly declared to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.
Keep a note that this is mandatory to declare a varibale before we use it if we use use strict
statement in our program.
The operand to the left of the = operator is the name of the variable, and the operand to the right
of the = operator is the value stored in the variable. For example:
Here 25, "John Paul" and 1445.50 are the values assigned to $age, $name and $salary variables,
respectively. Shortly we will see how we can assign values to arrays and hashes.
Scalar Variables
A scalar is a single unit of data. That data might be a integer number, floating point, a character,
a string, a paragraph, or an entire web page. Simply saying it could be anything, but only a single
thing.
#!/usr/bin/perl
121
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Age = 25
Name = John Paul
Salary = 1445.5
Array Variables
An array is a variable that stores an ordered list of scalar values. Array variables are preceded by
an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the
variable name followed by the index of the element in square brackets.
#!/usr/bin/perl
Here we used escape sign (\) before $ sign just to print it other Perl will understand it as a
variable and will print its value. When exected, this will produce following result:
$ages[0] = 25
$ages[1] = 30
$ages[2] = 40
$names[0] = John Paul
$names[1] = Lisa
$names[2] = Kumar
Hash Variables
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to
a single element of a hash, you will use the hash variable name followed by the "key" associated
with the value in curly brackets.
#!/usr/bin/perl
$data{'John Paul'} = 45
$data{'Lisa'} = 30
122
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$data{'Kumar'} = 40
Variable Context
Perl treats same variable differently based on Context ie. situation where a variable is being used.
Let's check following example:
#!/usr/bin/perl
@copy = @names;
$size = @names;
Here @names is an array, which has been used in two different contexts. First we copied it into
anyother array ie. list so it returned all the elements assuming that context is list context. Next we
used same array and tried to store this array in a scalar, so in this case it returned just number of
elements in this array assuming that context is scalar context. Following table lists down various
contexts:
A scalar is a single unit of data. That data might be a integer number, floating point, a character,
a string, a paragraph, or an entire web page. Simply saying it could be anything, but only a single
thing.
#!/usr/bin/perl
123
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Age = 25
Name = John Paul
Salary = 1445.5
Numeric Scalars
A scalar is most often either a number or a string. Following example demonstrates the usage of
various types of numeric scalars:
#!/usr/bin/perl
$integer = 200;
$negative = -300;
$floating = 200.340;
$bigfloat = -1.2E-23;
integer = 200
negative = -300
floating = 200.34
bigfloat = -1.2e-23
octal = 255
hexa = 255
String Scalars
Following example demonstrates the usage of various types of string scalars. Notice the
difference between single quoted strings and double quoted strings:
#!/usr/bin/perl
124
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Scalar Operations
You will see a detail of various operators available in Perl in a separate chapter but here I'm
going to list down few numeric and string operations.
#!/usr/bin/perl
str = helloworld
num = 15
mix = helloworld15
Multiline Strings
If you want to introduce multiline strings into your programs, you can use standard single quotes
as below:
#!/usr/bin/perl
$string = 'This is
a multiline
string';
print "$string\n";
125
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
This is
a multiline
string
You can use "here" document syntax as well to store or print multilines as below:
#!/usr/bin/perl
print <<EOF;
This is
a multiline
string
EOF
This is
a multiline
string
V-Strings
A literal of the form v1.20.300.4000 is parsed as a string composed of characters with the
specified ordinals. This form, known as v-strings.
A v-string provides an alternative and more readable way to construct strings, rather than use the
somewhat less readable interpolation form "\x{1}\x{14}\x{12c}\x{fa0}".
They are any literal that begins with a v and is followed by one or more dot-separated elements.
For example:
#!/usr/bin/perl
$smile = v9786;
$foo = v102.111.111;
$martin = v77.97.114.116.105.110;
smile = a?o
foo = foo
martin = Martin
Wide character in print at /tmp/135911788320439.pl line 7.
Special Literals
So far you must have a feeling about string scalars and its concatenation and interpolation
opration. So let me tell you about three special literals __FILE__, __LINE__, and
126
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
__PACKAGE__ represent the current filename, line number, and package name at that point in
your program.
They may be used only as separate tokens and will not be interpolated into strings. Check below
example:
#!/usr/bin/perl
An array is a variable that stores an ordered list of scalar values. Array variables are preceded by
an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the
variable name followed by the index of the element in square brackets.
#!/usr/bin/perl
Here we used escape sign (\) before $ sign just to print it other Perl will understand it as a
variable and will print its value. When exected, this will produce following result:
$ages[0] = 25
$ages[1] = 30
$ages[2] = 40
$names[0] = John Paul
$names[1] = Lisa
$names[2] = Kumar
In Perl, List and Array terms are often used as if they're interchangeable. But the list is the data,
and the aray is the variable.
127
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Array Creation
Array variables are prefixed with the @ sign and are populated using either parentheses or the
qw operator. For example:
The second line uses the qw// operator, which returns a list of strings, separating the delimited
string by white space. In this example, this leads to a four-element array; the first element is 'this'
and last (fourth) is 'array'. This means that you can use different lines as follows:
@days = qw/Monday
Tuesday
...
Sunday/;
You can also populate an array by assigning each value individually as follows:
$array[0] = 'Monday';
...
$array[6] = 'Sunday';
#!/usr/bin/perl
print "$days[0]\n";
print "$days[1]\n";
print "$days[2]\n";
print "$days[6]\n";
print "$days[-1]\n";
print "$days[-7]\n";
Mon
Tue
Wed
Sun
Sun
Mon
Array indices start from zero, so to access first element you need to give 0 as indices. You can
also give a negative index, in which case you select the element from the end, rather than the
beginning, of the array. This means that
128
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Perl offers a shortcut for sequential numbers and letters. Rather than typing out each element
when counting to 100 for example, we can do something like as follows:
#!/usr/bin/perl
@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);
Here double dot (..) is called range operator. This will produce following result:
1 2 3 4 5 6 7 8 9 10
10 11 12 13 14 15 16 17 18 19 20
a b c d e f g h i j k l m n o p q r s t u v w x y z
Array Size
The size of an array can be determined using scalar context on the array - the returned value will
be the number of elements in the array:
@array = (1,2,3);
print "Size: ",scalar @array,"\n";
The value returned will always be the physical size of the array, not the number of valid
elements. You can demonstrate this, and the difference between scalar @array and $#array,
using this fragment as follows:
#!/uer/bin/perl
@array = (1,2,3);
$array[50] = 4;
$size = @array;
$max_index = $#array;
Size: 51
Max Index: 50
129
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
There are only four elements in the array that contain information, but the array is 51 elements
long, with a highest index of 50.
Perl provides a number of useful functions to add and remove elements in an array. You may
have a question what is a function? So far you have used print function to print various values.
Similarly there are various other functions or sometime called sub-routines which can be used for
various other functionalities.
130
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
#!/usr/bin/perl
@weekdays = @days[3,4,5];
print "@weekdays\n";
The specification for a slice must a list of valid indices, either positive or negative, each
separated by a comma. For speed, you can also use the .. range operator:
#!/usr/bin/perl
@weekdays = @days[3..5];
print "@weekdays\n";
Now we are going to introduce one more function called splice(), which has following syntax:
This function will remove the elements of @ARRAY designated by OFFSET and LENGTH, and
replaces them with LIST, if specified. Finally it returns the elements removed from the array.
Following is the example:
#!/usr/bin/perl
@nums = (1..20);
print "Before - @nums\n";
splice(@nums, 5, 5, 21..25);
print "After - @nums\n";
Before - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
131
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
After - 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20
Here actual replacement begins with the 6th number after that five elements are then replaced
from 6 to 10 with the numbers 21, 22, 23, 24 and 25.
This function splits a string into an array of strings, and returns it. If LIMIT is specified, splits
into at most that number of fields. If PATTERN is omitted, splits on whitespace. Following is
the example:
#!/usr/bin/perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";
Roses
Michael
This function joins the separate strings of LIST into a single string with fields separated by the
value of EXPR, and returns the string. Following is the example:
#!/usr/bin/perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";
132
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
print "$string1\n";
print "$string2\n";
Rain-Drops-On-Roses-And-Whiskers-On-Kittens
Larry,David,Roger,Ken,Michael,Tom
Sorting Arrays
The sort() function sorts each element of an array according to ASCII Numeric standards. This
function has following syntax:
This function sorts the LIST and returns the sorted array value. If SUBROUTINE is specified
then specified logic inside the SUBTROUTINE is applied while sorting the elements.
#!/usr/bin/perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Before: @foods\n";
So far you have seen simple variable we defined in our programs and used them to store and
print scalar and array values. Perl provides numerous special variables which have their
predefined meaning.
We have a speciall variable which is written as $[. This special variable is a scalar containing the
first index of all arrays. Because Perl arrays have zero-based indexing, $[ will almost always be
0. But if you set $[ to 1 then all your arrays will use on-based indexing. It is recommended not to
use any other indexing other than zero. However, let's take one example to show the usage of $[
variable:
#!/usr/bin/perl
133
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";
Merging Arrays
Because an array is just a comma-separated sequence of values, you can combine them together
as shown below:
#!/usr/bin/perl
@numbers = (1,3,(4,5,6));
numbers = 1 3 4 5 6
The embedded arrays just become part of the main array as shown below:
#!/usr/bin/perl
@odd = (1,3,5);
@even = (2, 4, 6);
numbers = 1 3 5 2 4 6
#!/usr/bin/perl
134
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$var = (5,4,3,2,1)[4];
value of var = 1
Similarly, we can extract slices, although without the requirement for a leading @ character:
#!/usr/bin/perl
@list = (5,4,3,2,1)[1..3];
Value of list = 4 3 2
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to
a single element of a hash, you will use the hash variable name preceded by a "$" sign and
followed by the "key" associated with the value in curly brackets.
#!/usr/bin/perl
$data{'John Paul'} = 45
$data{'Lisa'} = 30
$data{'Kumar'} = 40
Creating Hashes
Hashes are created in one of two following ways. In the first method, you assign a value to a
named key on a one-by-one basis:
In the second case, you use a list, which is converted by taking individual pairs from the list: the
first element of the pair is used as the key, and the second, as the value. For example:
For clarity, you can use => as an alias for , to indicate the key/value pairs as follows:
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
Here is one more variant of the above form, have a look at it, here all the keys have been
preceded by hyphen (-) and no quotation is required around them:
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
But it is important to note that there is a single word ie without spaces keys have been used in
this form of hash formation and if you build-up your hash this way then keys will be accessed
using hyphen only as shown below.
$val = %data{-JohnPaul}
$val = %data{-Lisa}
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
45
30
40
Extracting Slices
You can extract slices of a hash just as you can extract slices from an array. You will need to use
@ prefix for the variable to store returned value because they will be a list of values:
#!/uer/bin/perl
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
Array : 45 30
136
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
keys %HASH
This function returns an array of all the keys of the named hash. Following is the example:
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";
Lisa
John Paul
Kumar
Similarly you can use values function to get a list of all the values. This function has following
syntax:
values %HASH
This function returns a normal array consisting of all the values of the named hash. Following is
the example:
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";
30
45
40
137
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
run time. You can get around this by using the exists function, which returns true if the named
key exists, irrespective of what its value might be:
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
if( exists($data{'Lisa'} ) ){
print "Lisa is $data{'Lisa'} years old\n";
}
else{
print "I don't know age of Lisa\n";
}
Here I introduced IF...ELSE statement which we will study in a separate chapter. For now you
just assume that if( condition ) part will be executed only when given condition is true otherwise
else part will be executed. So when we execute above program, it produces following result
because here given condition exists($data{'Lisa'} returns true:
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
1 - Hash size: is 3
2 - Hash size: is 3
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
138
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
1 - Hash size: is 3
2 - Hash size: is 4
3 - Hash size: is 3
Following is the general from of a typical decision making structure found in most of the
programming languages:
139
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean
context and all other values are true. Negation of a true value by ! or not returns a special false
value.
Perl programming language provides following types of conditional statements. Click the
following links to check their detail.
Statement Description
With latest versions of Perl, you can make use of switch statment
switch statement which allows a simple way of comparing a variable value against
various conditions.
The ? : Operator
Let's check conditional operator ? : which can be used to replace if...else statements. It has the
following general form:
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is
evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is
evaluated and its value becomes the value of the expression. Below is a simple example making
use of this operator:
#!/usr/local/bin/perl
$name = "Ali";
$age = 10;
There may be a situation when you need to execute a block of code several number of times. In
general statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages:
Perl programming language provides following types of loop to handle looping requirements.
Click the following links to check their detail.
141
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The foreach loop iterates over a normal list value and sets the variable
foreach loop
VAR to be each element of the list in turn.
Like a while statement, except that it tests the condition at the end of
do...while loop
the loop body
You can use one or more loop inside any another while, for or do..while
nested loops
loop.
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements. Click the following links to check their detail.
Causes the loop to skip the remainder of its body and immediately retest
next statement
its condition prior to reiterating.
The redo command restarts the loop block without evaluating the
redo statement
conditional again. The continue block, if any, is not executed.
Perl supports a goto command with three forms: goto label, goto expr,
goto statement
and goto &name.
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally
used for this purpose. Since none of the three expressions that form the for loop are required, you
can make an endless loop by leaving the conditional expression empty.
#!/usr/local/bin/perl
for( ; ; )
{
printf "This loop will run forever.\n";
}
142
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but as a programmer more commonly use the for(;;)
construct to signify an infinite loop.
What is an operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and + is called operator. Perl language supports many operator types but following is a
list of important and most frequently used operators:
• Arithmetic Operators
• Equality Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Logical Operators
• Quote-like Operators
• Miscellaneous Operators
143
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20
then, lets check following numeric equality operators:
[ Show Example ]
Below is a list of equity operators. Assume variable $a holds "abc" and variable $b holds "xyz"
then, lets check following string equality operators:
ge Returns true if the left argument is stringwise greater ($a ge $b) is false.
144
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Simple assignment operator, Assigns values from right $c = $a + $b will assigne value of $a
=
side operands to left side operand + $b into $c
Bitwise operator works on bits and perform bit by bit operation. Assume if $a = 60; and $b = 13;
Now in binary format they will be as follows:
145
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
$a = 0011 1100
$b = 0000 1101
-----------------
Binary AND Operator copies a bit to the result if it exists ($a & $b) will give 12 which is 0000
&
in both operands. 1100
Binary OR Operator copies a bit if it exists in eather ($a | $b) will give 61 which is 0011
|
operand. 1101
Binary XOR Operator copies the bit if it is set in one ($a ^ $b) will give 49 which is 0011
^
operand but not both. 0001
There are following logical operators supported by Perl language. Assume variable $a holds true
and variable $b holds false then:
146
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
Quote-like Operators:
There are following Quote-like operators supported by Perl language. In the following table, a {}
represents any pair of delimiters you choose.
Miscellaneous Operators:
There are following miscellaneous operators supported by Perl language. Assume variable a
holds 10 and variable b holds 20 then:
++ Auto Increment operator increases integer value by one $a++ will give 11
147
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem
The following table lists all operators from highest precedence to lowest.
148
– LAMP TECHNOLOGY