lamprevised | PDF | Linux Distribution | Linux
0% found this document useful (0 votes)
20 views

lamprevised

The document is a background study material for LAMP technology, specifically for BCA V Semester students at Srinivas Institute of Management Studies. It covers various units including Linux Operating System, Apache Web Server, HTML/XHTML, MySQL Database Server, and PHP, detailing installation processes, commands, and functionalities. Compiled by Prof. Sridhara Acharya, the material serves as a comprehensive guide for understanding and implementing LAMP technology.

Uploaded by

prajwalprabhu025
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

lamprevised

The document is a background study material for LAMP technology, specifically for BCA V Semester students at Srinivas Institute of Management Studies. It covers various units including Linux Operating System, Apache Web Server, HTML/XHTML, MySQL Database Server, and PHP, detailing installation processes, commands, and functionalities. Compiled by Prof. Sridhara Acharya, the material serves as a comprehensive guide for understanding and implementing LAMP technology.

Uploaded by

prajwalprabhu025
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 149

Srinivas Institute of Management Studies

Pandeshwar, Mangalore – 575 001


BACKGROUND STUDY MATERIAL

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

5.3 MYSQL administration Commands-


myisamchk, mysql, mysqladmin, mysqlbug, mysqlimport, mysqlshow
6 PHP 49
6.1 Obtaining, Installing and configuring PHP
6.2 Installing PHP from binary package
6.3 PHP configuration parameters and php.ini file
6.4 Binding The PHP4 Installation With Apache2
6.5 Registering The Changes Made In The httpd.conf With Apache2
7 PHP Language Core 51
7.1 Variables, constants, data types and operators
7.2 Decision making
7.3 Flow control and loop
7.4 Arrays and array operations
7.5 Two dimensional and multidimensional arrays
7.6 Strings and string operations
7.7 Functions, function declarations and parameter passing
7.8 Outputting the data include and require statements
7.9 Assignment Questions on Unit 3

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

9 Database operations with PHP 104


9.1 Built in database functions
9.2 Connecting to a mysql database
9.3 Selecting a database
9.4 Building and sending the query to database
9.5 Inserting and updating the data
9.6 Sample database routines and code segments
9.7 Assignment Questions on Unit 4

11 Value Added Chapter Introduction to Perl 112

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.

1.2 Linux Distributions

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

Debian Debian GNU/Linux is developed and maintained entirely by volunteers. The


Advanced Package Tool (apt) is very powerful and highly esteemed-many people think this
is the best updater around. It is one of the easiest distributions to keep up to date. The apt-get
mechanism handles package dependencies neatly.

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.

1.3 Download and Install

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

defragmented before you do this (see www.igd.fhg.de/~aschaefe/fips/). This program works


for older versions of Windows that are based on the FAT file system: Windows 95, 98, 2000,
and. ME. Unfortunately, newer versions of Windows (NT, XP) are based on the proprietary
NTFS file system, which breaks fips. It is unlikely that someone will reverse engineer this
system and implement something similar to fips for NTFS, because the Digital Millennium
Copyright Act (DMCA) makes reverse engineering a proprietary closed system a felony! A
couple of programs purport to do the same thing as fips, but they aren't as well tested. Red
Hat doesn't include them on the install disk-draw your own conclusions. You pays your
money, you takes your chances. It's your data.

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.

1.5 Linux Partition Size

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.

Table 1.1 Recommended Linux partition size

Partition Size Discription


/boot 32MB Where the boot files live
/ 512MB The / partition is the base of the OS
/home 1GB User files live here (not /usr!). Add more space
if you have a bunch of MP3s, less if this is a
web server and not a user machine.
/usr 5GB All the programs and documentation live here.
/var 2.25GB This is where all your web source will be and
where all the logs accumulate. This needs to be
big.
6
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

/tmp 256MB This is where temporary files are stored.


/web Optional An optional place to put web source.
/root Optional The root user space.
swap Up to two times the amount of physical
memory you are ever likely to have-be
generous, because you don't want to have to
reformat if you add more memory later. Red
Hat limits this to a max of 2GB. Since there is
about 750MB left, use that. Make it bigger if
you have more space, up to the limit.

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

1.7 Basic Unix

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.

1.8 Owner, Groups, Permissions, Ownerships

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

Table 2 Simple directory listing

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.

1.9 Processes and Demons

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:

• ~ is your home directory. The command cd - /bi n means go to /home/jrl /bin.


• . is the current directory. The command cd . /bi n means go the directory bi n below this
one. The command ./configure means execute the configure file in the current working
directory. Because the current directory is probably not in the PATH, if you typed
configure at the shell prompt, Unix would first search through all the directories in the
defined PATH, not find configure, or find a different one and execute that instead-the
Wrong Thing. Some people put in their PATH, but this is a Bad Thing for many reasons.
• .. is the directory above this one. The command cd .. means go to the next directory up.
Similarly, .. / .. means go two directories up.

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:

find / -name foo

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

cat [OPTION]... [FILE]...

Examples

cat file1.txt file2.txt

Reads and outputs the contents, in sequence, of file1.txt and file2.txt, respectively.

less is a simple, feature-rich command-line file viewer.

Syntax

less [-[+]aABcCdeEfFgGiIJKLmMnNqQrRsSuUVwWX~] [-b space] [-h lines]


