You are on page 1of 103

How It Works

The Web is usually accessed through a browser.


• Netscape
• Mozilla
• Internet Explorer etc.,

Information Science and Engineering 2


The browser connects to
www.example.com using port 80,
the port that the server operating system opens for such HTTP requests.

Serving Data to Client :


1. Serving Up Static Data
2. Serving Up Dynamic Data
3. Serving Up Content with Embedded HTML
1. Serving Up Static Data

Information Science and Engineering 3


1. Serving Up Dynamic Data

Information Science and Engineering 4


1. Serving Up Content with Embedded HTML

Information Science and Engineering 5


Apache Web Server
Server served up via the
HyperText Transfer Protocol (HTTP) by an httpd daemon
The "d" at the end means daemon, programs that are always running in
the background.
The daemon is called apache instead of httpd
Apache Explained www.example.com/content/chapt
er1/

GET /content/chapter1/ HTTP/1.0

Information Science and Engineering 6


Starting, Stopping, and Restarting Apache http://localhost/

Information Science and Engineering 7


# ps ax | grep httpd
1922 ? S 0:00 /usr/sbin/httpd
1927 ? S 0:00 /usr/sbin/httpd
1928 ? S 0:00 /usr/sbin/httpd
1929 ? S 0:00 /usr/sbin/httpd
1930 ? S 0:00 /usr/sbin/httpd
1932 ? S 0:00 /usr/sbin/httpd

# /etc/init.d/httpd start

# /etc/init.d/httpd status

httpd (pid 1937 1935 1933 1932 1930 1929 1928 1927
1922) is running...

# /etc/init.d/httpd stop
# /etc/init.d/httpd start # /etc/init.d/httpd graceful

Information Science and Engineering 8


# chkconfig --list httpd
httpd 0:off 1:off 2:off 3:on 4:on 5:on 6:off
If you do not see output indicating that 3, 4, and 5 are on,
turn them on:
# chkconfig httpd on
# chkconfig --list httpd
httpd 0:off 1:off 2:off 3:on 4:on 5:on 6:off

Information Science and Engineering 9


Configuration
/etc/httpd/conf/httpd.conf

Modifying the Default Configuration


ServerAdmin root@webserver.example.com
to:
ServerAdmin webmaster@example.com
Apache logs every hit to the webserver

• The client (Web surfer) IP address


• The date
• The URI requested (all the stuff after www.example.com/)

• The referer

CustomLog /var/log/httpd/logs/access_log common


to:
CustomLog /var/log/httpd/logs/access_log combined
Other options include
CustomLog /var/log/httpd/logs/access_log agent
CustomLog /var/log/httpd/logs/access_log referer

Information Science and Engineering 10


Securing Apache
Set User and Group
User apache
Group apache

Remove Online Manuals


# mv /var/www/html/manual /usr/doc/apache-1.3.24/

Consider Allowing Access to Local Documentation


Alias /doc/ /usr/share/doc/
<Location /doc>
order deny,allow
deny from all
allow from localhost .localdomain
Options Indexes FollowSymLinks
</Location>
Don't Allow public_html Web Sites (Unless You Want
To)
UserDir public_html
UserDir disabled

Information Science and Engineering 11


.htaccess
AccessFileName .htaccess
<Files ~ "^\.ht">
Order allow,deny
Deny from all
</Files>

Remove server-status and server-info


#<Location /server-status> #<Location /server-info>
# SetHandler server-status # SetHandler server-info
# Order deny,allow # Order deny,allow
# Deny from all # Deny from all
# Allow from .your_domain.com # Allow from .your_domain.com
#</Location> #</Location>

Information Science and Engineering 12


Don't Be a Proxy Server Unless You Want to Be
#LoadModule proxy_module modules/libproxy.so
and:
#AddModule mod_proxy.c
and:
#<IfModule mod_proxy.c>
#ProxyRequests On
#
#<Directory proxy:*>
# Order deny,allow
# Deny from all
# Allow from .your_domain.com
#</Directory>
#
# Enable/disable the handling of HTTP/1.1 "Via:" headers.
# ("Full" adds the server version; "Block" removes
# all outgoing Via: headers)
# Set to one of: Off | On | Full | Block
#
#ProxyVia On
#
# To enable the cache as well, edit and uncomment
# the following lines:
# (no caching without CacheRoot)
#
#CacheRoot "/var/cache/httpd"
#CacheSize 5
#CacheGcInterval 4
#CacheMaxExpire 24
#CacheLastModifiedFactor 0.1
#CacheDefaultExpire 1
#NoCache a_domain.com another_domain.edu joes.garage_sale.com
#</IfModule>
Information Science and Engineering 13
Disable CGI Programs
# chmod -x /var/www/cgi-bin/*
remove them:
# rm -rf /var/www/cgi-bin/*

Creating Them Yourself


<html>
<head>
<title>
This is my first HTML program
</title>
</head>
<body>
hello, world
</body>
</html>

$ chmod a+r /var/www/html/index.html

Information Science and Engineering 14


MySQL
MySQL is an Open Source (GPL) Standard Query Language (SQL)
database that is fast, reliable, easy to use, and suitable for
applications of any size.
MySQL can easily be integrated into Perl programs by using the
Perl DBI (DataBase Independent interface) module.

DBI is an Application Program Interface (API) that allows Perl to


connect to and query a number of SQL databases

How to Login :
$ mysql -u root
ERROR 2002: Can't connect to local MySQL server through socket
´/var/lib/mysql/mysql.sock´(2)

