Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
C G I P
CGI PROGRAMMING LABORATOARY
[ MySQL, Perl, PHP and JAVA Servlet ]
[ This document covers the common Gateway Interface Programming Laboratory programs included for the 7th semester of Information and Computer Science and Engineering course. ]
Purohit Shrinivasacharya
Assistant Professor, Dept. of Information Science and Engineering, Siddaganga Institute of Technology, Tumkur - 03
Develop and execute the following programs using HTML and PERL. Create Database using MYSQL wherever necessary. 1. a) Program to display various Server Information like Server Name, Server Software, Server protocol, CGI Revision etc. b) Program to accept UNIX command from a HTML form and to display the output of the command executed. a) Program to accept the User Name and display a greeting message. b) Program to keep track of the number of visitors visited the web page and displays the counter with proper headings. Program to display a greeting based on the access time of the Web server. Also to verify whether the webmaster is currently logged in. Program to display a digital clock which displays the current time of the server. Program to display the current contents of the table in a database. Program to insert new name and age information entered by the user into the database.
2. 3. 4. 5. 6.
Develop and execute the following programs using HTML and PHP. Create Database using MYSQL wherever necessary. 7. 8. 9. Program to query the database and to display the result on a web page. Program to accept book information viz. Accession number, title, authors, edition and publication from a web page and to store those in a database. Program to search a book for a title given by the user on a web page and display the search results with proper headings.
Develop and execute the following programs using HTML and JAVA Servlets. 10. 11. 12. 13. 14. 15. a) Program to accept user name and display a greeting message. b) Program to change the background color of the page based on the color selected by the user. Program to display a greeting based on the access time of the server. Program to create and display a cookie. Program to create a session and display session information viz. session ID, creation time and last accessed. Program to request server information viz. Request Method, URI, Protocol and Remote address. Program to accept User name and address and display them in a web page by passing parameters.
Note: One exercise must be asked in the examination. The assignment of the exercise must be based on lots.
Purohit Shrinivasacharya
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/ <Directory "/var/www/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory>
{ or restart }
Steps to Execute the CGI PERL Programs : 1. Open vi and type perl program and save as <filename>.pl 2. Save the above file in the folder (i.e /var/www/cgi-bin) 3. Execute the following command #chmode filename 777 4. Open web browser and type the following URL http://localhost/cgi-bin/1a.pl 5. Check the output
I. PERL PROGRAMS
1A. Program to display various server information like server name, server software, server protocol, CGI revision etc.
#! /usr/bin/perl use CGI ':standard'; print header(), start_html(-title=>'Server Information',-bgcolor=>'#000000',text=>'#33ff00'), h1({-align=>'center'},'SERVER INFORMATION'), hr(), 'HERE IS SOME INFORMATION ABOUT THE SERVER:', ul( li('SERVER_NAME:',$ENV{'SERVER_NAME'}), li('SERVER_PORT:',$ENV{'SERVER_PORT'}), li('SERVER_PROTOCOL:',$ENV{'SERVER_PROTOCOL'}), li('SERVER_SOFTWARE:',$ENV{'SERVER_SOFTWARE'}), li('CGI_REVISION:',$ENV{'GATEWAY_INTERFACE'}), ), hr(), end_html();
Purohit Shrinivasacharya
1B. Program to accept UNIX command from a html form and to display the output of the command executed. #! /usr/bin/perl
print header(), start_html(-title=>'Unix Command Executor',-bgcolor=>'#000000', -text=>'#33ff00'), h1({align=>"center"},'UNIX COMMAND EXECUTOR'), hr(), 'Please enter the unix command here...', br(), br(), start_form(-method=>'post',-action=>'/cgi-bin/lab_programs/1b.pl'), b('UNIX COMMAND:'), textfield(-name=>'comd',-value=>''), submit(-name=>'submit',-value=>'Execute'), hr(), end_form(), '$', $command=param('comd'), pre(`$command`), hr(), end_html(); use CGI ':standard';
2a. Program to accept the user name and display a greeting message.
#! /usr/bin/perl use CGI ':standard'; print header(), start_html(-title=>'Greeting a user',-bgcolor=>'#000000', -text=>'#33ff00'), h1({align=>"center"},'GREETING A USER'), hr(), 'Enter Username ..', br(), br(), start_form(-method=>'post',-action=>'/cgi-bin/lab_programs/2a.pl'), b('USER NAME:'), textfield(-name=>'uname',-value=>''), submit(-name=>'submit',-value=>'Send'), hr(), end_form(), 'Welcome to ', $username=param('uname'), end_html();
Purohit Shrinivasacharya
2B. Program to keep track of the number of visitors, visited the web page and display the counter with proper headings.
Before executing the program perform the following. 1. Login to mysql using following command 2. #mysql u root 3. /* if people database already present use it or create it using CREATE DATABASE people; mysql> USE people; 4. Create table and insert 0 into table in people database. mysql> CREATE DATABASE people; mysql> USE people; mysql> CREATE TABLE counter ( count int); mysql> INSERT INTO counter VALUES (0); mysql> QUIT;
use DBI; use CGI ':standard'; print header(), start_html(-title=>"Page visited", -bgcolor=>'#000000', -text=>'#33ff00'), h1({-align=>'center'}, 'SERVER VISITED INFORMATION'); $dbh = DBI->connect('DBI:mysql:people','root','') or die "can't connect:" .DBI->errstr(); $sth = $dbh->prepare('select * from counter') or die "can't prepare:" .$dbh->errstr(); $sth->execute() or die "can't execute:" .$sth->errstr(); ($count)=Ssth->fetchrow(); $count=$count+1; Smsg=update counter set count=$count where 1; $sth = $dbh->prepare(msg) or die "can't prepare:" .$dbh->errstr(); $sth->execute() or die "can't execute:" .$sth->errstr(); print hr(), $count times this page is visited, end_html();
Purohit Shrinivasacharya
3. Program to display a greeting based on the access time of the web server. Also to verify whether the webmaster is currently loggedin.
January
4. Program to display a digital clock which displays the current time of the server.
#! /usr/bin/perl use CGI ':standard'; ($sec,$min,$hr)=localtime(); print header(); print start_html(-title=>'Time system',-bgcolor=>'#000000', -text=>'#33ff00'); print h1({-align=>'center'},'DIGITAL CLOCK'); print hr(); print "<meta http-equiv='refresh' content='1'>"; if ($hr>=12) { $hr=$hr-12; $time="$hr:$min:$sec pm" } else { $time="$hr:$min:$sec am" } print h1({-align=>'center'},("$time")); print hr(); print end_html();
Purohit Shrinivasacharya
$dbh = DBI->connect('DBI:mysql:people','root','') or die "can't connect:" .DBI->errstr(); $sth = $dbh->prepare('select * from user') or die "can't prepare:" .$dbh->errstr(); $sth->execute() or die "can't execute:" .$sth->errstr(); print <table align=center border=1 > <tr><th>Name</th><th>Age</th></tr> while(($f1, $f2)=$sth->fetchrow()) { print ("<tr><td>$f1</td><td>$f2</td></tr>"); } print </table>; print end_html();
6. Program to insert new name and age information entered by the user into the database.
#! /usr/bin/perl #file name : 6.pl use DBI; use CGI ':standard'; #Create a form to read name and age of the person to insert into table. print header(), start_html(-title=>'DATABASE ENTRY',-bgcolor=>'#000000', -text=>'#33ff00'), h1({-align=>'center'},'DATABASE ENTRY'), hr(),br(), start_form(-method=>'post',-action=>'/cgi-bin/6ll.pl'), 'USER NAME:',textfield(-name=>'uname',-value=>' '), ' AGE:', textfield(-name=>'age',-value=>' '), br(), submit(-name=>'submit',-value=>'Insert'), reset(),hr(), end_form(); # insert data into user table
Purohit Shrinivasacharya
After executing the program login to mysql and execute the following commands to verify the inserted values. 1. #mysql u root 2. mysql> USE people; 3. mysql> SELECT * FROM user;
Purohit Shrinivasacharya
7. Prepare to query the database and to display the result on a web page
<html> <head> <title> Database Access using PHP </title> </head> <body bgcolor="#000000", text="#33ff00"> <h1 align="center">DATABASE ACCESS</h1> <hr></hr> <table align=center border=1 width=20%> <tr><th>NAME</th><th>AGE</th></tr> <? $mysql=mysql_connect("localhost","root","") or die ("can't connect to mysql"); $result=mysql_db_query("people","select * from user") or die ("query failed - ".mysql_errno().": ".mysql_error()); while($array=mysql_fetch_row($result)) { echo"<tr><td>$array[0]</td><td>$array[1]</td></tr>"; } echo "</table> <hr>"; echo "<b> QUERY EXECUTED:</b> $query"; echo "<br>"; echo "<b> Number of rows selected:</b>".mysql_num_rows($result); mysql_close($mysql);
Purohit Shrinivasacharya
1 0
8. Program to accept book information viz., Accession number, Title, Author, Edition, Publication from a webpage and to store those in a database. Before executing the program perform the following. 1. Login to mysql using following command
2. #mysql u root 3. /* if people database already present use it or create it using CREATE DATABASE people; mysql> USE people; 4. Create table and insert values into table in people database. mysql> CREATE TABLE BOOK (accn char(15), title char(30), author char(30), edition char(10),pubn char(30)); mysql> QUIT 5. Save file name as 8.php </html> <body bgcolor="#1E90FF"> <form action="/php/8l.php" method="post"> <h2>Complete the form with proper entry for Book Information </h2> <hr> <table border="0"> <tr><td>Accession No : </td> <td><input type="text" name="acc_no" width="15"></td> </tr> <tr><td>Title : </td> <td><input type="text" name="title" width="30"></td> </tr> <tr><td>Author : </td> <td><input type="text" name="author" width="30"></td> </tr> <tr><td>Edition : </td> <td><input type="text" name="edition" width="10"></td> </tr> <tr><td>Publication : </td> <td><input type="text" name="pub" width="30"></td> </tr> </table> <hr> <pre> <input type="submit" value="Click to Submit"> </pre> </form> <? $accnn = $_POST["acc_no"]; $titlee = $_POST["title"]; $authorr = $_REQUEST["author"]; $editionn = $_REQUEST["edition"]; $pubnn = $_REQUEST["pub"]; if($accnn == "" or $titlee == "" or $authorr == "" or $editionn == "" or $pubnn == "") { echo "Donot enter the null values $accnn $titlee"; } else
Purohit Shrinivasacharya
1 1
mysql_db_query("people","insert into BOOK(accn,title,author,edition,pubn) values ('$accnn','$titlee','$authorr','$editionn','$pubnn')") or die ("query failed - ".mysql_errno().": ".mysql_error()); mysql_close($mysql);
9. Program to search a book for a title given by a user on a web page and display the search result with proper heading. Before executing the program perform the following. 1. Login to mysql using following command
2. #mysql u root 3. /* if people database already present use it or create it using CREATE DATABASE people; mysql> USE people; 4. Create table and insert values into table in people database. mysql> CREATE TABLE BOOK (accn char(15), title char(30), author char(30), edition char(10),pubn char(30)); mysql> INSERT INTO BOOK VALUES (1,CGI LAB,PS,1,SIT); mysql> INSERT INTO BOOK VALUES (2,DS,BS,1,SIT); mysql> INSERT INTO BOOK VALUES (3,CGI LAB,VMS,1,SIT); mysql> INSERT INTO BOOK VALUES (4,LD LAB,MSR,4,SIT); mysql> QUIT; 5. Save file name as 9.php
<html> <head> <title> Php Database search </title> </head> <body bgcolor='#ffffff', text='#000000'> <h1 align="center"> DATABASE SEARCH </h1> <hr> <form action="/php/9.php" method="post"> <b>Enter Book Title : </b><input type=text name=title> <input type=submit value=Search> <input type=reset><hr> </form>
<? $title=$_POST["title"]; if($title==NULL) { echo "<b> Donot Enter NULL Values </b>"; } else {
Purohit Shrinivasacharya
1 2
Purohit Shrinivasacharya
1 3
10a. Program to accept username and display a greeting message. 1. Save following html code as 10a.html in folder /var/www/html
<html> <head>
Purohit Shrinivasacharya
1 4
2.
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class 10a extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name; response.setContentType("text/html"); name=request.getParameter("name"); PrintWriter out=response.getWriter(); out.println("<html><body bgcolor='#ffffff', text='#000000' >"); out.println("<h1 align=center> Hello.......! "+name+"</h1>"); out.close(); } }
Purohit Shrinivasacharya
1 5
Execution : 1. Open the browser and type the following URL http://localhost/10a.html
10b. Program to change the background color of the page based on the color selected by the user. 1. Save following html code as 10b.html in folder /var/www/html
<html> <body bgcolor=white> <form action="http://localhost:8080/test/servlet/10b" method="get"> <center><hr><br> <h3>Choose the color</h3> <select name="color" size=1> <option value=#DC143C>Red <option value=#1E90FF>Blue <option value=#FFD700>Yellow <option value=#00FF00>Green <option value=#00FFFF>Aqua <option value=#FF1493>Pink </select> <input type=submit value="Submit"> </br><br><hr> </center></hr> </form> </body> </html>
2.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class 10b extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); String color = req.getParameter("color");
Purohit Shrinivasacharya
1 6
} }
Execution :
Purohit Shrinivasacharya
1 7
11. Program to display a greeting based on the access time of the server. 1. Save following java code as 11.java in folder and compile
1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 11.java 3. execute this command after saving web.xml file #service tomcat5 restart import import import import javax.servlet.*; java.io.*; javax.servlet.http.*; java.util.*;
public class 11 extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String s; Calendar calendar=Calendar.getInstance(); int hour=calendar.get(Calendar.HOUR_OF_DAY); if(hour<12) s = "Good Morning...Have a nice Day"; else if(hour<16) s="Good Afternoon..."; else if(hour<20) s="Good Evening..."; else s="Good Night..."; res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Greeting Message</TITLE></HEAD>"); out.println("<BODY bgcolor=1E90FF>"); out.println("<hr><br><h3>" + s ); out.println("<br><br><hr>"); out.println("</BODY>"); out.println("</HTML>"); out.close(); } }
Purohit Shrinivasacharya
1 8
Execution :
1. Open web browser type the following URL http://localhost:8080/test/servlet/11
12.
import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class Prg12 extends HttpServlet {
Purohit Shrinivasacharya
1 9
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String name = request.getParameter("name"); String data =request.getParameter("data"); Cookie cookie = new Cookie(name,data); response.addCookie(cookie); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body bgcolor='#000000', text='#33ff00'>"); out.println("<center>"); out.println("<h2>Your Cookie has been set to :</h2>"+data); // to display created cookies Cookie[] cookies=request.getCookies(); out.println("<br><br><hr><b>"); for(int i=0;i<cookies.length;i++) { String cname=cookies[i].getName(); String value=cookies[i].getValue(); out.println("<h1>Created Cookie information</h1><br>"); out.println("<br><b>NAME = </b>"+cname); out.println("<br>"); out.println("<b>VALUE = </b>"+value); } out.println("</body></html>"); out.close();
} }
Execution :
1. Open web browser type the following URL http://localhost/12.html
Purohit Shrinivasacharya
2 0
13. Program to create a session and display session information viz. session ID, creation time and last accessed. 1. Save following java code as 13.java in folder and compile
1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 13.java 3. execute this command after saving web.xml file #service tomcat5 restart
public class 13 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession mySession=request.getSession(true); response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Session Information</title>"); out.println("</head>"); out.println("<body bgcolor='#000000', text='#33ff00'>"); out.println("<h1 align=center>SESSION INFORMATION</h1>"); out.println("<hr><br><center>"); out.println("<table border=5>"); out.println("<tr><td><b>New Session </b></td>"); out.println("<td>"); out.println(mySession.isNew()); out.println("</td></tr>"); out.println("<tr><td><b>Session ID </b></td>"); out.println("<td>"); out.println(mySession.getId()); out.println("</td></tr>"); out.println("<tr><td><b>Session Creation Time </b></td>"); out.println("<td>"); out.println(new Date(mySession.getCreationTime())); out.println("</td></tr>"); out.println("<tr><td><b>Session Last Accessed Time </b></td>"); out.println("<td>"); out.println(new Date(mySession.getLastAccessedTime())); out.println("</td></tr></table>");
Purohit Shrinivasacharya
2 1
14. Program to request server information viz. Request method, URI, Protocol and Remote address. 1. Save following java code as 14.java in folder and compile
1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 14.java 3. execute this command after saving web.xml file #service tomcat5 restart import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class 14 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<html><head>"); out.println("<title>Server Information</title>");
Purohit Shrinivasacharya
2 2
} }
Purohit Shrinivasacharya
2 3
15. Program to accept username and address and display them in a webpage by passing parameters. 1. Save following html code as 12.html in folder /var/www/html
<html> <head> <title>Address</title> </head> <body bgcolor='#ffffff', text='#000000'> <h1 align=center> Client Address</h1> <hr> <center> <form method=get action=http://localhost:8080/test/servlet/15> <table align=center border=0> <tr><td>Name :</td><td> <input type=text name=name></td></tr> <tr><td>Address :</td><td><input type=text name=address></td></tr> <tr><td>City :</td><td><input type=text name=city></td></tr> <tr><td>Pin Code :</td><td><input type=text name=code></td></tr> <tr><td>State :</td><td><input type=text name=state></td></tr> </table> <br> <input type=submit value=SUBMIT> <hr> </form> </body> </html>
import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class 15 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String name,code,address,state,city; response.setContentType("text/html"); name=request.getParameter("name"); address=request.getParameter("address");
Purohit Shrinivasacharya
2 4
city=request.getParameter("city"); code=request.getParameter("code"); state=request.getParameter("state"); PrintWriter out=response.getWriter(); out.println("<html><body bgcolor='#000000', text='#33ff00'>"); out.println("<b>" +name+</b>); out.println("<br>" + address + <br> + city + <br> + code); out.println("<br>" + state); out.println("<body></html>"); out.close(); } }
Purohit Shrinivasacharya