[-j line] [-k keyfile] [-{oO} logfile] [-p pattern] [-P prompt]
[-t tag] [-T tagsfile] [-x tab,...] [-y lines] [-[z] lines]
[-# shift] [+[+]cmd] [--] [filename]...
11
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

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.

The command sort

The command sort sorts the lines in a text file.

Syntax

sort [OPTION]... [FILE]...


sort [OPTION]... --files0-from=F

example

sort -r file.txt

Sort the contents of file.txt in reverse order.

1.11 Basic File system Essentials


For a complete explanation of where things go and why they go there, see
www.pathname.com/fhs/. Here we give a brief list of directories that you'll probably visit and
what they are. The various versions of Unix each do things slightly differently, so there are no
hard-and-fast rules. By the way, looking in all these directories to see what's there is an excellent
learning exercise.

/home User directories. Your directory will be under /home/your_name_goes_here.

/root The home directory of root.

/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.

/1ib Contains libraries for the executables in /bin and /sbin.

/usr/src Kernel source.

12
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

/usr /1oca1, /opt This is where optional (.local) software is installed.

/usr/X11R6 X Windows commands and libraries.

/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 The "variable" directory. Everything here changes often.

/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.

/var/www Web files

/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/X11 X Windows configuration files.

/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

Assignment Questions on Unit 1


Short answer questions (2 marks)
1. List any two advantages of getting Linux as a packaged distribution
2. List any four popular Linux packaged distributions
3. What is RPM? What is its use?
4. Expand
a. apt b. RPM c. YaST d. CLI
5. What is swap partition. What is its maximum limit in RedHat Linux.
6. Differentiate root user and non-root user accounts in Linux
7. In Linux, how you change ownership of a file and access permissions of a file. Give
example for each.
8. Differentiate process and daemons
9. List any four commands associated with process
10. Explain any two standard shortcuts of cd command
11. Differentiate locate and find commands
12. Differentiate cp and mv commands
13. What is aliasing of commands? Give example
14. Differentiate /bin and /usr/bin
15. Differentiate /tmp and /var/tmp

Long answer questions


1. Explain in brief any FIVE Linux Packaged Distributions
2. Assuming a 10GB disk, recommend Linux partitions in it.
3. List and explain any FOUR commands associated with processes in Linux (4)
4. List and explain in brief any FIVE Linux commands
5. Explain in brief
a. man b. pwd c. grep d. more e. mkdir
6. Explain in brief
a. ln b. mv c. locate d. chkconfig e. which, where
14
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

7. List and explain any 7 Linux commands


8. Explain standard shortcuts used with cd command (3)
9. What is command aliasing? Explain with example (3)
10. List any five File System Essentials
11. List any SEVEN File System Essentials
12. Explain in brief
a. /bin b. /usr/tmp c. /boot d. /var/log

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.

2.2 Apache Installation

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:

Download Apache2 from http://www.apache.org/downloads.cgi. In the Downloads section


choose the latest stable version of Apache available for download. At ,the time of creating this
material the latest stable version of Apache was httpd-2.0.48.tar.gz. which is considered to be
best available version.

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.

• Unix Source: httpd-2.0.48.tar.gz [PGP] [MDS]


• Unix Source: httpd-2.0.48.tar.Z [PGP] [MDS]
• Win32Source: httpd-2.0.48-win32-src.zip [PGP] [MDS]
• Win32 Binary (MSI Installer): apache 2.0.48-win32-x86-no ssl.msi [PGP] [MDS]
• Other files

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

This will extract the file httpd-2.0.48.tar from 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:

# tar -xvf 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

Then begin the apache2 configuration.

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

Finally run the:

# make install

This completes the installation of apache2.

2.3 MIME types and CGI Files

Manipulating the Apache2 HTTPD service

Starting the Apache2 HTTPD service:

#/usr/local/apache2/bin/apachectl start

Stopping the Apache2 HTTPD service:

# /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.

Some important entries in httpd.conf file

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.

Server Root /etc/httpd

This sets the absolute path to the server directory. Generally, the argument 'of Server Root
should be the path to where Apache is installed.

2.4 Authentication and log files

ErrorLog /logs/error_log

Custom Log /logs/access_log common

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.

ScoreBoard File /logs/apache_runtime_status

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

Set it to Off to deactivate.

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.

Number of servers to start initially should be a reasonable ballpark figure.

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

User and Group

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.

2.5 Automatic directory indexing

Directorylndex index.html index.htm index.shtml index.php index.php4 index.php3 index.phtml


index.cgi Specifies the name of the file or files to use as a pre-written HTML. Separate multiple
entries with spaces.

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

Alias /icons/ "/usr/local/apache2/icons/"

ScriptAlias /cgi-bin/ "/var/www/sct/phpproj/cgi-binl"

These both map a URL path to a directory on the server.

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

2.6 <Directory>, Access control, URL Pathnames


Additional options can be added to directories using <Directory> and Options directives
<Directory> is a container directive. Container directives enclose multiple lines in the config file.
They require a closing directive of the form </Directive>.
Aspects of Apache's behaviour can be controlled on a per-directory or per-filename basis using
<Directory> and related <Files> and <FilesMatch> directives. Directives placed between
<Directory></Directory> apply to sub-directories as well. What options are allowed in directory
can be controlled using the Options directive. Possible values to an Option directive are given
below with brief descriptions:

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

3.1 IP Address Virtual Host


The Virtual Host directive in the httpd.conf configuration file is used to set the values of
ServerName, DocumentRoot, ErrorLog and TransferLog or Custom Log configuration directives
to different values for each virtual host.
Multiple websites can be served from one computer, even if they have different hostnames. Each
host name that is served from the single computer that hosts them all, is referred to as a virtual
host. There are two ways provided by Apache for setting up virtual hosts on a single computer,
IP based and Name based.
IP based virtual hosts use the IP address of the connection to determine the correct virtual host.
Hence, a unique IP address is required for each host. With name based virtual hosting, Apache
Web server relies on the client to deliver the host name as part of the HTTP leaders sent to
Apache. Using this technique, many different virtual hosts can share the same IP address.
Apache can be configured to support .multiple virtual hosts either by running a separate httpd
daemon for each hostname, or by running a single httpd daemon, which supports all the virtual
hosts.
If separate httpd daemons must be run for each host, separate installations of Apache for each
virtual host have to be created. For each installation, use the Listen directive in the httpd.conf
configuration file to select which IP address or virtual host that daemon services
For example, Listen 192.168.0.1:80.
A single http daemon can also be used to service to the main server and all its virtual hosts. If a
moderately large Intranet environment is required, different websites for various departments or
projects may have to be setup. Each of these websites lie on a single Linux server, configured to
use multiple interfaces with independent host names and IP addresses (i.e. Virtual Domains). The
first step is to set up multiple interfaces on the Ethernet card that connects the Linux Server to
the network.
The existing interface will be eth0. Use the ifconfig command to add a new interface to it:
/sbin/ifconfig eth0:1192.168.0.200
Now add a route to the new interface:
/sbin/route add -host 192.168.0.200 dev eth0:1
Make sure the 192.168.0.200 (or whatever is chosen) is a reserved IP address and cannot by
dynamically assigned by any DHCP server that may also be servicing the network. Ping the new
IP address as any other address on the network.
Next edit the name server files to give this interface a suitable name. If the Linux box is also
running a DNS service configure it from there.
Change to the directory /var/named. Using any ASCII editor, edit the file
named.xxx.yyy.forward (where xxx.yyy is your domain name). Scroll down the list until you

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>

3.2 Name based Virtual Host


Using the new name based virtual hosts is quite easy, and superficially looks like the old method.
The notable difference between IP-based and Name-based virtual host configuration is the Name
Virtual Host directive, which specifies a single IP address that should be used as a target for
name-based virtual hosts.
For example, suppose that both sct.perlproj.com and sct.phpproj.com point to the IP address
192.168.0.1. Then simply add the following to the Apache's httpd.conf:
NameVirtualHost192.168.0.1
<Virtual Host 192.168.0.1>
DocumentRoot /var/www/sct/perlproj
ServerName sct.perlproj.com
</VirtuaIHost>
<Virtual Host 192.168.0.1>
DocumentRoot /var/www/sct/phpproj
ServerName sct.phpproj.com
</VirtuaIHost>
The Following entries should be appended to the hosts file available under /etc directory:
192.168.0.1 sct.perlproj.com
192.168.0.1 sct.phpproj.com

3.3 Dynamic Virtual Hosting


Apache modules are code segments that are written to work with Apache because they are
written using Apache's API specifications. They can be statically loaded into the Apache Web
server executable by being added using appropriate instructions when compiling the Apache

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.

3.4 Server side includes


Create a file called lamp under /var/www.
Make the following entry in the httpd.conf file found in /etc/httpd/conf directory.
Server name 192.168.0.1:80
NameVirtualHost 192.168.0.1
<VirtualHost 192.168.0.1>
ServerAdmin webmaster@sct.com
DocumentRoot /var/www/lampp
ServerName sct.lampptraning.com
ErrorLog /var /www/lampp/logs/error_log
</Virtual Host>
The Following entry should be appended to the hosts file, found in, /etc directory:
192.168.0.1 sct.lampptraning.com

Registering The Changes Made In The httpd.conf With Apache2

After making any changes to the httpd.conf ensure to restart the apache server to apply
new changes. This can be done by:

Stop the Apache2 HTTPD service:

# /usr/local/apache2/bin/apachectl stop

Start the Apache2 HTTPD service:

# /usr/local/apache2/bin/apachectl start

3.5 Assignment Questions on Unit 2


Short answer questions (2 marks)
1. What are two versions of Apache?
2. List any two important features of Apache
3. How do you verify integrity of downloaded Apache Web Server?

25
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

4. Explain ServerType Environment entry in httpd.conf file


5. Explain ScreenBoardFile Environment entry in httpd.conf file
6. Explain MinSpareServers & MaxSpareServers environment entries in httpd.conf file
7. Explain DocumentRoot environment entry in httpd.conf file
8. Explain MaxKeepAliveRequests environment entry in httpd.conf file
9. Explain UserDir environment entry in httpd.conf file
10. What is the use of .htaccess files
11. What is the use of VirtualHost directive in the httpd.conf file
12. Differentiate IP based Virtual Hosts and Name based Virtual Hosts

Long answer questions


1. Write a note on configuring Apache Web Server
2. Write a note on Apache2 installation process
3. List and explain any FIVE important entries in httpd.conf file
4. Explain the following entries in httpd.conf
a. ScoreBoardFile b. MaxKeepAliveRequests c. ServerAdmin
d. DocumentRoot e. DirectoryIndex
5. Explain how one can add additional options to directories? Give examples.
6. List any five values to the options directives
7. Explain IP based Virtual Host
8. Explain Name based Virtual Host
9. Write a note on Apache Modules
10. Give a sample httpd.conf configuration file for the LAMP framework.

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

Figure : Standard Two tier Architecture.

Application Server Database


server

Figure : Standard three tier Architecture.

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.

Locking in on the changes

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.

Other Colorations When Developing Commercial Applications


All commercial applications capture, validate and store business data for manipulation later. The
capturing of business data is always done via a form. Once the form captures business data, it is
validated using program code that is part of the form's code base.
This is usually the first problem area in HTML. When HTML is used to craft a form, only a few
script;'1g languages are allowed to be used within the HTML code base. Examples of "these are,
Java Script, JScript, VB Script and so on.

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).

4.2 PHP and the web server architecture model

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

Decomposing the server side architecture.

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.

4.3 Over view of PHP capabilities

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.

4.4 CGI vs Shared object Model


Common Gateway Interface (CGI) is a basic way to create dynamic web pages. CGI is a
standard for communication between a client and the server. CGI scripts can be written in
almost any language. Perl is well suited to the types of text processing common for many
tasks, such as search engines and forms interfaces. Other benefits of Perl include portability,
ease of programming and overall computational power and performance. And to top it off,
the Perl module CGI.pm is a useful way to make Perl CGI script writing quick and easy.
CGI scripts can do simple things that require no input from the client, such as displaying the
current time or a random banner when a web page is accessed. Or they can do more
complicated tasks involving posted form data from the client, such as entering a credit card
number, searching a database and returning the information, and filling out a form.

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.

Figure: CGI model


The header is a very important piece of information that is sent back to the browser because it
tells the browser how to render the data that follows. The primary piece of information that is
sent in the header is the Content- l2e. If the header contains content-type: text/plain, the browser

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.

Click on the link <MySQL Version Number>Production release (recommended).

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

RPM Name Functionality