Welcome to the MySQL monitor. Commands end with ; or \g. Your


MySQL connection id is 3 to server version: 3.23.36 Type ´help;´ or ´\h´
for help. Type ´\c´ to clear the buffer
mysql>
Information Science and Engineering 15
# chkconfig mysqld on
# /etc/init.d/mysqld start

$ mysql -u root

SHOW DATABASES and CREATE DATABASE Commands

mysql> SHOW DATABASES;


+------------+
| Database |
+------------+
| mysql |
| sit |
| test |
+-------------+
3 rows in set (0.00 sec)

Information Science and Engineering 16


mysql> CREATE DATABASE people;
Query OK, 1 row affected (0.00 sec)

mysql> SHOW DATABASES;


+------------+
| Database |
+------------+
| mysql |
| people |
| sit |
| test |
+-------------+
4 rows in set (0.00 sec)
ls -l /var/lib/mysql
total 3
drwx------ 2 mysql mysql 1024 Dec 12 15:28 mysql
srwxrwxrwx 1 mysql mysql 0 Dec 13 07:19 mysql.sock
drwx------ 2 mysql mysql 1024 Dec 13 07:24 people
drwx------ 2 mysql mysql 1024 Dec 12 15:28 test

Information Science and Engineering 17


The CREATE TABLE and SHOW TABLES Commands

mysql> CREATE TABLE age_information (


-> lastname CHAR(20),
-> firstname CHAR(20),
-> age INT
-> );

Query OK, 0 rows affected (0.00 sec)

# ls -l /var/lib/mysql/people
total 10
-rw-rw---- 1 mysql mysql 8618 Dec 13 07:24 age_information.frm
-rw-rw---- 1 mysql mysql 0 Dec 13 07:24 age_information.MYD
-rw-rw---- 1 mysql mysql 1024 Dec 13 07:24 age_information.MYI

Information Science and Engineering 18


mysql> SHOW TABLES;
+------------------------+
| Tables_in_people |
+------------------------+
| age_information |
+------------------------+

1 row in set (0.00 sec)

Information Science and Engineering 19


Data Types

TINYINT -128 to 127 (signed) or 0 to 255 (unsigned)

SMALLINT -32768 to 32767 (signed) or 0 to 65535 (unsigned)

MEDIUMINT -8388608 to 8388607 (signed) or 0 to 16777215 (unsigned)

INTEGER (same as INT) -2147483648 to 2147483647 (signed) or 0 to 4294967295


(unsigned)
BIGINT -9223372036854775808 to 9223372036854775807 (signed)
or 0 to 18446744073709551615 (unsigned)

Real Type :
FLOAT
DOUBLE
REAL (same as DOUBLE)
DECIMAL
NUMERIC (same as DECIMAL)
Information Science and Engineering 20
Character Data Type :
VARCHAR variable-length string up to 255 characters

TINYBLOB maximum length 255 characters


TINYTEXT
BLOB maximum length 65535 characters
TEXT
MEDIUMBLOB maximum length 16777215 characters
MEDIUMTEXT
LONGBLOB maximum length 4294967295 characters
LONGTEXT

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

Information Science and Engineering 21


The DESCRIBE Command

mysql> DESCRIBE age_information;


+------------+------------+-------+-----+---------+----------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------+-------+-----+---------+----------+
| lastname | char(20) | YES | | NULL | |
| firstname | char(20) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
+------------+------------+-------+-----+---------+----------+

3 rows in set (0.00 sec)

OR
SHOW COLUMNS FROM age_information;

Information Science and Engineering 22


The INSERT Command
mysql> INSERT INTO age_information
-> (lastname, firstname, age)
-> VALUES (´Shrinivasacharya´ , ´Purohit´ , 30);

Query OK, 1 row affected (0.00 sec)

The SELECT Command


mysql> SELECT * FROM age_information;
+------------------------+-------------+------+
| lastname | firstname | age |
+------------------------+-------------+------+
| Shrinivasacharya | Purohit | 30 |
+------------------------+-------------+------+

1 row in set (0.00 sec)

Information Science and Engineering 23


ORDER BY <column name >

SELECT <column names> FROM <table name> ORDER BY <column


name> ;

-DESC to show descending order

SELECT <column names> FROM <table name> WHERE <cond> ;

The UPDATE Command


UPDATE <table name> SET <column name> = <value> WHERE <cond>;

SET <column name> = <column name> OP <value>

The DELETE Command


DELETE FROM <table name> WHERE <cond> ;

Information Science and Engineering 24


Change Password
# mysqladmin password xyz

$ mysql -u root -p

mysql> USE mysql;

Grant Command
mysql> GRANT SELECT,INSERT,UPDATE,DELETE
-> ON people.*
-> TO apache@localhost
-> IDENTIFIED BY ´password´;

Query OK, 0 rows affected (0.00 sec)

Information Science and Engineering 25


• Perl is a stable, cross platform programming language.
• Perl is Open Source software
• Perl was created by Larry Wall.
• 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 both procedural and object-oriented programming.
• The Perl interpreter can be embedded into other systems.
• Perl is the most popular web programming language due to its text
manipulation capabilities and rapid development cycle.

Information Science and Engineering 26


A First Perl Program
Example 1:

#! /usr/bin/perl -w
# file name : hello.pl
print "hello, world!\n ";

$ chmod a+x hello.pl

$ ./hello.pl

Example 2:

#! /usr/bin/perl -w
# file name : simpleadd.pl
$a = 5;
$b = 6;
$c = $a + $b;
print "\$c is now: $c\n";