MySQL-4.0MySQL-server-4.0.17-0.i386.rpm The actual MySQL Database Engine
MySQL-client-4.0.17-0.i386.rpm The interactive character based MySQL
client
MySQL-shared-4.0.17-0.i386.rpm The shared libraries (Iibmysqlclient.so)
that certain languages and applications
need to . dynamically load and use
MySQL
MySQL-shared-compat-4.0.17-0.i386.rpm The shared libraries for both MySQL 3.23
(For Backward Com patibility and
MySQL 4.0
MySQL-embedded-4.0.17-0.i386.rpm The embedded M 5 L server library
MySQL -devel-4.0.17-0.i386.rpm The Libraries and Include files compile
other MySQL clients, such as the Perl
modules for development
MySQL-bench-4.0.17-0.i386.rpm The RPM required to benchmark (test-
suite) the MySQL installation. Requires
Perl and the DBD::mysql module
MySQL-Max-4.0.17-0.i386.rpm The mysqld-max server version, which
includes Innodb tables

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

<Sys prompt> mysqladmin version

This results the following informations in the screen.

mysqladmin Ver 8.40 Oistrib 4.0.17, for pc-linux on i686 B


Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
This software comes with ABSOLUTELY NO WARRANTY. This is free software
and you are welcome to modify and redistribute it under the GPL license
Server version 4.0.17-Max

Protocol version 10

Connection Localhost via UNIX socket

UNIX socket /var/lib/mysql/mysql.sock

uptime: 36 min 28 sec

Threads: 1 Questions: 7 Slow queries: 0 Opens: 6 Flush tables: 1


Open tables: 0 Queries per second avg: 0.003

And the system prompt reappears.

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

<SystemPrompt> rpm -e MySQL-c1ient


<SystemPrompt> rpm -e MySQL-bench
<SystemPrompt> rpm –e MySQL-embedded
<SystemPrompt> rpm -e MySQL-shared
<SystemPrompt> rpm -e MySQL-devel
<SystemPrompt> rpm -e MySQL-server

<System Prompt> rpm -e --nodeps MySQL-server

This will forcibly remove the RPM without the requirement of removing the dependencies.

Installing MySQL RPMs into the Linux Server.

Log in as root. Alternatively log in as any Linux user and su to root.


Create a subdirectory under / to copy the RPMs downloaded into. eg: /mysqlrpms
<System Prompt> cd /
<System Prompt> mkdir mysqlrpms
<System Prompt> cd mysqlrpms
Then copy the RPMs from wherever they have been downloaded into this subdirectory.
Once done /mysqlrpms should contain:

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

To install RPMs individually, do the following:


<System Prompt> rpm –ivh MySQL-4.0MySQL-server-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.

<System Prompt> rpm –ivh MySQL-client-4.0.17-0.i386.rpm

This installs MySQL database engine- client.


Once the MySQL database engine and its client RPMs have installed successfully, the Mysql
database management system (DBMS) is ready to run on the Linux box.

Similarly the following rpm can be installed.

<System Prompt> rpm –ivh MySQL-shared-4.0.17-0.i386.rpm


35
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

<System Prompt> rpm –ivh MySQL-shared-compat-4.0.17-0.i386.rpm


<System Prompt> rpm –ivh MySQL-embedded-4.0.17-0.i386.rpm
<System Prompt> rpm –ivh MySQL -devel-4.0.17-0.i386.rpm
<System Prompt> rpm –ivh MySQL-bench-4.0.17-0.i386.rpm
<System Prompt> rpm –ivh MySQL-Max-4.0.17-0.i386.rpm

5.2 Post installed trouble shooting

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

5.3 MYSQL administration Commands-


$mysql –u root: This is a command used to connect to the MYSQL as a root user. This root
user is different from linux root user. Using this connection the administrator has all the
privileges in the MYSQL. He can create or modify the databases, users, various privileges to the
users etc.
In order to connect to MYSQL first of all the service should be started. The command to start the
MYSQL service is
# chkconfig mysqld on
# /etc/init.d/mysqld start
Once the root user is connected the prompt is shown as follows
Mysql>

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

To create a databse the following command is used


Mysql> CREATE DATABASE name of the database

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.

Mysql>USE name of the database;

CREATE TABLE and SHOW TABLE Command


Each table within the database must be defined and created. This is done with the CREATE
TABLE command.
Create a table named age_information to contain an individual is first name, last name, and age.
MySQL needs to know what kind of data can be stored in these fields. In this case, the first name
and the last name are character strings of up to 20 characters each, and the age is an integer:
The Syntax of the same is :

mysql> CREATE TABLE age_information (


-> lastname CHAR(20),
-> firstname CHAR(20),
-> age INT
-> );
Query OK, 0 rows affected (0.00 see)

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

Mysql> SHOW TABLES;


The various data types used in the table are
For integers
TINYINT is an 8 bit integer having the values ranging from -128 to 127 for signed integer and 0
to 255 for unsigned integer.

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

Data types for Date


DATE YYYY-MM-DD
DATETIME YYYY-MM-DD HH:MM:SS
TIMESTAMP YYYYMMDDHHMMSS or YYMMDDHHMMSS or
YYYYMMDD or YYMMDD
TIME HH:MM:SS
YEAR YYYY or YY
The different types of the character data types are listed below. These data types are case
sensitive.
VARCHAR Variable-length string upto 255 characters.
TINYBLOB Maximum length 255 characters
TINYTEXT Maximum length 255 characters
BLOB Maximum length 65535 characters
TEXT Maximum length 65535 characters
MEDIUMBLOB maximum length of 16777215 characters
MEDIUMTEXT maximum length of 16777215 characters

38
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

LONGBLOB maximum length of 4294967295 characters


LONGTEXT maximum length of 4294967295 characters

The DESCRIBE Command


The DESCRIBEcommand gives information about the fields in a table. The fields created
earlier-lastname, firstname, and age-appear to have been created correctly.

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

The UPDATE Command


Since the database is about people, information in it can change (people are unpredictable like
that). For instance, although a person's birthday is static, their age changes. To change the value
in an existing record, we can UPDATE the table. Let's say the fictional Larry Wall has turned 47:

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

The DELETE Command


Sometimes we need to delete a record from the table (don't assume the worst-perhaps the person
just asked to be removed from a mailing list, which was opt-in in the first place, of course). This
is done with the DELETE command:
mysql> DELETE FROM age_information WHERE lastname = Raymond';

44
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Query OK, 1 row affected (0.00 sec)

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

6.1 Obtaining, Installing and configuring PHP4


Here are a quick set of steps that will build PHP as a dynamic Apache module (DSO) for with
MySQL support.
Before Installation following important points should be considered.

• 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

This will extract php-4.3.4.tar file from the php-4.3.4.tar.gz file.


The php-4.3.4.tar.gz will be replaced by the php-4.3.4.tar in the same sub directory. The
contents of php-4.3.4.tar must be extracted after which the actual install process can begin.
To extract the content of php-4.3.4 Use the following command

# tar –xvf php-4.3.4.tar


The extraction process creates a directory called php-4.3.4 into which the contents of the tar
file are extracted. This is just one level below the jphp4 subdirectory. Change to this
sub-directory:

# cd php-4.3.4

6.3 PHP configuration parameters and php.ini file.


# ./configure --with-mysql --with-apxs2
If an error is generated which indicates that the apxs script cannot be found, look for it
on the system (i.e. use Find Files) and if found, note down the path to the file. Then provide the
full path such as: --with-apxs2=/path/to/apxs

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

6.4 Binding The PHP4 Installation With Apache2


The only thing left to do is to edit Apache's httpd.conf file and make sure the PHP 4 mime type
is there and uncommented. The line should look like this:
AddType application/x-httpd-php .php
Ensure that the PHP module is loaded by noticing the following line in the httpd.conf file
LoadModule php4_module modules/libphp4.so
If this line does not exist then insert the same in the httpd.conf file.

The php files will be served up after restarting the apache server.

6.5 Registering The Changes Made In The httpd.conf With Apache2


Stop the Apache2 HTIPD service:
# /usr/local/apache2/bin/apachectl stop
Start the Apache2 HTIPD service:
# /usr/local/apache2/bin/apachectl start

Sample of httpd.conf File For The LAMPP Framework


The following entries should be exists in the httpd.conf file available under /etc/httpd/conf
directory:
NameVirtualHost 192.168.0.1
<VirtualHost 192.168.0.1>
ServerAdminwebmaster@sct.com
DocumentRoot /var/www/lampp
ServerNamesct.lampptraning.com
ErrorLog/var/www/lampp/logs/errorjog
</VirtuaIHost>
AddType application/x-httpd-php .php

LoadModule php_4 module modules/libphp4.so

49
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Chapter 7
PHP LANGUAGE CORE

7.1 Variables, constants, data types and operators


Variables are what are used to store a user value for later use. There are different kinds of
variables in PHP. For example, age may have to be referenced so it would be nice to define age
only once, and then just refer to it later when required. When the value in age must change,
simply update the definition of age. Then, all other calculations that refer to the age
automatically provide the correct output.
All variable names must start with the $ character. After that there must be a letter. The rest of
the name can consist of both letters and numbers. The following are three examples of valid
names for a variable: $name, $address2 and $colour_30. The _ (underscore) character is often
used in variable names. It is used as a replacement for space, since space is an illegal character in
a variable name.
Once a variable is named it needs to be assigned a value to be used in any program. Assigning a
value to variable is done as follows:

$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;

This code produces the following output:


Hello, my first name is Chhaya.
Hello, my last name is $Iast_name.

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

PHP Arithmetic Operators

Operator Name Example Result


+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y

The example below shows the different results of using the different arithmetic operators:

<!DOCTYPE html>
<html>
<body>

<?php
$x=10;
$y=6;

echo ($x + $y);


echo "<br>";
echo ($x - $y);

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 output will be


16
4
60
1.6666666666667
4

PHP Assignment Operators

The PHP assignment operators is used to write a value to a variable.


The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the assignment expression on the right.

Assignment Same as... Description


The left operand gets set to the value of the expression on the
x=y x=y
right
x += y x=x+y Addition
x -= y x=x–y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus

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 output will be


10
120
25
30
2
3

PHP String Operators

Operator Name Example Result


$txt1 = "Hello"
Now $txt2 contains "Hello
. Concatenation $txt2 = $txt1 . "
world!"
world!"
Concatenation $txt1 = "Hello" Now $txt1 contains "Hello
.= assignment $txt1 .= " world!" world!"

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>

The output will be

Hello world!
Hello world!

PHP Increment / Decrement Operators

Operator Name Description


++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

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>

The output will be

11
10
4
5

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result


== Equal $x == $y True if $x is equal to $y
True if $x is equal to $y, and
=== Identical $x === $y
they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
True if $x is not equal to $y, or
!== Not identical $x !== $y
they are not of the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
True if $x is greater than or equal
>= Greater than or equal to $x >= $y
to $y
True if $x is less than or equal to
<= Less than or equal to $x <= $y
$y

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

var_dump($x == $y); // returns true because values are equal


echo "<br>";
var_dump($x === $y); // returns false because types are not equal
echo "<br>";
var_dump($x != $y); // returns false because values are equal
echo "<br>";
var_dump($x !== $y); // returns true because types are not equal
echo "<br>";

$a=50;
$b=90;

var_dump($a > $b);


echo "<br>";
var_dump($a < $b);
?>

</body>
</html>

The output will be

bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)

PHP Logical Operators

Operator Name Example Result


and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
True if either $x or $y is true, but
xor Xor $x xor $y
not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

57
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

PHP Array Operators

The PHP array operators are used to compare arrays:

Operator Name Example Result


Union of $x and $y (but
+ Union $x + $y duplicate keys are not
overwritten)
True if $x and $y have the same
== Equality $x == $y
key/value pairs
True if $x and $y have the same
=== Identity $x === $y key/value pairs in the same order
and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y

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>

The output will be

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)

7.2 Decision making


Control-structures are traditionally used to control the flow of program execution. In PHP scripts
often different things need to get done based on different reasons. This means that the script has
to be able to make a decision and then get some work or the other done.
Conditional statements in PHP script do this.
In PHP there are two conditional statements:
• if ( ...else) statement - This statement is used if a block of code must execute when a
condition specified in the code is tested and the test returns the value TRUE. Another
block of code will execute when the same condition specified in the code is tested and
the test returns the value FALSE
• switch statement - This statement is used to select one, from many code blocks, for
execution

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>

The output looks like this


Have a good day!

If multiple lines to be executed then { } bracket should be used.


<HTML>
<HEAD><TITLE>GreetingUsing Multiple Lines</TITLE> </HEAD>
<BODY>
<?php
$x=10;
if ($x==10)
{
echo "Hello<BR>";
echo "Good morning<BR>";
}
</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.

The Switch Statement


If one of many code blocks has to be selected for execution, use the Switch statement.
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

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

echo "Your favourite colour is red!";


break;
case "blue":
echo "Your favourite colour is blue!";
break;
case "green":
echo "Your favourite colour is green!";
break;
default:
echo "Your favourite colour is neither red, blue, or green!";
}
?>
</body>
</html>
The output will be
Your favourite colour is red!

7.3 Flow control and loop

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.

In PHP, we have the following looping statements:

• 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

while (<some condition which is true>)

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

while (list($key, $val) = each($array))

{ echo”<p>$key => $val</p>\n"; }

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:

list($a, $b, $c, $d) = array(l, 2, 3, 4); // $a == 1, $b == 2, $c == 3, $d == 4

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);

/ / Start the table


echo "<TABLE>\n";
/ / Print the first row with headers
echo "<TR>\n";
echo" <TH>Name</TH>\n";
echo" <TH>Age</TH>\n";
echo "</TR>\n";
/ / Ensure that the each() function starts from the start:
64
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

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 statement

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>

The output will be

The number is: 1


The number is: 2
The number is: 3
The number is: 4
The number is: 5

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:

7.4 Arrays and array operations

The for loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init counter; test counter; increment counter) {


code to be executed;
}

Parameters:

• init counter: Initialize the loop counter value


• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value
66
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

The example below displays the numbers from 0 to 10:

<!DOCTYPE html>
<html>
<body>

<?php
for ($x=0; $x<=10; $x++) {
echo "The number is: $x <br>";
}
?>

</body>
</html>

The output will be

The number is: 0


The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.

Syntax

foreach ($array as $value) {


code to be executed;
}

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

foreach (array-expression as $key => $value) statement

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

foreach ($colors as $value) {


echo "$value <br>";
}
?>

</body>
</html>

The output will be

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

foreach ($age as $name => $value)


{
echo "\$age[$name] => $value.\n";
?>
</BODY>
HTML>
The following example demonstrates multi-dimensional arrays:

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

7.5 Two dimensional and multidimensional arrays

A multidimensional array is an array containing one or more arrays.

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.

• For a two-dimensional array you need two indices to select an element


• For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of


arrays).

First, take a look at the following table:

Name Stock Sold

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)
);

for ($row = 0; $row < 4; $row++) {


echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>

</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)
);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";


echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

</body>
</html>
The output will be

71
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Volvo: In stock: 22, sold: 18.


BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
We can also put a For loop inside another For loop to get the elements of the $cars array (we still
have to point to the two indices):
<!DOCTYPE html>
<html>
<body>

<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

for ($row = 0; $row < 4; $row++) {


echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>

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

7.6 Strings and string operations


A string is a sequence of characters, like "Hello world!". PHP uses several functions related to
string operations

The PHP strlen() function

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>

The output will look like

12

The PHP strpos() function

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>

The output will look like


6
The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is
that the first character position in the string is 0, and not 1.
The complete list of the string functions is given below

Function Description

Returns a string with backslashes in front of the specified


addcslashes()
characters

addslashes() Returns a string with backslashes in front of predefined characters

bin2hex() Converts a string of ASCII characters to hexadecimal values

Removes whitespace or other characters from the right end of a


chop()
string

chr() Returns a character from a specified ASCII value

chunk_split() Splits a string into a series of smaller parts

convert_cyr_string() Converts a string from one Cyrillic character-set to another

convert_uudecode() Decodes a uuencoded string

convert_uuencode() Encodes a string using the uuencode algorithm

count_chars() Returns information about characters used in a string

crc32() Calculates a 32-bit CRC for a string

crypt() One-way string encryption (hashing)

echo() Outputs one or more strings

explode() Breaks a string into an array

fprintf() Writes a formatted string to a specified output stream

74
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Returns the translation table used by htmlspecialchars() and


get_html_translation_table()
htmlentities()

hebrev() Converts Hebrew text to visual text

hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>

hex2bin() Converts a string of hexadecimal values to ASCII characters

html_entity_decode() Converts HTML entities to characters

htmlentities() Converts characters to HTML entities

htmlspecialchars_decode() Converts some predefined HTML entities to characters

htmlspecialchars() Converts some predefined characters to HTML entities

implode() Returns a string from the elements of an array

join() Alias of implode()

lcfirst() Converts the first character of a string to lowercase

levenshtein() Returns the Levenshtein distance between two strings

localeconv() Returns locale numeric and monetary formatting information

Removes whitespace or other characters from the left side of a


ltrim()
string

md5() Calculates the MD5 hash of a string

md5_file() Calculates the MD5 hash of a file

metaphone() Calculates the metaphone key of a string

money_format() Returns a string formatted as a currency string

nl_langinfo() Returns specific local information

nl2br() Inserts HTML line breaks in front of each newline in a string

number_format() Formats a number with grouped thousands

ord() Returns the ASCII value of the first character of a string

parse_str() Parses a query string into variables

print() Outputs one or more strings

75
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

printf() Outputs a formatted string

quoted_printable_decode() Converts a quoted-printable string to an 8-bit string

quoted_printable_encode() Converts an 8-bit string to a quoted printable string

quotemeta() Quotes meta characters

Removes whitespace or other characters from the right side of a


rtrim()
string

setlocale() Sets locale information

sha1() Calculates the SHA-1 hash of a string

sha1_file() Calculates the SHA-1 hash of a file

similar_text() Calculates the similarity between two strings

soundex() Calculates the soundex key of a string

sprintf() Writes a formatted string to a variable

sscanf() Parses input from a string according to a format

str_getcsv() Parses a CSV string into an array

str_ireplace() Replaces some characters in a string (case-insensitive)

str_pad() Pads a string to a new length

str_repeat() Repeats a string a specified number of times

str_replace() Replaces some characters in a string (case-sensitive)

str_rot13() Performs the ROT13 encoding on a string

str_shuffle() Randomly shuffles all characters in a string

str_split() Splits a string into an array

str_word_count() Count the number of words in a string

strcasecmp() Compares two strings (case-insensitive)

Finds the first occurrence of a string inside another string (alias of


strchr()
strstr())

strcmp() Compares two strings (case-sensitive)

76
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

strcoll() Compares two strings (locale based string comparison)

Returns the number of characters found in a string before any part


strcspn()
of some specified characters are found

strip_tags() Strips HTML and PHP tags from a string

stripcslashes() Unquotes a string quoted with addcslashes()

stripslashes() Unquotes a string quoted with addslashes()

Returns the position of the first occurrence of a string inside


stripos()
another string (case-insensitive)

Finds the first occurrence of a string inside another string (case-


stristr()
insensitive)

strlen() Returns the length of a string

Compares two strings using a "natural order" algorithm (case-


strnatcasecmp()
insensitive)

Compares two strings using a "natural order" algorithm (case-


strnatcmp()
sensitive)

strncasecmp() String comparison of the first n characters (case-insensitive)

strncmp() String comparison of the first n characters (case-sensitive)

strpbrk() Searches a string for any of a set of characters

Returns the position of the first occurrence of a string inside


strpos()
another string (case-sensitive)

strrchr() Finds the last occurrence of a string inside another string

strrev() Reverses a string

Finds the position of the last occurrence of a string inside another


strripos()
string (case-insensitive)

Finds the position of the last occurrence of a string inside another


strrpos()
string (case-sensitive)

Returns the number of characters found in a string that contains


strspn()
only characters from a specified charlist

Finds the first occurrence of a string inside another string (case-


strstr()
sensitive)

77
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

strtok() Splits a string into smaller strings

strtolower() Converts a string to lowercase letters

strtoupper() Converts a string to uppercase letters

strtr() Translates certain characters in a string

substr() Returns a part of a string

Compares two strings from a specified start position (binary safe


substr_compare()
and optionally case-sensitive)

substr_count() Counts the number of times a substring occurs in a string

substr_replace() Replaces a part of a string with another string

trim() Removes whitespace or other characters from both sides of a string

ucfirst() Converts the first character of a string to uppercase

ucwords() Converts the first character of each word in a string to uppercase

vfprintf() Writes a formatted string to a specified output stream

vprintf() Outputs a formatted string

vsprintf() Writes a formatted string to a variable

wordwrap() Wraps a string to a given number of characters

7.7 Functions, function declarations and parameter passing


The real power of PHP comes from its functions; it has more than 1000 built-in functions.

PHP User Defined Functions

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.

A user defined function declaration starts with the word "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!

Function names are NOT case-sensitive.

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>

The output will be


Hello world!

PHP Function Arguments

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 output will be


Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.

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

PHP Default Argument Value

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

echo "The height is : $minheight <br>";


}

setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>

</body>
</html>

The output will be

The height is : 350


The height is : 50
The height is : 135
The height is : 80

PHP Functions - Returning values

To let a function return a value, use the return statement:

<!DOCTYPE html>
<html>
<body>