Information Science and Engineering 27


Declaring Variables with use strict
Example 3:

#! /usr/bin/perl -w
# file name : useVar.pl
$abc=100;
print “The value of abc : $ab\n ";

use strict;

my $abc
OR
my($a, $b, $c);

Information Science and Engineering 28


Variables
Integers:
• Decimal: 10 -2884 2_248_188 The underscore can be used to
chunk numbers for ease of reading, but don't use the usual
comma format, as in 2,248,188, because that means
something completely different.
• Octal: 037 04214
• Hexadecimal: 0x25 0xaB80

Strings :
• Single quotes : ´hello world´
• Double quotes : “hello World”

Floats:
• Standard: 7.1 .8 9.
• Scientific: 3.4E-34 -8.023e43
Array :
• @data = (´Joe´, 39, "Test data", 49.3);
• my @data = (´Joe´, 39, "Test data", 49.3);

Information Science and Engineering 29


Example 4:
#! /usr/bin/perl -w
#file name : array1.pl
use strict;
my @data = (´Joe´, 39, "Test data", 49.3);
print "Within double quotes: @data\n";
print "Outside any quotes: ", @data, "\n";
print ´Within single quotes: @data´, "\n";

Output :

Within double quotes: Joe 39 Test data 49.3


Outside any quotes: Joe39Test data49.3
Within single quotes: @data

Information Science and Engineering 30


Example 5:
#! /usr/bin/perl -w
# file name : array2.pl
use strict;
my @data = (´Joe´, 39, ´Test data´, 49.3);
print "element 0: $data[0]\n";
print "element 1: $data[1]\n";
print "element 2: $data[2]\n";
print "element 3: $data[3]\n";

Output :
element 0: Joe
element 1: 39
element 2: Test data
element 3: 49.3

$#array_name it prints last index of the array

Information Science and Engineering 31


Array Functions
• push() function adds elements to the right.
• pop() removes the rightmost element.
• unshift() function adds elements to the left.
• shift() removes the leftmost element.

Example 6:
#! /usr/bin/perl -w
# file name: pushpop.pl
use strict;
my @a = (2, 4, 6, 8);
print "before: @a\n";
push(@a, 10, 12); #unshift(@a,10,12);
print "after push: @a\n";
my $element = pop(@a); #my $element=shift(@a);
print "after pop: @a\n";
print "element popped: $element\n";
Output :
before: 2 4 6 8 before: 2 4 6 8
after push: 2 4 6 8 10 12 after push: 10 12 2 4 6 8
after pop: 2 4 6 8 10 after pop: 12 2 4 6 8
element popped: 12 element popped: 10
Information Science and Engineering 32
• short() function sorts lists.
• reverse() function reverses lists .
• unshift() function adds elements to the left.
• shift() removes the leftmost element.

Example 7:
#! /usr/bin/perl -w
# file name : sortreverse.pl
use strict;
my @a = (´hello´, ´world´, ´good´, ´riddance´);
print "before: @a\n";
my @b = sort(@a);
print "sorted: @b\n";
@b = reverse(@a);
print "reversed: @b\n";

Output :
before: hello world good riddance
sorted: good hello riddance world
reversed: riddance good world hello

Information Science and Engineering 33


Hash Variables %person = (
name => ´Purohit´,
age => 30,
phone => ´555-1212´,
address => ´SIT.´,
city => ´Tumkur´,
state => ´KA´,
zip => ´572103´ );
Example 8:
#! /usr/bin/perl -w
# file name : hash1.pl
use strict;
my %person = (name => ´Purohit´, age => 28, phone => ´9448176001´,
address => ´SIT.´, city => ´Tumkur´, state => ´KARNATAKA´,
zip => ´572103´ );
print "$person{name} lives in $person{state}\n";
print "$person{name} is $person{age} years old\n";

Output :
Purohit lives in KARNATAKA
Purohit is 30 years old
Information Science and Engineering 34
Hash Functions
my @k = keys(%person);
{ state zip address city phone age name }

Operators
Arithmetic Meaning
+ addition
- subtraction
* multiplication
/ division
% modulus
exponentiation
**

Information Science and Engineering 35


Example 9:
#! /usr/bin/perl -w
# file name : operators.pl
use strict;
my $i = 10;
my $j = 4;
print ´$i + $j = ´, $i + $j, "\n";
print ´$i * $j = ´, $i * $j, "\n";
print ´$i / $j = ´, $i / $j, "\n";
print ´$i % $j = ´, $i % $j, "\n";
print ´$i ** $j = ´, $i ** $j, "\n";

Output :

$i + $j = 14
$i * $j = 40
$i / $j = 2.5
$i % $j = 2
$i ** $j = 10000

Information Science and Engineering 36


. string concatenation
x string replication
Example 10:
#!/usr/bin/perl -w
# file name : string.pl
use strict;
my $a = ´hello´;
my $b = ´world´;
my $msg = $a . ´ ´. $b;
print "\$msg : $msg\n";
$a = ´hi´;
$b = $a x 2;
my $c = $a x 5;
print "\$b : $b\n";
print "\$c : $c\n";
Output :
$msg : hello world
$b : hihi
$c : hihihihihi

Information Science and Engineering 37


Numerical Comparison
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
<=> Compare
< less than

Example 11:
if ($i < 10)
{
print "\$i is less than 10\n";
}
if ($j >= 20)
{
print "\$j is greater than or equal to 20\n";
}
Information Science and Engineering 38
String Comparison
le less than or equal to
gt greater than