<?php
function sum($x,$y) {
$z=$x+$y;
return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";


echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>

</body>
</html>

The output will be

5 + 10 = 15
7 + 13 = 20
2+4=6

81
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

The DATE()function

The date() function is used to format a time or a date.

Syntax:

string date ( string format [, int timestamp])

This function returns a string formatted according to the specified format.

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

7.8 Outputting the data include and require statements

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 &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>

To include the footer file in a page, use the include statement:

<!DOCTYPE html>
<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

84
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

</body>
</html>
The output will be

Welcome to my home page!


Some text.
Some more text.
Copyright © 1999-2014 W3Schools.com

Example 2

Assume we have a standard menu file called "menu.php":

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

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>

</body>
</html>
The output will be
Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP Tutorial

Welcome to my home page!


Some text.
Some more text.
85
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Example 3

Assume we have a file called "vars.php", with some variables defined:

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

<h1>Welcome to my home page!</h1>


<?php include 'vars.php';
echo "I have a $color $car.";
?>

</body>
</html>

The output will be

Welcome to my home page!

I have a red BMW.

PHP include vs. require

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>

<h1>Welcome to my home page!</h1>


<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>

86
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

The output will be

Welcome to my home page!


I have a .

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>

<h1>Welcome to my home page!</h1>


<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>
The output will be

Welcome to my home page!

7.9 Assignment Questions


Short answer questions (2 marks)
1. What is request/response communication paradigm?
2. List any two benefits in running PHP as a Web Server side scripts
3. List any two drawbacks in running PHP as a Web Server side scripts
4. List any four features of PHP
5. What is a PHP file? List its features.
6. Explain in brief MySql
7. Write commands to make sure that MySql starts at the time the machine boots
8. Differentiate database &d tables. Give commands to create database & tables in MySql
9. List different types of integer data types available in MySql
10. What is a BLOB? List different types of BLOBs available in MySql
11. Give sample httpd.conf file for the LAMP framework with PHP configuration entries.

87
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Long answer questions


1. With the help of a diagram explain the request/response Internet paradigm
2. Explain Server Side Internet Architecture of Apache with a neat diagram
3. Explain the execution of a CGI program with the help of diagram and example
4. List benefits and drawbacks in running PHP as Server Side Scripts
5. Write a note on MySQL data types
6. Explain with example the following MySQL commands (6)
a. CREATE TABLE b. INSERT c. SELECT
7. Explain different ways in which SELECT command is used in MySql.
8. Explain with example the following MySql commands
a. UPDATE b. DELETE c. DESCRIBE
9. Write a note on granting privilege for a new user on a database in MySql
10. Write a note on installing and configuring PHP

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.

File existence and verification


It is always a good practice to determine the existence of a file before attempting to work with it.
File_exists() and is_file() are the functions used.
file_exists()
The file_exists() function will ensure that file exists, returning true if it does, and false otherwise.
Syntax
bool file_exists( string file)
Verifying the existence of a file an example
$filename= “userdata.txt”;
if(!file_exists($filename))
print “$filename doesnot exists”;

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:

File Modes Description


r Readonly. File pointer at the start of the file
r+ Read/Write. File pointer at the start of the file
w Write only. Truncates the file (overwriting it). If the file doesn't exist,
fopen() willtry to create the file
w+ Read/Write. Truncates the file (overwriting it).' If the file doesn't exist,
fopen() will try to create the file
a Append. File pointer at the end of the file. If the file doesn't exist,
fopen() will try to create the file
a+ Read/Append. File pointer at the end of the file. If the file doesn't exist,
fopen() will try to create the file
x Create and open for write only. File pointer at the beginning of the file.

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);

Reading from a file


The ability to read from a file is of obvious importance. The following are a set of functions
geared toward making file reading an efficient process. It will be seen that the syntax of many of
the functions are almost replicas of those used for writing.
The feof() function is used to determine if the end of file is true.
The fread() function reads from an open file.

syntax:

string fread (int filepointer, int length)

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

$file = fread($fh, filesize($fh));


print $file;
fclose($fh);
filesize() is used to retrieve the byte size of lampp.txt. This will ensure that fread()will read in the
entire contents of the file.
Reading a character from a file
The fgetc() function returns a string containing one character from the file pointed to the file
pointer or returns false on reaching the end of file.
Syntax:
string fgetc (int filepointer)
The example below reads a file character by character, until the end of file [feof()] is true:
<?php .
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file. ");
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
fclose($f);
?>
Writing to a file
The fwrite() function will simply write the contents of a string to a file specified by a filepointer.
Syntax:
int fwrite (int filepointer, string string [, int length])
If the optional input parameter length is provided, writing will stop either after length characters
have been written or after the end of string has been reached whichever is earlier.
The following example will show how to write to a file.
<?
$data= "Sharanam Shah. Makanji Mansion. Mumbai.";
$filename= "mydata.txt";
/ If file exists and Is writable
if(is _writeable( $filename)
{
/ Open file and place file pointer at end of file
$fh = fopen($filename, "a+");
/ Write $data to file
$success= fwrite($fh, $data);
/ / Close the file
fclose($fh);

92
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

}
Else
{ print "Could not open $filename for writing"; }
?>

8.2 Processing HTML from input from the user


The example below displays a simple HTML form with two input fields and a submit button:
<!DOCTYPE HTML>
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

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

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:

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>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

The output will be

and "welcome_get.php" looks like this:

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</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.

GET vs. POST

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.

When to use GET?

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.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

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.

8.3 Creating a dynamic HTML Form with PHP


Dealing with forms
When building a web site, sooner or later a form will be needed. There are a number of different
forms that can be used to input information. Some require entering information using keyboard,
while others require selecting one or more choices by clicking with a mouse. Yet others simply
involve a hidden form value that is embedded in the form itself and is not intended to be
modified by the user.
Forms are the best way of gathering data from visitors. Forms can be as small as a login form, or
as large as a membership subscription form asking for lots of input. Obviously, the bigger the
form, the more information there is to process, and the greater the challenge.
It is possible to have multiple forms on the same page, so there must be some way to distinguish
one form from the other. Furthermore, there must be a way to tell the client's browser what to
once the user initiates some form action (usually by clicking a button). Both of these needs
retaken care of by enclosing form entities as follows:
<FORM Action="some_action" Method="post">
... form entities ...
</FORM>
Two important elements make up this enclosure:
• Action - The value passed to the keyword Action specifies what script should process the
form at the Web server side.
• Method - The method specifies how the data captured by the will be sent to the script.

95
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

There are two possible methods:

• 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.

SEND FORM INFORMATION VIA MAIL


While the idea of simply displaying the entered user information to the browser is appealing, it
doesn’t do too much for us in the sense of actually processing the user input in a meaningful
way. One way to process this information could be to send it to a particular email address, for
example, the site administrator's.
This can be done by creating a small form, which captures some user information like Name,
Email Address, Products Purchased, Comments etc and a php script which actually transfers the
information captured via the form to a desired email address mentioned in the script.
96
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

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

boolean mail(string recipient, string subject, string message [, string addl_headers])


The recipient is the person to whom the mail has to be sent, the subject is, of course, the subject
of the email. The message is the textual body of the email, and the optional input parameter
addl_headers is used to supply any additional header information (such as HTML formatting)
that is sent along with the email.
The codespec for a emailinfo.php is
<?php
// Change -$recipient to be the recipient of the form information
$recipient= "admin@ivanbayross.com";
// Email subj ect
$subject= "User Comments from LPOST['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 LPOST['name'] for taking a moment to send us your comments!";
?>

Output:
Thank you Sharanam Shah for taking a moment to send us your comments!

VALIDATE FORM INFORMATION


One efficient way to ensure that users understand which form fields are missing or not being
accepted is to display explicit error messages. The idea behind this type of error checking is to
check each field separately, ensuring that it is not empty and that illegal data has not been
entered. If the field is OK, move on to the next field. Otherwise, display an appropriate error
message, set a flag that will later be used as a means for sending the information as an email, and
move on to the next field, repeating this process until the entire form is checked.
The codespecs is as shown below
<?php
// Initializing a flag to handle errors
$error_f1ag= "n";
// Ensure that the name variable is not empty
if ($name == “”)
{
print "<FONT Color=\"red\">* You forgot to enter your name!</font><BR>";
$error_flag = "y";
}
// Ensure that tha emall variable is not empty
if ($email == III') :
{
print "<font color=\"red~">* You forgot to enter your email!</font><br>";
$error_flag = "y";
}
if ($error_f1ag== "n")
98
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

{
// 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.

TIPS and TRICKS for DESIGNING FORMS


• Always include the MAXLENGTH attribute in text fields to limit the size of field. This will
save the script from an unexpected error
• If a field's value is to be displayed without allowing the user to change it, use READONLY
boolean attribute set and also set it's TABINDEX attribute's value to -1
For example:
<INPUT Type="text" Name="price" READONLY Tabindex="-l">
• If multiple checkboxes are placed on a form with the same name, PHPwill accept only the
value of the last check box (in source order). In case all the values are needed as an array,
put brackets [ ] after the NAMEattributes of each checkbox

8.4 Using GET, POST, SESSION and COOKIES variable


COOKIES
A cookie is often used to identify a user.
A cookie is a small file, containing pure text material and nothing else that the Web server sends
to a client computer when contacted via its Browser. A cookie is saved at the client end by its
Browser, in a special sub directory on the HOD.
Each time the client computer requests for any resource from the Web server that set the
cookie via its Browser, the browser will automatically send the cookie along with the resource
request to the Web Server. The contents of the cookie will then be available at the Web server
end again. Using PHP, a cookie can be both created and/or retrieved.
How to create cookies?
The setcookie() function is used to create cookies.
Syntax:
setcookie(name, value, expire, path, domain);
The following example sets a cookie named "uname" - that expires after ten hours.
<?php
setcookie("uname", $name, timeO+36000);
99
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

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

<title> <?=$site_name;?> </title>


</head>
<body bgcolor="black" text="white" Iink="red" alink="purple" vlink="blue">
body.inf
Ivan Bayross is an M.Tech in DBMS from Manchester U.K
Hisspecialization is application development using O-RDBMS.
Hehas auth'ored and published more than 30 books tightly focused on commercial
application development
Heis currently Chairman and M.D. of a software development house in Mumbai, India.
Hisdomain expertise is:
Oracle 9iAS, Developer 2000,
VisualBasic, Delphi,
Java- JDK 2.0,
SystemsDesign,
Design validation,
ProjectManagement,
User and Technical Documentation.

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

9.2 Connecting to a mysql database


Before any interactive' HTML form based w,ork can 'be done PHP must be able to connect to a
Mysql database. If PHP is not connected to the MySQL database then all commands forwarded
to the database via PHP, will fail.
A good practice for using databases, is to specify the username, password and database name
right at the top of the code spec so that if a change is required at a
later date, only one line at the top of the code spec has to be changed.
For example:
$username= "username";
$password = "password";
$database= "your_database";
Here is the general order of events that take place during the MySQL server communications
process:
1. Establish a connection with the MySQL server. If the connection .attempt fails, display
an appropriate message and exit process
2. Select a database on the MySQL server. If select the database fails, display an appropriate
message and exit process. It's possible to simultaneously have several databases open for
querying
3. Perform necessary queries on selected database(s)
4. Once the querying is complete, close the database server connection

Connecting to the database.


Issue the following command to the PHP interpreter to create a connection with the Mysql
database:
mysql_ connect(local host,$username,$password);
The function mysql_connect{) is used to establish an initial connection with the MySQL server.
Once a successful connection is established, a database residing on that server can be selected.
This line tells PHP to connect to the MySQL database engine running in the memory (RAM) of
the localhost (localhost indicates that the MySQL database is running on the same computer that
the PHP interpreter is running on). Unless the web site hosting company specifies otherwise
always use localhost.

9.3 Selecting a database


After having connected to the MySQL database engine, running in the Web server's
memory(RAM) a database existing on the HDD must be selected. This must be a database to
which the username specified has access.
The following command does this:
@mysql_select_db($database) or die("Unable to select database");
This tells PHP to select the database stored in the variable $database (which has been set
programmatically earlier). If the PHP interpreter cannot connect to the MySQL database
specified, it will stop executing the PHP script and output the message, Unable to select
database. This extra or die part is good to leave in, as it provides some user defined error
handling but it is not essential.
The input parameter database_name should be selected and assigned an identification handle
returned by mysq'-select_db().
Example:
<?php

104
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

@mysq'-connect("localhost", "ivan", "ivan2306") or die("Could not connect to


MySQLserver!"); .
@mysql_select_db("inventory") or die("Could not select company database!");
?>
If there is only one database selection, there is no need to return a database 10. However, as with
mysql_connectO, when multiple databases are open, the database 10 must be returned so there is
a way to specify exactly on which database the queries are to be fired otherwise the most
recently opened link is used.

9.4 Building and sending the query to database


Now since a successful connection to the MySQL database has been established and the database
to be used is selected, MySQL commands can be fired to specific database table/s .
There are two ways of executing a command. One is to just enter the command in PHP. This
technique is used if there are no results expected (i.e. output) from running of the command.
The other way is to define the command as a variable. This technique ensures that the results of
the operation will be saved in the variable.
A command looks like this
mysql_query($query);
The function mysq_query() provides the functional interface from which a database can be
queried. The input parameter query corresponds to an SQL query. The useful thing about using
this technique is that the same command can be repeated over and over again without learning
new ones, all that needs to be done is to change the variable.
Depending on, the type of query, mysql_query() has different outcomes. In a successful SELECT
sql statement, a result ID is returned that can subsequently be passed to mysql_resultO so that
selected data can be formatted and displayed to the screen. If the query fails, FALSE is returned.
Furthermore, the number of rows that have been selected can be determined by executing nysql-
num_rows(). In the case of SQL statements involving INSERT, UPDATE, REPLACE, or
DELETE, the function mysql_affected_rows() can be called to determine how many rows were
affected by the query.

9.5 Inserting and updating the data


Now return to the inventory database created earlier. Add a block of information to the database
table custmast:
$query="Insert into custmast(custid, fname, lname) values('C100',
‘Sharanam’, 'Shah') ";
$query is used because the ANSI SQL Insert statement is being assigned to this variable.
INSERT INTO custmast tells the PHP interpreter to insert into a database table called custmast
the values enclosed in the brackets, which follow. Whatever is in the brackets contains all the
formation to be added to the table custmast.

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

@mysqLselect_db("inventory") or die("Could not select company database!");


// declare query
$query= "Insert into custmast(custid, fname, lname)
values (‘C100’, 'Sharanam’, 'Shah') ";
// execute query
$result = mysqLquery($query);
// determine the number of rows that have been affected.
print "Total rows inserted: ".mysqLaffected_rows();
// Close the connection
mysql_c1ose();
?>
Output:
Total rows inserted: 1

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:

<FORM Action="insert.php" Method="post">


Customer 10: <INPUT Type = "text" Name="custid"><BR>
First Name: <INPUT Type="text" Name="fname"><BR>
Last Name: <INPUT Type="text" Name="lname"><BR>
<INPUT Type="Submit" Value="Submit">
</FORM>
Edit the PHP script written earlier. Instead of hard coding blocks of information into the
input into database table, use variables instead:
<?php
$username= "root";
$password="";
$database= "inventory";
// connect to the server and select a database.
@mysql_connectClocalhost, $username,$password);
or dieC"Could not connect to MySQL server!");
@mysql_select_dbC"inventory") or dieC"Could not select company database!");
// declare query
$query = "Insert into custmast (custid, fname, lname)
values($_POST['custid'], $_POST['fname'], $_POST['lname'])”;
// execute query
$result = mysql_queryC$query);
// determine the number of rows that have been affected.
print "Total rows inserted: ".mysql_affected_rows());
// Close the connection
mysql_c1ose();
?>
This script should be saved as insert.php so that HTML form can invoke it on demand.

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.

Outputting the data


Now that there is at least one record, (if not many more), in the MySQL database table custmast
this data needs to be output (extracted from) custmast using PHP.
The first command must be a MySQL query made up like this
SELECT * FROM CUSTMAST;
This is a basic MySQL command, which tells the PHP script to select all the records in the
contacts table. Because there will be output from this command it must be executed with the
results being assigned to a variable.

$query="SELECT* FROM custmast";


$result= mysq1_ query($query);
In this case, a result ID is returned that can subsequently be passed to mysql_result() so the
selected data can be formatted and displayed to the screen.

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.

9.6 Sample database routines and code segments


The final part of this script is to assign each record in the $result array to its own variable. The
following code does this:

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

$first= mysql_result( $result,$i,"first");


$last=mysq_result( $result,$i,”last");
There is no need to get the id field because there is no use for it in the current output page.

Combining the script


A full PHP script to output data from the $result 10. In this script the data is not formatted when
it is output

Closing the Connection To The Database


Themysql_close() closes the connection to the MySQL database engine. The PHP script will run
perfectly even if this command in not included, but too many open MySQL connections can
cause problems on the web site host server. It is good practice to always include this line once all
the database commands have been issued, (i.e; as the last line in the database section of the
PHPscript).

9.7 Assignment Questions on Unit 4

108
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Short answer questions (2 marks)


1. List rules to be followed while naming a variable in PHP
2. Differentiate use of ‘ and “ with strings
3. Differentiate echo and print statement in PHP
4. How to concatenate strings in PHP? Give example
5. List all logical operators available in PHP
6. Explain each() function with example
7. Explain list() function with example
8. List any four output options of phpinfo() function
9. Explain $_SERVER variable. List any two options of it
10. Explain Loader function. List any two options of it
11. Differentiate GET and POST methods
12. Explain with example $_POST autoglobal variable
13. Explain with example $_REQUEST autoglobal variable
14. Give syntax of mail() function in PHP
15. What is a cookie?
16. Which function is used to create a cookie in PHP? Give its syntax.
17. Differentiate include() and require() functions
18. List different file access modes which can be used with fopen() function in PHP

Long answer questions


1. Write a note on Strings in PHP
2. List and explain in brief (6)
a. Assignment operators
b. Comparison operators
3. Explain with syntax and example (consider apiece) if, switch, while, for, do..while, foreach
statements in PHP
4. Explain function declaration in PHP. Give example 5. Explain phpinfo() function with all
its output options.

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 is a stable, cross platform programming language.


• Though Perl is not officially an acronym but few people used it as Practical Extraction
and Report Language.
• It is used for mission critical projects in the public and private sectors.
• Perl is an Open Source software, licensed under its Artistic License, or the GNU General
Public License (GPL).
• Perl was created by Larry Wall.
• Perl 1.0 was released to usenet's alt.comp.sources in 1987
• At the time of writing thi tutorial, latest version of perl is 5.16.2
• Perl is listed in the Oxford English Dictionary.

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 and the Web

• 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.

• Perl's DBI package makes web-database integration easy.

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.

Perl is available on a wide variety of platforms:

• Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.)


• Win 9x/NT/2000/
• WinCE
• Macintosh (PPC, 68K)
• Solaris (x86, SPARC)
• OpenVMS
• Alpha (7.2 and later)
• Symbian
• Debian GNU/kFreeBSD
• MirOS BSD
• And many more...

Getting Perl Installation

The most up-to-date and current source code, binaries, documentation, news, etc. is available at
the official website of Perl:

Perl Official Website : http://www.perl.org/

You can download Perl documentation from the following site.

Perl Documentation Website : http://perldoc.perl.org

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.

Here is a quick overview of installing Perl on various platforms:

112
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Unix & Linux Installation


Here are the simple steps to install Perl on Unix/Linux machine.

• Open a Web browser and go to http://www.perl.org/get.html


• Follow the link to download zipped source code available for Unix/Linux.
• Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt.

$tar -xzf perl-5.x.y.tar.gz


$cd perl-5.x.y
$./Configure -de
$make
$make test
$make install

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:

(1) Interactive Interpreter:

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.

$perl -e <perl code> # Unix/Linux

Here is the list of all the available command line options:

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

-e program run Perl script sent in as program


file run Perl script from a given file

(2) Script from the Command-line:

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:

$perl script.pl # Unix/Linux

(3) Integrated Development Environment

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.

First Perl Program

Interactive Mode Programming:

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:

$perl -e 'print "Hello World\n"'

This execution will produce following result:

114
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Hello, world

Script Mode Programming

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

# This will print "Hello, World"


print "Hello, world\n";

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:

$chmod 0755 hello.pl


$./hello.pl

This execution will produce following result:

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

Perl File Extension


A Perl script can be created inside of any normal simple-text editor program. There are several
programs available for every type of platform. There are many programs designed for
programmers available for download on the web.

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:

# This is a comment in perl

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

# This is a single line comment


print "Hello, world\n";

=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

This will produce following result:

Hello, world

Whitespaces in Perl

A Perl program does not care about whitespaces. Following program works perfectly fine:

#!/usr/bin/perl

print "Hello, world\n";

But if spaces are inside the quoted strings then they would be printed as is. For example:

#!/usr/bin/perl

# This would print with a line break in the middle


print "Hello
world\n";

This will produce following result:

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.

Single & Double Quotes in Perl

You can use double quotes or single quotes around literal strings as follows:

#!/usr/bin/perl

print "Hello, world\n";


print 'Hello, world\n';

116
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

This will produce following result:

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';

This will produce following result:

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

This will produce following result:

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 = 10

117
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

This is case of single quote so variable value will be


interpolated. For example value of a = $a

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

$result = "This is \"number\"";


print "$result\n";
print "\$result\n";

This will produce following result:

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.

S.N. Types and Description