ge greater than or equal to

eq equivalent to

ne not equal to
cmp Compare
lt less than

if ($name gt ´Purohit´)
{ print "$name comes after Purohit alphabetically\n"; }

if ($language ne ´Perl´)
{ print “It is C or JAVA.\n"; }

Information Science and Engineering 39


Increment and Decrement
++ Auto Increment  $X++;
-- Auto Decrement  $X--;

Example 12:
#! /usr/bin/perl -w
# file name : increment.pl
use strict;
my $i = 10;
my $j = ++$i;
print "\$i = $i, \$j = $j\n";

$i = 10;
$j = $i++;
print "\$i = $i, \$j = $j\n";

Information Science and Engineering 40


Logical Operators
|| logical or
! logical not
and logical and
or logical or
not logical not
&& logical and

if ($i >= 0 && $i <= 100)


{ print "\$i is between 0 and 100\n"; }

if ($answer eq ´y´ or $answer eq ´Y´)


{ print "\$answer" equals ´y´ or ´Y´\n"; }

Information Science and Engineering 41


Conditional and Looping Constructs
if (condition)
{ statements }
else
{ statements }

if (condition1)
{ statements }
elsif (condition2)
{ statements }
else
{ statements }

while (condition)
{
statements
}

Information Science and Engineering 42


Examples :
$i = 1;
while ($i <= 5)
{ print "the value is: $i\n";
$i++;
}

#! /usr/bin/perl -w
# file: whilearray.pl
use strict;
my @names = (´Joe´, ´Charlie´, ´Sue´, ´Mary´);
my $i = 0;
while ($i <= $#names)
{
print "Element $i is $names[$i]\n";
$i++;
}

Information Science and Engineering 43


#! /usr/bin/perl -w
# file: whilehash.pl
use strict;
my %capitals = (
Illinois => ´Springfield´,
California => ´Sacramento´,
Texas => ´Austin´,
Wisconsin => ´Madison´,
Michigan => ´Lansing´
);
my @sk = sort(keys(%capitals)); my $i = 0;
while ($i <= $#sk)
{
print "$sk[$i]: \t$capitals{$sk[$i]}\n";
$i++;
}
Output :
California: Sacramento
Illinois: Springfield
Michigan: Lansing
Texas: Austin
Wisconsin: Madison Information Science and Engineering 44
for (init_expression; condition; step_expression)
{
statements
}
for ($i = 0; $i <= $#names; $i++)
{
print "Element $i is $names[$i]\n";
}

foreach scalar_variable (list)


{
statements
}
#! /usr/bin/perl -w
# file name : foreach1.pl
use strict; my @a = (2, 4, 6, 8);
foreach my $i (@a)
{
print $i, ´ ** ´, $i, ´ = ´, $i ** $i, "\n";
}
Information Science and Engineering 45
Output :
2 ** 2 = 4
4 ** 4 = 256
6 ** 6 = 46656
8 ** 8 = 16777216

Information Science and Engineering 46


Functions
sub <function_name >
{

# body
}

#! /usr/bin/perl -w
# file: function1.pl
sub say_hello
{
print "hello, world!\n";
}

say_hello();

Information Science and Engineering 47


Return Values

#!/usr/bin/perl -w
# file: return1.pl
sub test1
{
$a = 10; $b = 11;
$a + $b; # return ($a+$b);
}
sub test2
{ @a = (´testing´, ´one´, ´two´, ´three´);
sort(@a);
}

$c = test1();
print "\$c = $c\n";
@b = test2();
print "\@b = @b\n";

Information Science and Engineering 48


Function Arguments
#! /usr/bin/perl -w
# file: printargs1.pl
use strict;
sub print_args
{ my $i = 0;
while ($i <= $#_)
{
print "arg $i: $_[$i]\n";
$i++;
}
}

my $num = 10;
my $name = ´Purohit´;
print_args($num, $name, 3.14159, ´hello, world!´);

Information Science and Engineering 49


#! /usr/bin/perl -w
# printargs2.pl
use strict;
sub print_args_2
{
my($a, $b, $c) = @_;
print "\$a is: $a\n";
print "\$b is: $b\n";
print "\$c is: $c\n";
}

my $num = 10;
my $name = ´Purohit´;
print_args_2($num, $name, 3.14159);

Output :
$a is: 10
$b is: Purohit
$c is: 3.14159

Information Science and Engineering 50


File I/O
Reading from a File
open FH, ´< file name´;

if (! open (FH, ´<filename´))


{
die "Can't open filename: $!";
}

open(FH, ´< filename´) or die "Can't open filename";

#! /usr/bin/perl -w
# file: file1.pl
use strict;
my $line;
open (FH, ´<test.txt´) or die "Can't open test.txt: $!";
while ($line = <FH>)
{
print "Line is: $line"; #@all_lines = <FH>;
}
close (FH);
Information Science and Engineering 51
my $i = 0;
while ($i <= $#all_lines)
{
print "Line is: $all_lines[$i]";
$i++;
}

Writing to a File
#! /usr/bin/perl -w
# file3.pl
use strict;
my $line;
open (FH, ´ >output.txt´) or die "Can't open output.txt: $!";
while ($line = <STDIN>)
{
print FH "You entered: $line";
}
close (FH);

Information Science and Engineering 52


Operating System Calls
system ´/bin/ls´;

Information Science and Engineering 53


Information Science and Engineering 54
Apache Configuration /etc/httpd/conf/httpd.conf

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

<Directory "/var/www/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory> # /etc/init.d/httpd graceful
OR
Service httpd restart
CGI Programming :
#!/usr/bin/perl
# first.cgi
print "Content-type: text/plain\n";
print "\n";
print “This is my first CGI Programming…";

/var/www/cgi-bin/first.cgi
chmod a+rx first.cgi
Information Science and Engineering 55
#!/usr/bin/perl
# second.cgi
print "Content-type: text/plain\n";
print "\n";
print "<b>hello</b>, <i>world</i>!";

#!/usr/bin/perl
# second1.cgi
print "Content-type: text/html\n";
print "\n";
print "<b>hello</b>, <i>world</i>!";

Information Science and Engineering 56


#!/usr/bin/perl
# info.cgi
use strict;
my($host, $date);
chomp($host = `/bin/hostname`);
chomp($date = `/bin/date`);
print "Content-type: text/html\n\n";
print "<html>\n";
print "<head>\n";
print "<title>System Information</title>\n";
print "</head>\n";
print "<body bgcolor=\"#520063\" text=\"#ffffff\">\n";
print "<h1>Hello from $host!</h1>\n";
print "The current time is now: $date\n";
print "</body>\n";
print "</html>\n";

Information Science and Engineering 57


here document
#!/usr/bin/perl
# info2.cgi
use strict;
my($host, $date);
chomp($host = `/bin/hostname`);
chomp($date = `/bin/date`);
print <<EOHTML;
Content-type: text/html
<html>
<head>
<title>System Information</title>
</head> <body bgcolor="#520063" text="#ffffff">
<h1>Hello from $host!</h1>
The current time is now: $date
</body>
</html>
EOHTML

Information Science and Engineering 58


CGI.pm Introduced
use CGI;
OR
use CGI ´:standard´;
#!/usr/bin/perl
# simple.cgi
use CGI ´:standard´;
print header(),
start_html(-title => ´A Simple Page´, -bgcolor => ´#ffffff´, -text => ´#520063´),
h1(´Hello, world! again´),
hr(),
´Time to go now...´,
end_html();
$q = new CGI;
print $q->header(),
.
.
$q->hr(),
..

Information Science and Engineering 59


<HTML>
<HEAD><TITLE>A Simple Page</TITLE> </HEAD>
<BODY TEXT="#520063" BGCOLOR="#ffffff">

<H1>  h1()
<P>  p()
</BODY></HTML>  end_html()
<HR>  hr()
lists  li(), dl(), ul(), dd() etc.,
<BOLD> </BOLD>  b()

print start_html(-title => ´My Title´);


OR
print start_html(´My Title´);

Information Science and Engineering 60


Information Received by the CGI Program

• Client request information


• Path information
• Posted data

Request Information

Client Information :
• remote_host()— the name of the client machine
• user_name()— the name of the user if authenticated
• user_agent()— the browser that the user is surfing with
• referer()— the referer (remember, this is misspelled)
• path_info()— the path information
• query_string()— the query string

Information Science and Engineering 61


Server Information :
• server_name()— the hostname of the webserver
• server_software()— the name of the webserver software
• virtual_host()— the name of the virtual host
• server_port()— the port that the server is using (usually 80)
• script_name()— the name of the script

Information Science and Engineering 62


#! /usr/bin/perl
# info4.cgi
use CGI ´:standard´;
print header(),
start_html(´More System Information´),
h1(´Client Information´),
´Here is some information about the client:´,
ul( li(´The remote host: ´, remote_host()),
li(´The user agent: ´, user_agent()),
li(´The referer: ´, referer()) ),
h1(´Server Information´),
´Here is some information about the server:´,
ul( li(´The server name: ´, server_name()),
li(´The server software: ´, server_software()),
li(´The server port: ´, server_port()),
li(´The script name: ´, script_name()) ),
end_html();

Information Science and Engineering 63


Path Information
http://localhost/cgi-bin/messageboard.cgi/webprogramming/19312

$env_path = $ENV{PATH_INFO} || ´´;


OR
$method_path = path_info() || ´´;

#! /usr/bin/perl
# path_info.cgi
use strict;
use CGI ´:standard´;
my $env_path = $ENV{PATH_INFO} || ´ ´;
my $method_path = path_info() || ´ ´;
print header, start_html(-title => ´Path Information´, -bgcolor => ´#ffffff´),
´From %ENV: ´, b($env_path),
br(),
´From path_info(): ´, b($method_path),
end_html();
Information Science and Engineering 64
Processing Posted Form Data
• GET
• POST

<html>
<head> <title>Enter Your Name and Age</title> </head>
<body bgcolor="#ffffff">
<form action="/cgi-bin/nameage.cgi" method="get">
Name: <input type="text" name="yourname">
<br> Age: <input type="text" name="age"> <br>
<input type="submit" value="Click to Submit">
</form>
</body>
</html>

http://localhost/cgi-bin/nameage.cgi?yourname=Purohit&age=30

Information Science and Engineering 65


#!/usr/bin/perl
# nameage.cgi
use strict;
use CGI ´:standard´;
my $name = param(´yourname´) || ´Purohit´;
my $age = param(´age´) || 30;
my @params = param();
print header(), start_html(´Your Name and Age´),
"Hello $name, you are $age years old.",
hr(),
´The parameters entered are: ´, b("@params"),
end_html();

Information Science and Engineering 66


Form Widget Methods

• start_form() — start tag for the form


• textfield() — tag for a text widget
• textarea() — tag for a text area
• radio_group() — tags for a radio button group
• checkbox() — tag for a check box
• popup_menu() — tag for a pop-up menu
• scrolling_list() — tags for a scrolling list box
• submit() — tag for a submit button
• reset() — tag for a reset button
• end_form() — </FORM>

Information Science and Engineering 67


function invocation meaning
startform($method,$action,$encoding) starts a form
starts a form that may contain a file
start_multipart_form($method,$action)
input field
endform() ends a form
textfield(-name=>'field_name', -default=>initial value, -size=>number,
single-line text input field
-maxlength=>number)

textarea(-name=>'field_name', -default=>initial value, -rows=>number,


multi-line text input field
-cols=>number)

password_field(-name=>'field_name', -size=>number,
"password" input field
-maxlength=>number)

filefield(-name=>'field_name', -default=>initial filename) file input field

popup_menu(-name=>'menu_name', -values=>array or hash reference,


select element
-default=>initial selection)

scrolling_list(-name=>'menu_name', -values=>array or hash reference, select element with size larger than
-default=>initial selection(s), -size=>number, -multiple=>'true') 1

Information Science and Engineering 68


checkbox_group(-name=>'group_name', -values=>array or hash group of checkboxes with the
reference, -default=>initial selection(s), -linebreak=>'true') same name

checkbox(-name=>'checkbox_name', -checked=>'checked',
a standalone checkbox
-value=>internal value, -label=>visible label)

radio_group(-name=>'group_name', -values=>array or hash reference, group of radio buttons that work


-default=>initial selection(s), -linebreak=>'true') together

submit(-name=>'button_name', -value=>button text) submit button


reset( -value=>button text) reset button
defaults( -value=>button text) reset to original defaults

hidden(-name=>'field_name', -default=>array reference) hidden field

image_button(-name=>'button_name', -src=>image URL,


image submit button
-align=>alignment, -alt=>text, -value=>text)

button element, for client-side


button(-name=>'button_name', -value=>button text, -onClick=>script)
scripting

Information Science and Engineering 69


Database Functions:

$variable=DBI->connect() DBI->connect(´DBI:mysql:’<database name>’ ,


´<username>´, ´<password>´)
$variable1=$variable->prepare() $dbh->prepare(´<MySql query>´)
$variable1->execute()
DBI->errstr() It prints error message
$variable->errstr(),

Information Science and Engineering 70


#! /usr/bin/perl
# Program to display the current contents of the table in a database.
use DBI;
use CGI ':standard';
print header(),
start_html(-title=>"Database Information", -bgcolor=>'#000000', -text=>'#33ff00'),
h1({-align=>'center'}, 'DISPLAY TABLE CONTENTS');
print '-' x 80;
$dbh = DBI->connect('DBI:mysql:people','root',’')
or die "can't connect:" .DBI->errstr();
print b("<pre> USER </pre>");
print '-' x 80;
print b("<pre>NAME AGE</pre>");
print '-' x 80;
$sth = $dbh->prepare('select * from user')
or die "can't prepare:" .$dbh->errstr();
$sth->execute()
or die "can't execute:" .$sth->errstr();

while(($f1, $f2)=$sth->fetchrow())
{
print pre("$f1 $f2");
}
print '-' x 80;
print end_html();
Information Science and Engineering 71
#!/usr/bin/perl -w
use DBI;
use strict;
use CGI ':standard';
my $msg;
my $dbh = DBI->connect('DBI:mysql:people', ‘root', ‘')
or die "Can't connect: " . DBI->errstr();
my $fname = param('fname') || ' ';
my $lname = param('lname') || ' ';
my $age = param('age') || ' ';
if( $fname eq ' ' || $age eq ' ‘ )
{
$msg="Incomplete Entry ... Datababse could not be updated !";
}
else
{
my $sth = $dbh->prepare('INSERT INTO ageInfo (lname,fname,age)
VALUES(?,?,?)')
or die "Can't prepare SQL: " . $dbh->errstr();
$sth->execute($lname,$fname,$age)
or die "Can't execute SQL: " . $sth->errstr();
$msg="Data Successfully Inserted into People Database";
}
my $sth = $dbh->prepare('SELECT * FROM ageInfo') or die "Can't prepare SQL: " .
$dbh->errstr();
Information Science and Engineering 72
$sth->execute() or die "Can't execute SQL: " . $sth->errstr();
print header(),
start_html(-title => "Content of People database",-bgcolor => "#1E90FF" ),
h3($msg),
<<EOHTML;
<h2>Current Name/Age Information from People Database</h2>
<hr><br><br>
<table border="1"><tr>
<th>First Name</th><th>Last Name</th><th>Age</th></tr>
EOHTML
while(($lname,$fname,$age)=$sth->fetchrow())
{
print "<tr><td>$fname</td><td>$lname</td><td>$age</td></tr>\n";
}
$sth->finish();
$dbh->disconnect();

Information Science and Engineering 73


Mysql> CREATE DATABASE people;

Mysql> use people;

Mysql> create table ageInfo (fname char(30), lname char(30), age int );

Information Science and Engineering 74


• Hypertext Preprocessor
• The syntax is similar to Perl
• It has many built-in functions that perform important and common requests

1. <? ... … ?>


Example : <? echo “Hello World! ….."; ?>

2. <?php … … ?>
Example : <?php echo “Hello World!...."; ?>

3. <SCRIPT LANGUAGE="php"> … … </SCRIPT>


Example : <SCRIPT LANGUAGE="php"> echo "hello, world!"; </SCRIPT>

4. <% ... %>


Example : <% echo “ Hello World!..... %>

Information Science and Engineering 75


Program Examples :
$ mkdir /var/www/html/php
$ chmod a+rx /var/www/html/php
$ cd /var/www/html/php

<html>
<head>
<title>Hello, world! with PHP</title>
</head>
<body bgcolor="#ffffff">
<? echo "hello, world!" ?> #<? phpinfo() ?>
</body>
</html>

Information Science and Engineering 76


Information Science and Engineering 77
<?
$title = "PHP is cool";
echo "<title> $title </title>";
?>

<? // comment line or /* …… */


if ($num > 10)
echo "\$num is greater than 10";

if ($name == “Purohit")
{
echo "You say your name is Purohit";
echo "Are you sure that is your name?";
}
?>

Information Science and Engineering 78


<? // assign some variables the different data types
$integer = 12;
$float1 = 1.345e23;
$float2 = 4995.392;
$string1 = ´My favorite number is $integer´;
$string2 = "I am this big: $float1 or $float2"; ?>
<html> <head> <title>Integers, Floats and Strings in PHP</title>
</head>
<body bgcolor="#ffffff">
Integer: <b><? echo $integer; ?></b><br>
Float 1: <b><? echo $float1; ?></b> <br>
Float 2: <b><? echo $float2; ?></b> <br>
String 1: <b><? echo $string1; ?></b><br>
String 2: <b><? echo $string2; ?></b>
</body>
</html>

Information Science and Engineering 79


Arrays
• Enumerated Arrays
• Associative Arrays

<?
$a = array(2, 4, 6, 8);
echo $a[0]; // echoes 2
$b = array(“CSE", “ISE", “MCA");
echo $b[1]; // echos ISE
?>

<?
$capital["Illinois"] = "Springfield";
$capital["California"] = "Sacramento";
$capital["Texas"] = "Austin";
$capital["Wisconsin"] = "Madison";
$state = "Illinois";
echo "$state: $capital[$state]"; // echoes "Illinois: Springfield"
?>

Information Science and Engineering 80


OR
<?
$capital = array( "Illinois" => "Springfield",
"California" => "Sacramento",
"Texas" => "Austin",
"Wisconsin" => "Madison" );
$state = "Illinois";
echo "$state: $capital[$state]"; // echoes "Illinois: Springfield"
?>

Web Variables
<Directory /var/www/html/php>
php_flag register_globals Off
</Directory>

Pre–PHP Version 4.1.0


$HTTP_GET_VARS $HTTP_GET_VARS[“name“]
$HTTP_POST_VARS $HTTP_POST_VARS[“name“]
Information Science and Engineering 81
<html>
<head> <title>PHP Form 1 Result</title> </head>
<body bgcolor="#ffffff">
Using $var1: <b> <? echo $var1; ?> </b> <br>
Using $var2: <b> <? echo $var2; ?> </b> <br>
Using $HTTP_GET_VARS:
<b><? echo $HTTP_GET_VARS["var1"]; ?> </b>,
<b> <? echo $HTTP_GET_VARS["var2"]; ?> </b>
</body>
</html>

Post–Version 4.1.0
•$_GET — an array of the data sent with GET (replaces $HTTP_GET_VARS)
•$_POST — an array of the data sent with POST (replaces $HTTP_POST_VARS)
•$_COOKIE — HTTP cookie variables
•$_REQUEST — a merge of the GET, POST, and cookie data
Version 4.1.0 introduces some other helpful variables:
•$_SERVER — the Apache server environment variables, such as REMOTE_ADDR
•$_ENV — the environment variables
•$_SESSION — data registered by the session module

Information Science and Engineering 82


if (condition) switch (expression)
{ statements { case expr: statements break;
}elseif (condition) case expr: statements break;
{ statements } ……
else{ statements } default: statements break;
}

while (condition){ statements } while (condition):


statements
endwhile;

do { statements }while (condition);


<? // Example :
$array = array(2, 4, 6, 8);
for (start_expr; condition; step_expr) foreach ($array as $value)
{ statements } { echo "$value "; }
// echoes "2468"
foreach (array_expr as variable)
?>
{ statements }

Information Science and Engineering 83


<?
$a = array(2, 4, 6, 8);
foreach ($a as $k => $v)
{ echo "$k = $v "; } // echoes: 0 = 2 1 = 4 2 = 6 3 = 8
?>

<h3>Display ages in a table using the foreach loop</h3>


<table border="1">

<?
foreach ($a as $k => $v)
{
echo "<tr><th>$k</th><td>$v</td></tr>";
}
?>

</table>

Information Science and Engineering 84


PHP Functions
The syntax to declare a function is:
function function_name(variable_list)
{
statements
}
The syntax to call a function is:
function_name(variable_list);

Example :
<?
function print_hello ()
{ echo "hello, world!"; }
?>

<html>
<head> <title>PHP Functions - Part 1</title> </head>
<body bgcolor="#ffffff">
<? print_hello(); ?>
</body>
</html> Information Science and Engineering 85
function no_default_args($a, $b, $c)
{ echo "<hr>";
echo "no_default_args(): \$a : $a <br>";
echo "no_default_args(): \$b : $b <br>";
echo "no_default_args(): \$c : $c <br>";
}
Calling :
no_default_args("foo", $variable_name, 4.9485);

function default_args($a = 2, $b = 4, $c = 6)
{
echo "<hr>"; echo "default_args(): \$a : $a <br>";
echo "default_args(): \$b : $b <br>";
echo "default_args(): \$c : $c <br>";
}

Calling :
default_args(10);

Information Science and Engineering 86


Built-In PHP Functions
print()
print "<h1>PHP Results</h1>";
print "$name : $age : $result[0]";
print "<hr>";
die()
if ($name == “ “ )
{ die("the name field was not entered in the form"); }

Array Functions

array_push() array_unshift()
array_pop() array_shift()
sort() rsort()
array_reverse()
asort(), arsort(), ksort(), and krsort()
count() -- array size

array_keys()  gives key names


array_values()  gives values

Information Science and Engineering 87


printf()
printf "Integer: %d, Float: %6.2f", $i, $f;
join()
$array = array(2, 4, 6, 8);
$string = join(":", $array); // $string is now "2:4:6:8"
substr()
$string = "hello, world!";
$substring = substr($string, 2, 6); // $substring is "llo, w“
trim()
$string = " hello, world!\n\n\n";
$string2 = trim($string); // $string2 is "hello, world!"

Information Science and Engineering 88


MySQL Functions
mysql_connect() —Connect to the MySQL Server
<? $mysql = mysql_connect( “localhost“, “username", “password “ )
or die("could not connect to mysql"); ?>
mysql_close() —Close a MySQL Server Connection
<? mysql_close($mysql); ?>
mysql_db_query() —Execute a Query
<? $result = mysql_db_query($db, $query) ?>
mysql_num_rows() —Return the Number of Rows Selected
<? echo mysql_num_rows($result); ?>
mysql_fetch_row() —Fetch a Row as an Enumerated Array
<? $array = mysql_fetch_row($result);
echo "First column: $array[0]";
echo "Second column: $array[1]";
?>
mysql_errno() and mysql_error() —Return MySQL Errors
<?
$result = mysql_db_query($db, $query)
or die("query failed-".mysql_errno() . ": " .mysql_error());
?>

Information Science and Engineering 89


<? $mysql = mysql_connect("localhost", “root", “ “ )
or die("could not connect to mysql");
// execute the MySQL query, grab the result in $result
$result = mysql_db_query("books", "SELECT * FROM ageInfo")
or die("query failed - " . mysql_errno() . ": " . mysql_error());
?>
<html>
<head> <title>PHP and MySQL</title> </head>
<body bgcolor="#ffffff">
We executed: <b>SELECT * FROM ageInfo</b>
<hr> We found <b>
<? echo mysql_num_rows($result); ?>
</b> rows.
<h3>Query result</h3>
<? //loop through each row
while ($array = mysql_fetch_row($result))
{
foreach ($array as $f)
{ print "$f :: "; }
print "<hr>";
}
?>
</body> </html>
<? mysql_close($mysql); Information
?> Science and Engineering 90
Develop and execute the following programs using HTML and PHP. Create Database
using MYSQL wherever necessary.
7. Program to query the database and to display the result on a web page.
8. Program to accept book information viz. Accession number, title, authors, edition and
publication from a web page and to store those in a database.
9.Program to search a book for a title given by the user on a web page and display the
search results with proper headings

Mysql> create table bookInfo (access_no char(10), title char(50),


author char (30), edition char(20), publication (20));

INSERT INTO book_info VALUES (1133,'Complete Reference


C','Schildt',2004,'TMH');

Information Science and Engineering 91


mysql_select_db( “database name“ ) -- Select a database

mysql_query() -- Execute a Query

mysql_free_result($result) -- Close the record set

mysql_close($mysql); -- Close the connection

Information Science and Engineering 92


Information Science and Engineering 93
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!...meta http-equiv="content-type" content="text/html;
charset=UTF-8">
<title> The stack ordering...</title>
<style type="text/css">
.layer1Style
{
border: solid thick black;
padding: 1em; width: 300px;
background-color: green;
position: absolute;
top: 100px; left: 200px; z-index: 0;
}
.layer2Style
{
border: solid thick black;
padding: 1em; width: 300px;
background-color: blue;
position: absolute;
top: 120px; left: 220px; z-index: 0;
Information
} Science and Engineering 94
.layer3Style
{
border: solid thick black;
padding: 1em; width: 300px;
background-color: red;
position: absolute;
top: 140px; left: 240px; z-index: 0;
}
</style>
<script type="text/javascript">
var topLayer="layer3";
function mover(toTop)
{
var oldTop=document.getElementById(topLayer).style;
var newTop=document.getElementById(toTop).style;
oldTop.zIndex="0";
newTop.zIndex="1";
topLayer=document.getElementById(toTop).id;
}
</script>

Information Science and Engineering 95


</head>
<body style=background-color:yellow">
<h2 style="text-align:center;color:red">
Program includes XHTML document to show the Stacking of Paragraphs
</h2>
<div style="z-indes: 0;" class="layer1Style" id="layer1"
onmouseover="mover('layer1')">
The lives of most inhabitants of Industrialized Countries....
</div>
<div style="z-indes: 0;" class="layer2Style" id="layer2"
onmouseover="mover('layer2')">
The www may seem like magic, until you understand how it works....
</div>
<div style="z-indes: 0;" class="layer3Style" id="layer3"
onmouseover="mover('layer3')">
Windows XP provides many ways you to communicate with friends...
</div>
</body>
</html>

Information Science and Engineering 96


Information Science and Engineering 97
Information Science and Engineering 98
Information Science and Engineering 99
Information Science and Engineering 100
Information Science and Engineering 101
Information Science and Engineering 102
Information Science and Engineering 103

You might also like