Scalar:
Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a
1
number, a string, or a reference. A reference is actually an address of a variable which we
will see in upcoming chapters.
Arrays:
2 Arrays are ordered lists of scalars that you access with a numeric index which starts with 0.
They are preceded by an "at" sign (@).
Hashes:
3 Hashes are unordered sets of key/value pairs that you access using the keys as subscripts.
They are preceded by a percent sign (%).

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:

Escape sequence Meaning


\\ Backslash
\' Single quote
\" Double quote
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\0nn Creates Octal formatted numbers
\xnn Creates Hexideciamal formatted numbers
\cX Control characters, x may be any character
\u Force next character to uppercase
\l Force next character to lowercase
\U Force all following characters to uppercase
\L Force all following characters to lowercase
\Q Backslash all following non-alphanumeric characters

119
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

\E End \U, \L, or \Q

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

# This is case of interpolation.


$str = "Welcome to \ntutorialspoint.com!";
print "$str\n";

# This is case of non-interpolation.


$str = 'Welcome to \ntutorialspoint.com!';
print "$str\n";

# Only W will become upper case.


$str = "\uwelcome to tutorialspoint.com!";
print "$str\n";

# Whole line will become capital.


$str = "\UWelcome to tutorialspoint.com!";
print "$str\n";

# A portion of line will become capital.


$str = "Welcome to \Ututorialspoint\E.com!";
print "$str\n";

# Backsalash non alpha-numeric including spaces.


$str = "\QWelcome to tutorialspoint's family";
print "$str\n";

This will produce following result:

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:

$age = 25; # An integer assignment


$name = "John Paul"; # A string
$salary = 1445.50; # A floating point

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.

Here is a simple example of using scalar variables:

#!/usr/bin/perl

$age = 25; # An integer assignment


$name = "John Paul"; # A string
$salary = 1445.50; # A floating point

print "Age = $age\n";


print "Name = $name\n";
print "Salary = $salary\n";

This will produce following result:

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.

Here is a simple example of using array variables:

#!/usr/bin/perl

@ages = (25, 30, 40);


@names = ("John Paul", "Lisa", "Kumar");

print "\$ages[0] = $ages[0]\n";


print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";

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.

Here is a simple example of using hash variables:

#!/usr/bin/perl

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

print "\$data{'John Paul'} = $data{'John Paul'}\n";


print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

This will produce following result:

$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

@names = ('John Paul', 'Lisa', 'Kumar');

@copy = @names;
$size = @names;

print "Given names are : @copy\n";


print "Number of names are : $size\n";

This will produce following result:

Given names are : John Paul Lisa Kumar


Number of names are : 3

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:

S.N. Context and Description


Scalar:
1
Assignment to a scalar variable evaluates the right-hand side in a scalar context.
List:
2
Assignment to an array or a hash evaluates the right-hand side in a list context.
Boolean:
3 Boolean context is simply any place where an expression is being evaluated to see whether
it's true or false
Void:
4 This context not only doesn't care what the return value is, it doesn't even want a return
value.
Interpolative:
5
This context only happens inside quotes, or things that work like quotes.

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.

Here is a simple example of using scalar variables:

#!/usr/bin/perl

123
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

$age = 25; # An integer assignment


$name = "John Paul"; # A string
$salary = 1445.50; # A floating point

print "Age = $age\n";


print "Name = $name\n";
print "Salary = $salary\n";

This will produce following result:

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;

# 377 octal, same as 255 decimal


$octal = 0377;

# FF hex, also 255 decimal


$hexa = 0xff;

print "integer = $integer\n";


print "negative = $negative\n";
print "floating = $floating\n";
print "bigfloat = $bigfloat\n";
print "octal = $octal\n";
print "hexa = $hexa\n";

This will produce following result:

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

$var = "This is string scalar!";


$quote = 'I m inside single quote - $var';
$double = "This is inside single quote - $var";

$escape = "This example of escape -\tHello, World!";

print "var = $var\n";


print "quote = $quote\n";
print "double = $double\n";
print "escape = $escape\n";

This will produce following result:

var = This is string scalar!


quote = I m inside single quote - $var
double = This is inside single quote - This is string scalar!
escape = This example of escape - Hello, World!

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 = "hello" . "world"; # Concatenates strings.


$num = 5 + 10; # adds two numbers.
$mul = 4 * 5; # multiplies two numbers.
$mix = $str . $num; # concatenates string and number.

print "str = $str\n";


print "num = $num\n";
print "mix = $mix\n";

This will produce following result:

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

This will produce following result:

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 will also produce the same result:

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;

print "smile = $smile\n";


print "foo = $foo\n";
print "martin = $martin\n";

This will also produce the same result:

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

print "File name ". __FILE__ . "\n";


print "Line Number " . __LINE__ ."\n";
print "Package " . __PACKAGE__ ."\n";

# they can not be interpolated


print "__FILE__ __LINE__ __PACKAGE__\n";

This will produce following result:

File name hello.pl


Line Number 4
Package main
__FILE__ __LINE__ __PACKAGE__

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.

Here is a simple example of using array variables:

#!/usr/bin/perl

@ages = (25, 30, 40);


@names = ("John Paul", "Lisa", "Kumar");

print "\$ages[0] = $ages[0]\n";


print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";

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:

@array = (1, 2, 'Hello');


@array = qw/This is an array/;

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';

Accessing Array Elements


When accessing individual elements from an array, you must prefix the variable with a dollar
sign ($) and then append the element index within square brackets after the name of the variable.
For example:

#!/usr/bin/perl

@days = qw/Mon Tue Wed Thu Fri Sat Sun/;

print "$days[0]\n";
print "$days[1]\n";
print "$days[2]\n";
print "$days[6]\n";
print "$days[-1]\n";
print "$days[-7]\n";

This will produce following result:

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

print $days[-1]; # outputs Sun


print $days[-7]; # outputs Mon

Sequential Number Arrays

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);

print "@var_10\n"; # Prints number from 1 to 10


print "@var_20\n"; # Prints number from 10 to 20
print "@var_abc\n"; # Prints number from a to 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;

print "Size: $size\n";


print "Max Index: $max_index\n";

This will produce following result:

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.

Adding and Removing Elements in Array

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.

S.N. Types and Description


push @ARRAY, LIST
1
Pushes the values of the list onto the end of the array.
pop @ARRAY
2
Pops off and returns the last value of the array.
shift @ARRAY
3 Shifts the first value of the array off and returns it, shortening the array by 1 and moving
everything down
unshift @ARRAY, LIST
4
Prepends list to the front of the array, and returns the number of elements in the new array.
#!/usr/bin/perl

# create a simple array


@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";

# add one element at the end of the array


push(@coins, "Penny");
print "2. \@coins = @coins\n";

# add one element at the beginning of the array


unshift(@coins, "Dollar");
print "3. \@coins = @coins\n";

# remove one element from the last of the array.


pop(@coins);
print "4. \@coins = @coins\n";

# remove one element from the beginning of the array.


shift(@coins);
print "5. \@coins = @coins\n";

This will produce following result:

1. @coins = Quarter Dime Nickel


2. @coins = Quarter Dime Nickel Penny
3. @coins = Dollar Quarter Dime Nickel Penny
4. @coins = Dollar Quarter Dime Nickel
5. @coins = Quarter Dime Nickel

130
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Slicing Array Elements


You can also extract a "slice" from an array - that is, you can select more than one item from an
array in order to produce another array.

#!/usr/bin/perl

@days = qw/Mon Tue Wed Thu Fri Sat Sun/;

@weekdays = @days[3,4,5];

print "@weekdays\n";

This will produce following result:

Thu Fri Sat

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

@days = qw/Mon Tue Wed Thu Fri Sat Sun/;

@weekdays = @days[3..5];

print "@weekdays\n";

This will produce following result:

Thu Fri Sat

Replacing Array Elements

Now we are going to introduce one more function called splice(), which has following syntax:

splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ]

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

This will produce following result:

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.

Transform Strings to Arrays


Let's look into one more function called split(), which has the following syntax:

split [ PATTERN [ , EXPR [ , LIMIT ] ] ]

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

# transform above strings into arrays.


@string = split('-', $var_string);
@names = split(',', $var_names);

print "$string[3]\n"; # This will print Roses


print "$names[4]\n"; # This will print Michael

This will produce following result:

Roses
Michael

Transform Arrays to Strings


We can use the join() function to rejoin the array elements and form one long scalar string. This
function has following syntax:

join EXPR, LIST

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

# transform above strings into arrays.


@string = split('-', $var_string);
@names = split(',', $var_names);

132
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

$string1 = join( '-', @string );


$string2 = join( ',', @names );

print "$string1\n";
print "$string2\n";

This will produce following result:

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:

sort [ SUBROUTINE ] LIST

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

# sort this array


@foods = sort(@foods);
print "After: @foods\n";

This will produce following result:

Before: pizza steak chicken burgers


After: burgers chicken pizza steak
Please note that sorting is performed based on ASCII Numeric value of the words. So the best
option is to first transform every element of the array into lowercase letters and then perform the
sort function.

The $[ Special Variable

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

# Let's reset first index of all the arrays.


$[ = 1;

print "Food at \@foods[1]: $foods[1]\n";


print "Food at \@foods[2]: $foods[2]\n";

This will produce following result:

Foods: pizza steak chicken burgers


Food at @foods[1]: pizza
Food at @foods[2]: steak

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));

print "numbers = @numbers\n";

This will produce following result:

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 = (@odd, @even);

print "numbers = @numbers\n";

This will produce following result:

numbers = 1 3 5 2 4 6

Selecting Elements from Lists


The list notation is identical to that for arrays - you can extract an element from an array by
appending square brackets to the list and giving one or more indices:

#!/usr/bin/perl

134
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

$var = (5,4,3,2,1)[4];

print "value of var = $var\n"

This will produce following result:

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];

print "Value of list = @list\n";

This will produce following result:

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.

Here is a simple example of using hash variables:

#!/usr/bin/perl

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

print "\$data{'John Paul'} = $data{'John Paul'}\n";


print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

This will produce following result:

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

$data{'John Paul'} = 45;


$data{'Lisa'} = 30;
$data{'Kumar'} = 40;

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:

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);


135
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

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}

Accessing Hash Elements


When accessing individual elements from a hash, you must prefix the variable with a dollar sign
($) and then append the element key within curly brackets after the name of the variable. For
example:

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

print "$data{'John Paul'}\n";


print "$data{'Lisa'}\n";
print "$data{'Kumar'}\n";

This will produce following result:

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 = @data{-JohnPaul, -Lisa};

print "Array : @array\n";

This will produce following result:

Array : 45 30
136
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Extracting Keys and Values


You can get a list of all of the keys from a hash by using keys function which has the following
syntax:

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);

@names = keys %data;

print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";

This will produce following result:

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);

@ages = values %data;

print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";

This will produce following result:

30
45
40

Checking for Existence


If you try to access a key/value pair from a hash that doesn't exist, you'll normally get the
undefined value, and if you have warnings switched on, then you'll get a warning generated at

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:

Lisa is 30 years old

Getting Hash Size


You can get the size - that is, the number of elements from a hash by using scalar context on
either keys or values. Simply saying first you have to get an array of either the keys or values and
then you can get size of array as follows:

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

@keys = keys %data;


$size = @keys;
print "1 - Hash size: is $size\n";

@values = values %data;


$size = @values;
print "2 - Hash size: is $size\n";

This will produce following result:

1 - Hash size: is 3
2 - Hash size: is 3

Add & Remove Elements in Hashes


Adding a new key/value pair can be done with one line of code using simple assignment
operator. But to remove an element from the hash you need to use delete function as shown
below in the example:

#!/usr/bin/perl

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

138
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

@keys = keys %data;


$size = @keys;
print "1 - Hash size: is $size\n";

# adding an element to the hash;


$data{'Ali'} = 55;
@keys = keys %data;
$size = @keys;
print "2 - Hash size: is $size\n";

# delete the same element from the hash;


delete $data{'Ali'};
@keys = keys %data;
$size = @keys;
print "3 - Hash size: is $size\n";

This will produce following result:

1 - Hash size: is 3
2 - Hash size: is 4
3 - Hash size: is 3

Perl Conditional Statements


Perl conditional statements helps in decision making which require the programmer specifies one
or more conditions to be evaluated or tested by the program, along with a statement or statements
to be executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.

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

An if statement consists of a boolean expression followed by one


if statement
or more statements.

if...else statement An if statement can be followed by an optional else statement.

An if statement can be followed by an optional elsif statement and


if...elsif...else statement
then by an optional else statement.

An unless statement consists of a boolean expression followed by


unless statement
one or more statements.

An unless statement can be followed by an optional else


unless...else statement
statement.

An unless statement can be followed by an optional elsif


unless...elsif..else statement
statement and then by an optional else statement.

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:

Exp1 ? Exp2 : Exp3;

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;

$status = ($age > 60 )? "A senior citizen" : "Not a senior citizen";


140
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

print "$name is - $status\n";

This will produce following result:

Ali is - Not a senior citizen

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.

Loop Type Description

Repeats a statement or group of statements while a given condition is


while loop
true. It tests the condition before executing the loop body.

Repeats a statement or group of statements until a given condition


until loop
becomes true. It tests the condition before executing the loop body.

141
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

Execute a sequence of statements multiple times and abbreviates the


for loop
code that manages the loop variable.

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:

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.

Control Statement Description

Causes the loop to skip the remainder of its body and immediately retest
next statement
its condition prior to reiterating.

Terminates the loop statement and transfers execution to the statement


last statement
immediately following the loop.

A continue BLOCK, it is always executed just before the conditional is


continue statement
about to be evaluated again.

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.

The Infinite Loop:

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

You can terminate above infinite loop by pressing Ctrl + C keys.

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

Lets have a look on all operators one by one.

Perl Arithmetic Operators:

Assume variable $a holds 10 and variable $b holds 20 then:

Operator Description Example

+ Addition - Adds values on either side of the operator $a + $b will give 30

Subtraction - Subtracts right hand operand from left


- $a - $b will give -10
hand operand

Multiplication - Multiplies values on either side of the


* $a * $b will give 200
operator

Division - Divides left hand operand by right hand


/ $b / $a will give 2
operand

Modulus - Divides left hand operand by right hand


% $b % $a will give 0
operand and returns remainder

Exponent - Performs exponential (power) calculation on


** $a**$b will give 10 to the power 20
operators

Perl Equality 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 ]

Operator Description Example

Checks if the value of two operands are equal or not, if


== ($a == $b) is not true.
yes then condition becomes true.

Checks if the value of two operands are equal or not, if


!= ($a != $b) is true.
values are not equal then condition becomes true.

Checks if the value of two operands are equal or not,


and returns -1, 0, or 1 depending on whether the left
<=> ($a <=> $b) returns -1.
argument is numerically less than, equal to, or greater
than the right argument.

Checks if the value of left operand is greater than the


> value of right operand, if yes then condition becomes ($a > $b) is not true.
true.

Checks if the value of left operand is less than the value


< ($a < $b) is true.
of right operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or


>= equal to the value of right operand, if yes then condition ($a >= $b) is not true.
becomes true.

Checks if the value of left operand is less than or equal


<= to the value of right operand, if yes then condition ($a <= $b) is true.
becomes true.

Below is a list of equity operators. Assume variable $a holds "abc" and variable $b holds "xyz"
then, lets check following string equality operators:

Operator Description Example

Returns true if the left argument is stringwise less than


lt ($a lt $b) is true.
the right argument.

Returns true if the left argument is stringwise greater


gt ($a gt $b) is false.
than the right argument.

Returns true if the left argument is stringwise less than


le ($a le $b) is true.
or equal to the right argument.

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

than or equal to the right argument.

Returns true if the left argument is stringwise equal to


eq ($a eq $b) is false.
the right argument.

Returns true if the left argument is stringwise not equal


ne ($a ne $b) is true.
to the right argument.

Returns -1, 0, or 1 depending on whether the left


cmp argument is stringwise less than, equal to, or greater ($a cmp $b) is -1.
than the right argument.

Perl Assignment Operators:

Assume variable $a holds 10 and variable $b holds 20 then:

Operator Description Example

Simple assignment operator, Assigns values from right $c = $a + $b will assigne value of $a
=
side operands to left side operand + $b into $c

Add AND assignment operator, It adds right operand to


+= $c += $a is equivalent to $c = $c + $a
the left operand and assign the result to left operand

Subtract AND assignment operator, It subtracts right


-= operand from the left operand and assign the result to $c -= $a is equivalent to $c = $c - $a
left operand

Multiply AND assignment operator, It multiplies right


*= operand with the left operand and assign the result to $c *= $a is equivalent to $c = $c * $a
left operand

Divide AND assignment operator, It divides left operand


/= with the right operand and assign the result to left $c /= $a is equivalent to $c = $c / $a
operand

Modulus AND assignment operator, It takes modulus


%= using two operands and assign the result to left $c %= $a is equivalent to $c = $c % a
operand

Exponent AND assignment operator, Performs


$c **= $a is equivalent to $c = $c **
**= exponential (power) calculation on operators and assign
$a
value to the left operand

Perl Bitwise Operators:

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

-----------------

$a&$b = 0000 1100

$a|$b = 0011 1101

$a^$b = 0011 0001

~$a = 1100 0011

There are following Bitwise operators supported by Perl language

Operator Description Example

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

(~$a ) will give -61 which is 1100


Binary Ones Complement Operator is unary and has the
~ 0011 in 2's complement form due to
efect of 'flipping' bits.
a signed binary number.

Binary Left Shift Operator. The left operands value is


$a << 2 will give 240 which is 1111
<< moved left by the number of bits specified by the right
0000
operand.

Binary Right Shift Operator. The left operands value is


$a >> 2 will give 15 which is 0000
>> moved right by the number of bits specified by the right
1111
operand.

Perl Logical Operators:

There are following logical operators supported by Perl language. Assume variable $a holds true
and variable $b holds false then:

Operator Description Example

Called Logical AND operator. If both the operands are


and ($a and $b) is false.
true then then condition becomes true.

146
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

C-style Logical AND operator copies a bit to the result if


&& ($a && $b) is false.
it exists in both operands.

Called Logical OR Operator. If any of the two operands


or ($a or $b) is true.
are non zero then then condition becomes true.

C-style Logical OR operator copies a bit if it exists in


|| ($a || $b) is true.
eather operand.

Called Logical NOT Operator. Use to reverses the logical


not state of its operand. If a condition is true then Logical not($a and $b) is true.
NOT operator will make false.

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.

Operator Description Example

q{ } Encloses a string with-in single quotes q{abcd} gives 'abcd'

qq{ } Encloses a string with-in double quotes qq{abcd} gives "abcd"

qx{ } Encloses a string with-in invert quotes qx{abcd} gives `abcd`

Miscellaneous Operators:

There are following miscellaneous operators supported by Perl language. Assume variable a
holds 10 and variable b holds 20 then:

Operator Description Example

If $a="abc", $b="def" then $a.$b will


. Binary operator dot (.) concatenates two strings.
give "abcdef"

The repetition operator x returns a string consisting of


x the left operand repeated the number of times ('-' x 3) will give ---.
specified by the right operand.

The range operator .. returns a list of values counting


.. (2..5) will give (2, 3, 4, 5)
(up by ones) from the left value to the right value

++ Auto Increment operator increases integer value by one $a++ will give 11

Auto Decrement operator decreases integer value by


-- $a-- will give 9
one

147
– LAMP TECHNOLOGY
Srinivas Institute of Management Studies BCA Vsem

The arrow operator is mostly used in dereferencing a $obj->$a is an example to access


->
method or variable from an object or a class name variable $a from object $obj.

Perl Operators Precedence

The following table lists all operators from highest precedence to lowest.

left terms and list operators (leftward)


left ->
nonassoc ++ --
right **
right ! ~ \ and unary + and -
left =~ !~
left * / % x
left + - .
left << >>
nonassoc named unary operators
nonassoc < > <= >= lt gt le ge
nonassoc == != <=> eq ne cmp ~~
left &
left | ^
left &&
left || //
nonassoc .. ...
right ?:
right = += -= *= etc.
left , =>
nonassoc list operators (rightward)
right not
left and
left or xor

148
– LAMP TECHNOLOGY

You might also like