Вы находитесь на странице: 1из 32

Web Programming Laboratory

2013

Web Programming Laboratory


Subject Code: 10CSL78 I.A. Marks : 25
Hours/Week : 03 Exam Hours: 03
Total Hours : 42 Exam Marks: 50
1. Develop and demonstrate a XHTML file that includes Javascript script for the
following problems:
a) Input: A number n obtained using prompt
Output: The first n Fibonacci numbers
b) Input: A number n obtained using prompt
Output: A table of numbers from 1 to n and their squares using alert
2. a) Develop and demonstrate, using Javascript script, a XHTML document that
collects the USN ( the valid format is: A digit from 1 to 4 followed by two upper-case
characters followed by two digits followed by two upper-case characters followed by
three digits; no embedded spaces allowed) of the user. Event handler must be included
for the form element that collects this information to validate the input. Messages in the
alert windows must be produced when errors are detected.
b) Modify the above program to get the current semester also (restricted to be a number
from 1 to 8)
3. a) Develop and demonstrate, using Javascript script, a XHTML document that
contains three short paragraphs of text, stacked on top of each other, with only enough
of each showing so that the mouse cursor can be placed
over some part of them. When the cursor is placed over the exposed part of any
paragraph, it should rise to the top to become completely visible.
b) Modify the above document so that when a paragraph is moved from the top
stacking position, it returns to its original position rather than to the bottom.
4. a) Design an XML document to store information about a student in an engineering
college affiliated to VTU. The information must include USN, Name, Name of the
College, Brach, Year of Joining, and e-mail id. Make up sample data for 3 students.
Create a CSS style sheet and use it to display the document.
b) Create an XSLT style sheet for one student element of the above document and use it
to create a display of that element.
5. a) Write a Perl program to display various Server Information like Server Name,
Server Software, Server protocol, CGI Revision etc.
b) Write a Perl program to accept UNIX command from a HTML form and to display
the output of the command executed.
6. a) Write a Perl program to accept the User Name and display a greeting message
randomly chosen from a list of 4 greeting messages.
Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

b) Write a Perl program to keep track of the number of visitors visiting the web page
and to display this count of visitors, with proper headings.
7. Write a Perl program to display a digital clock which displays the current time of the
server.
8. Write a Perl program to insert name and age information entered by the user into a
table created using MySQL and to display the current contents of this table.
9. Write a PHP program to store current date-time in a COOKIE and display the Last
visited on date-time on the web page upon reopening of the same page.
10. Write a PHP program to store page views count in SESSION, to increment the
count on each refresh, and to show the count on web page.
11. Create a XHTML form with Name, Address Line 1, Address Line 2, and E-mail text
fields. On submitting, store the values in MySQL table. Retrieve and display the data
based on Name.
12. Build a Rails application to accept book information viz. Accession number, title,
authors, edition and publisher from a web page and store the information in a database
and to search for a book with the title specified by the user and to display the search
results with proper headings.
Note: In the examination each student picks one question from the
lot of all 12 questions.

Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

Steps to be followed with the Terminal


1) Always begin with the following commands
(space) /etc/init.d/httpd start OR service httpd start
or
a. service network start
2) To check whether apache server is running in the background
/etc/init.d/httpd status OR service httpd status
will see so many processes running in the background . It will display 2001, 2007,
2009.....
3) All the HTML, XML, XSLT, CSS, PHP programs should be saved in
# cd /var/www/html (enter into html dir)
4) To go Editor
All html pgograms should have .html extension
5) vim 1a.html
Edit the HTML Program. Paste the Program
6) .to save ESC SHIFT :wq(write and Quit)
# vim Mystyle.css
7) paste the css portion
To run the program go to Browser. in the adress bar type http://localhost/1a.html
You can see the Output.
8) To run perl programs
# cd /var/www/cgi-bin
All perl programs should be saved under .pl extension
vim 6a.pl
paste the perl program , save and Quit
To see the output go to browser and in the adress bar type http://localhost/cgi-bin/6a.pl
9to check errors in perl type perlcc c filename.pl
10) For mysql programs
service mysqld start
mysql> show databases;
use any of the databases available or create a new database
create student
use student
show tables
if tables are not available create a new table by the following cmd
create table tablename
insert into table

Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

One more method:


Steps to be followed with the Text Editor
1. To start httpd: system Administrator servicescheckbox shud be checked at
httpd and click START press OK.
2. to open text editor ApplicationsAccessoriestext editorSave(to save
file)Filesystemvarwwwhtmlfilename.html
3. to open text editor ApplicationsAccessoriestext editorSave(to save
file)Filesystemvarwwwcgi-binfilename.pl
***********************************************************************
**********************************************************************

1. Develop and demonstrate a XHTML file that includes Javascript script for the
following problems:
a) Input: A number n obtained using prompt
Output: The first n Fibonacci numbers
b) Input: A number n obtained using prompt
Output: A table of numbers from 1 to n and their squares using alert
*****************************1a.html****************************
<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Fibonacci Numbers </title>
</head>
<body>
<h1>Calculating the fibonacci numbers</h1>
<script type="text/javascript"> var n,a=0,b=1,i,c
n=prompt("Enter a number ","")
if(n<=0)
alert("Invalid number")
else
{
if(n==1)
document.write(a)
else document.write(a+"<br />"+b)
for(i=2;i<n;i++)
{
c=a+b
a=b
b=c
Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

document.write("<br />"+c)
}
}
</script>
</body>
</html>
******************************Output*********************************

b) Input: A number n obtained using prompt.


Output: A table of numbers from 1 to n and their squares using alert.
******************************1b.html**************************
<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <title>Squares of numbers</title> </head>
<body>
<h1>
Printing numbers &amp; calculating their squares
</h1>
<script type="text/javascript">
var n,i;
Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

n=prompt("Enter a number","");
if(n>0)
{
c="Number | Square"
for(i=1;i<=n;i++)
c=(c+"\n"+i+" -----> "+i*i);
alert(c)
}
else alert("Enter a number greater than 1.")
</script>
</body>
</html>
*************************** Output*********************************

Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

2. a) Develop and demonstrate, using Javascript script, a XHTML document that


collects the USN ( the valid format is: A digit from 1 to 4 followed by two upper-case
characters followed by two digits followed by two upper-case characters followed by
three digits; no embedded spaces allowed) of the user. Event handler must be included
for the form element that collects this information to validate the input. Messages in the
alert windows must be produced when errors are detected.
b) Modify the above program to get the current semester also (restricted to be a number
from 1 to 8)
**********************************2a.html**********************************
<html>
<head> <title> USN Validation </title> </head>
<body>
<script type="text/javascript">
function func(usn)
{
var pattern1=/^[1-4][A-Z]{2}[0-9]{2}[A-Z]{2}[0-9]{3}$/
if(!usn.value.match(pattern1)||usn.value.length==0)
{
alert("Invalid USN!\nEnter a valid USN")
return false
}
else alert("USN valid!")
}
</script>
<form action="">
<p>
USN: <input type="text" name="usn" /> <br/>
<input type="button" value="Validate" onclick="func(usn)" />
</p>
</form>
</body>
</html>
******************************Output**********************************

Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

b) Modify the above program to get the current semester also (restricted to be a number
from 1 to 8)
**********************************2b.html**********************************
<html>
<head><title>usn and semester validation</title></head>
<body>
<script type="text/javascript">
function disp(usn,sem)
{
var pattern1=/^[1-4][A-Z]{2}[0-9]{2}[A-Z]{2}[0-9]{3}$/
if(!usn.value.match(pattern1)||usn.value.length==0)
{
alert("invalid usn!\n enter a valid usn")
return false
}
else alert("usn valid!")
var pattern2=/^[1-8]$/
if(!sem.value.match(pattern2)||sem.value.length==0)
{
alert("invalid semester!\n enter a valid semester")
return false
}else alert("semester valid!")
}
</script>
<form action="">
<p>
usn:<input type="text"name="usn"/> <br />
semester:<input type="text"name="sem"/> <br />
<input type="button" value="validate" onclick="disp(usn,sem)"/>
</p>
</form>
</body>
</html>
Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

***************************** Output**********************************

3. a) Develop and demonstrate, using Javascript script, a XHTML document that


contains three short paragraphs of text, stacked on top of each other, with only enough
of each showing so that the mouse cursor can be placed over some part of them. When
the cursor is placed over the exposed part of any paragraph, it should rise to the top to
become completely visible.
**********************************3a.html**********************************
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>lab 3a</title>
<script type="text/javascript" >
var top="p1";
function toTop(newTop)
{
var domTop=document.getElementById(top).style;
var domNew=document.getElementById(newTop).style;
domTop.zIndex="0";
Dept. of ISE, RRIT Bangalore

Web Programming Laboratory

2013

domNew.zIndex="10";
top=newTop;
}
</script>
<style type="text/css">
.para1 {position:absolute;top:0;left:0;z-index:0;background-color:red;}
.para2 {position:absolute;top:50px;left:110px;z-index:0;background-color:green;}
.para3 {position:absolute;top:100px;left:220px;z-index:0;background-color:blue;}
</style>
</head>
<body>
<br/>
<div>
<p class="para1" id="p1" onmouseover="toTop('p1')">
Notepad is a basic text editor that you can use to create simple documents.<br />Notepad is a
basic text editor that you can use to create simple documents.<br />Notepad is a basic text
editor that you can use to create simple documents.<br />Notepad is a basic text editor that
you can use to create simple documents.<br />Notepad is a basic text editor that you can use
to create simple documents.
</p>
<p class="para2" id="p2" onmouseover="toTop('p2')">
Notepad is a basic text editor that you can use to create simple documents.<br />Notepad is a
basic text editor that you can use to create simple documents.<br />Notepad is a basic text
editor that you can use to create simple documents.<br />Notepad is a basic text editor that
you can use to create simple documents.<br />Notepad is a basic text editor that you can use
to create simple documents.
</p>
<p class="para3" id="p3" onmouseover="toTop('p3')">
Notepad is a basic text editor that you can use to create simple documents.<br />Notepad is a
basic text editor that you can use to create simple documents.<br />Notepad is a basic text
editor that you can use to create simple documents.<br />Notepad is a basic text editor that
you can use to create simple documents.<br />Notepad is a basic text editor that you can use
to create simple documents.
</p>
</div>
</body>
</html>

Dept. of ISE, RRIT Bangalore

10

Web Programming Laboratory

2013

******************************Output***************************

3b) Modify the above document so that when a paragraph is moved from the top
stacking position, it returns to its original position rather than to the bottom.
**********************************3b.html**********************************
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>lab 3b</title>
<script type="text/javascript">
var top="p1";
function toTop(newTop)
{
var domTop=document.getElementById(top).style;
var domNew=document.getElementById(newTop).style;
domTop.zIndex="0";
domNew.zIndex="10";
top=newTop;
}
function toOriginal()
{
document.getElementById("p1").style.zIndex=0;
document.getElementById("p2").style.zIndex=0;
document.getElementById("p3").style.zIndex=0;
}
</script>
<style type="text/css">
.para1 {position:absolute;top:0;left:0;z-index:0;background-color:red;}
.para2 {position:absolute;top:50px;left:110px;z-index:0;background-color:green;}
.para3 {position:absolute;top:100px;left:220px;z-index:0;background-color:blue;}
</style>
</head>
<body>
<br/>
<div>
<p class="para1" id="p1" onmouseover="toTop('p1')"onmouseout="toOriginal()">
Dept. of ISE, RRIT Bangalore

11

Web Programming Laboratory

2013

Notepad is a basic text editor that you can use to create simple documents.<br />Notepad is a
basic text editor that you can use to create simple documents.<br />Notepad is a basic text
editor that you can use to create simple documents.<br />Notepad is a basic text editor that
you can use to create simple documents.<br />Notepad is a basic text editor that you can use
to create simple documents.
</p>
<p class="para2" id="p2" onmouseover="toTop('p2')"onmouseout="toOriginal()">
Notepad is a basic text editor that you can use to create simple documents.<br />Notepad is a
basic text editor that you can use to create simple documents.<br />Notepad is a basic text
editor that you can use to create simple documents.<br />Notepad is a basic text editor that
you can use to create simple documents.<br />Notepad is a basic text editor that you can use
to create simple documents.
</p>
<p class="para3" id="p3" onmouseover="toTop('p3')":onmouseout="toOriginal()">
Notepad is a basic text editor that you can use to create simple documents.<br />Notepad is a
basic text editor that you can use to create simple documents.<br />Notepad is a basic text
editor that you can use to create simple documents.<br />Notepad is a basic text editor that
you can use to create simple documents.<br />Notepad is a basic text editor that you can use
to create simple documents.
</p>
</div>
</body>
</html>
******************************Output***********************************

4 a) Design an XML document to store information about a student in an engineering


college affiliated to VTU. The information must include USN, Name, Name of the
College, Brach, Year of Joining, and e-mail id. Make up sample data for 3 students.
Create a CSS style sheet and use it to display the document.
*******************************4a.xml*******************************
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="4a.css"?>
<student>
<stud-info>Student Information</stud-info>
<stud1>
Dept. of ISE, RRIT Bangalore

12

Web Programming Laboratory

2013

<usn>USN: 1RI10IS009</usn>
<name>NAME: Aashish</name>
<college>COLLEGE: RRIT</college>
<branch>BRANCH: IS</branch>
<year>YEAR: 2010</year>
<email>EMAIL:abc@gmail.com</email>
</stud1>
<stud2>
<usn>USN: 1RI10is002</usn>
<name>NAME: def</name>
<college>COLLEGE: RRIT</college>
<branch>BRANCH: IS</branch>
<year>YEAR: 2010</year>
<email>EMAIL: def@gmail.com</email>
</stud2>
<stud3>
<usn>USN: 1RI10Is003</usn>
<name>NAME: xyz</name>
<college>COLLEGE: RRIT</college>
<branch>BRANCH: IS</branch>
<year>YEAR: 2010</year>
<email>EMAIL: xyz@yahoo.com</email>
</stud3>
</student>
********************************4a.css**************************************
stud-info{display:block;color:blue;font-style:italic; font-size:200%;}
student{display:block;font-size:100%;}
stud1{display:block;color:blue;}
stud2{display:block;color:red;}
stud3{display:block;color:black;}
usn,name,college,branch,year,email{display:block;}

Dept. of ISE, RRIT Bangalore

13

Web Programming Laboratory

2013

******************************Output***********************************

4b) Create an XSLT style sheet for one student element of the above document and use
it to create a display of that element.
*******************************4b.xml******************************
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="4b.xsl"?>
<student>
<usn>1RI10IS006</usn>
<name>anil</name>
<noc>:rrit</noc>
<branch>ise</branch>
<yoj>2010</yoj>
<eid>anil@g.com</eid>
</student>
*****************************4b.xsl********************************
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="student">
<html>
<head><title><h1>stylesheet for 4b.xml</h1></title>
Dept. of ISE, RRIT Bangalore

14

Web Programming Laboratory

2013

</head>
<body>
<h2>vtu student description</h2>
<span style = "font-style: italic;color: blue;">usn:
</span>
<xsl:value-of select = "usn" /> <br />
<span style = "font-style: italic;color: blue;">name:
</span>
<xsl:value-of select = "name" /> <br />
<span style = "font-style: italic;color: blue;">college:
</span>
<xsl:value-of select = "noc" /> <br />
<span style = "font-style: italic;color: blue;">branch:
</span>
<xsl:value-of select = "branch" /> <br />
<span style = "font-style: italic;color: blue;">year:
</span>
<xsl:value-of select = "yoj" /> <br />
<span style = "font-style: italic;color: blue;">email:
</span>
<xsl:value-of select = "eid" /> <br />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
******************************Output***********************************

Dept. of ISE, RRIT Bangalore

15

Web Programming Laboratory

2013

PERL
The first line is the standard reference to the location of Perl on your server. If you're not
sure where Perl is on your server, type which perl at the command prompt.
The next item is the HTTP header, which is the Perl script telling the browser what type
of document it will be displaying after the server executes the script. It's telling the
browser that it will be displaying a text (which is what HTML is) HTML document, as
opposed to a plain text document, image or any other number of content types. This line
must be included before any of the print statements in the script. This line must be
followed by a blank line which is why there are two new line commands (\n) included.
The first one goes to the next line, the second puts a blank line after it.
After the browser knows what type of stuff it will be displaying, the script gets around to
printing the HTML tags. Here we have simple print statements, enclosed in quotes with a
new line character and the semicolon to end the statement. The new line character isn't
necessary, but it makes the code displayed by the browser easier to read. Otherwise when
you View Source using your browser, the HTML would be on one long line.
Type this script using any text editor and save it using whatever name you want with a .pl
extension. (Don't try copying and pasting from the browser. It may not translate correctly
and you will learn better by typing it in.) Upload it to your server's cgi-bin directory. (If
you are in the Windows environment, be sure to upload the file in ASCII format, not
Binary.) Be sure to give it the correct permissions by typing chmod 777 whatever.pl
Now you can access the script by typing in the URL with the filename appended like
this:
http://localhost/cgi-bin/7a.pl
If it doesn't run for you the first time you try, don't be dismayed, be sure you have every
character in exactly the right place and that you have the correct file permissions. If it still
doesn't work, run the script from the Telnet command line by typing
5. a) Write a Perl program to display various Server Information like Server Name,
Server Software, Server protocol, CGI Revision etc.
**********************************5a.pl**********************************
#!/usr/bin/perl
#this line tells the machine to run the file through perl
#evironment variables can be accessed using $env
print "content-type:text/html","\n\n";
print "<html><body> SERVER INFO <br>";
print "<br> Server name=",$ENV{'SERVER_NAME'};
print "<br> Running port=",$ENV{'SERVER_PORT'};
print "<br> Server protocol=",$ENV{'SERVER_PROTOCOL'};
print "<br> Server software=",$ENV{'SERVER_SOFTWARE'};
print "<br> CGI version=",$ENV{'GATEWAY_INTERFACE'};
print "<br></body></html>";
Dept. of ISE, RRIT Bangalore

16

Web Programming Laboratory

2013

******************************Output***********************************

5b) Write a Perl program to accept UNIX command from a HTML form and to display
the output of the command executed.
1. String variables are prefixed by $
2. System command will execute unix command
3. A 'QUERY_STRING' is the part of a URL which is attached to the end, after the file name.
It begins with a question mark and usually includes information in pairs.
4. The format is parameter=value, as in the following example:
http://localhost/cgi-bin/6b.pl?com=date

**********************************5b.html**********************************
<html>
<body bgcolor="powderblue">
<h1><font color="red"> Enter the command</font></h1>
<form action="http://localhost/cgi-bin/5b.pl" >
<input type="text" name="com" />
<input type="submit" value="Submit" />
<input type="reset" value="clear" />
</form>
</body>
</html>
**********************************5b.pl**********************************
#!/usr/bin/perl
use CGI':standard';
print "content type: text/html \n\n";
$c=param('com');
system($c);
exit(0);

Dept. of ISE, RRIT Bangalore

17

Web Programming Laboratory

2013

******************************Output***********************************

6. a) Write a Perl program to accept the User Name and display a greeting message
randomly chosen from a list of 4 greeting messages.
**********************************6a.html**********************************
<html>
<head><title>username</title></head>
<body bgcolor="aqua">
<font color="maroon">enter the name:-</font>
<form action="http://localhost/cgi-bin/6a.pl" method="get">
<br>
<input type="text" name="username" size=40>
<input type="submit" value="submit">
<input type="reset" value="clear">
</form></body></html>
**********************************6a.pl**********************************
#!/usr/bin/perl
use CGI':standard';
print "content-type:text/html","\n\n";
$input=param(username);
Dept. of ISE, RRIT Bangalore

18

Web Programming Laboratory

2013

print"<h1>hi!</h1>",$input;
my @msgs=("good day","***welcome***","fine day","best wishes");
print"<h1>";
print "$msgs[int rand scalar @msgs]";
print "</h1> thanks for visiting";
******************************Output***********************************

Dept. of ISE, RRIT Bangalore

19

Web Programming Laboratory

2013

6b) Write a Perl program to keep track of the number of visitors visiting the web page
and to display this count of visitors, with proper headings.
1. Create 6b.txt file in cgi-bin and give permission chmod 777 6b.txt
2. Store 0 (zero) in 6b.txt as initial counter and save the file
3. Read from file open(FILE,"<6b.txt")
4. Increment the access counter
5. Write to the file open(FILE,">6b.txt ")
**********************************6b.pl**********************************
#!/usr/bin/perl
use CGI':standard';
print"content-type:text/html","\n\n";
print"<html><body>No. of visits <br>";
$file="6b.txt";
open(INFO,$file);
$n=<INFO>;
close(INFO);
print $n;
open (INFO, ">6b.txt");
print INFO++$n;
close INFO;
print "<br></body></html>";
******************************Output***********************************
Before executing the program need to check whether selinux is on or off i.e (0 or 1)
Type this command in the root only, not in the directory /var/www/cgi-bin
# cat /selinux/enforce
1
# echo 0> /selinux/enforce
# cat /selinux/enforce
0

Dept. of ISE, RRIT Bangalore

20

Web Programming Laboratory

2013

7. Write a Perl program to display a digital clock which displays the current time of the
server.
*******************************7.pl***********************************
#!/usr/bin/perl
#refresh line should be correct in ordee to refresh, "Refresh:"is must
use CGI':standard';
print "Refresh:1\n";
print "content-type:text/html","\n\n";
print "<html><body><h1>Digital Clock </h1><br>";
$str= "A.M" ;
($s,$m,$h)=localtime(time);
if($h>12)
{
$str="P.M";
$h -=12;
}
print "<br><h2><i>The current time is $h:$m:$s $str</i></h2>";
print "<br></body></html>";
exit(0);
******************************Output***********************************

8. Write a Perl program to insert name and age information entered by the user into a
table created using MySQL and to display the current contents of this table.
Procedure to create database.

First type /sbin/service mysqld start it will start system database.


Type mysql and press enter
To create database type create database databasename; ex: create database rrit;
show databases; will shows the database present in the system.
use databasename; To use the database created type this query.
show tables;
create table tablename(name varchar(30),age integer(3)); it will create new table.

Dept. of ISE, RRIT Bangalore

21

Web Programming Laboratory

2013

select * from tablename; it will display the table content.

Dept. of ISE, RRIT Bangalore

22

Web Programming Laboratory

2013

***********************************8.pl********************************
#!/usr/bin/perl
print "content-type: text/html\n\n";
print "<html><title>Result of the insert operation </title>";
use CGI ':standard';
use DBI;
$dbh=DBI->connect("DBI:mysql:rrit","root","");
$name=param("name");
$age=param("age");
$qh=$dbh->prepare("insert into stud values('$name','$age')");
$qh->execute();
$qh=$dbh->prepare("Select * from stud");
$qh->execute();
print "<table border size=1><tr><th>Name</th><th>Age</th></tr>";
while ( ($name,$age)=$qh->fetchrow())
{
print "<tr><td>$name</td><td>$age</td></tr>";
}
print "</table>";
$qh->finish();
$dbh->disconnect();
print"</html>";
********************************8.html********************************
<html>
<form action="http://localhost/cgi-bin/8.pl">
Name : <input type="text" name="name"> <br>
Age : <input type="text" name="age"> <br>
<input type="submit" value="Submit">
</form>
</html>
******************************Output***********************************

Dept. of ISE, RRIT Bangalore

23

Web Programming Laboratory

2013

*********************************Terminal output****************************

9. Write a PHP program to store current date-time in a COOKIE and display the Last
visited on date-time on the web page upon reopening of the same page.
Steps for PHP
1) Create PHP file using .php file extension in the directory
cd /var/www/html
2) To run PHP , in the browser type http://localhost/filename.php
***********************************9.php***********************************
<?php
date_default_timezone_set('Asia/Calcutta');
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
if(isset($_COOKIE['lastVisit']))
{
$visit = $_COOKIE['lastVisit'];
echo "Your last visit was - ". $visit;
}
else
echo "You've got some stale cookies!";
?>
Dept. of ISE, RRIT Bangalore

24

Web Programming Laboratory

2013

******************************Output***********************************

10. Write a PHP program to store page views count in SESSION, to increment the
count on each refresh, and to show the count on web page.
session start Initialize session data:
A PHP session variable is used to store information about, or change settings for a user
session. Session variables hold information about one single user, and are available to all
pages in one application
Before you can store user information in your PHP session, you must first start up the
session.
<?php session_start(); ?>
The above code will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
The correct way to store and retrieve session variables is to use the PHP $_SESSION
variable.
In the above example, we create a simple page-views counter. The isset() function checks if
the "count" variable has already been set. If "count" has been set, we can increment our
counter. If "count" doesn't exist, we create a "count" variable, and set it to 1
session_start() creates a session or resumes the current one based on the current session
id that's being passed via a request, such as GET, POST, or a cookie. This function
retrieves the $_SESSION array
_SESSION["count"]: When you want to store user data in a session use the
$_SESSION associative array. This is where you both store and retrieve session data.
Session_reister(count): Registers any number of variables and places them in the
session. The variable to be registered is passed as a string. Alternatively, a list of variables
to be registered can be passed as an array. It returns TRUE on success; FALSE on error

Dept. of ISE, RRIT Bangalore

25

Web Programming Laboratory

2013

********************************10.php*********************************
<?php
session_start();
session_register("count");
if (!isset($_SESSION))
{
$_SESSION["count"] = 0;
echo "<p>Counter initialized</p>\n";
}
else { $_SESSION["count"]++; }
echo "<p>The counter is now <b>$_SESSION[count]</b></p>".
"<p>reload this page to increment</p>";
?>
******************************Output***********************************

11. Create a XHTML form with Name, Address Line 1, Address Line 2, and E-mail text
fields. On submitting, store the values in MySQL table. Retrieve and display the data
based on Name.
Procedure to create database
1. Run the mysql
2. Create database mysql;
3. Use mysql;
4. Create table student(Name varchar(30) ,Address1 varchar(40) ,Address2
varchar(40),Email varchar(30) );
*********************************11.html***********************************
<html>
<body>
<form action="http://localhost/insert.php" method="post">
Name: <input type="text" name="name" />
Address Line 1: <input type="text" name="address1" />
Dept. of ISE, RRIT Bangalore

26

Web Programming Laboratory

2013

Address Line 2: <input type="text" name="address2" />


Email: <input type="text" name="email" />
<input type="submit" />
</form>
</body>
</html>
********************************insert.php********************************
<html>
<body>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql");
$sql="INSERT INTO student(Name,Address1,Address2,Email)
VALUES('$_POST[name]','$_POST[address1]','$_POST[address2]','$_POST[email]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
<form action="http://localhost/result.php" method="post">
Name: <input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
*******************************result.php************************************
<html>
<head><title>Search Result </title></head>
<body>
<h3>Search Result </h3>
<hr>
<?php
$link=mysql_connect("localhost","root","");
mysql_select_db("mysql");
$n=$_POST["name"];
print "Entered Name is $n \n";
$var=mysql_query("SELECT * FROM student WHERE name like '%$n%'");
Dept. of ISE, RRIT Bangalore

27

Web Programming Laboratory

2013

echo"<table border size=1>";


echo"<tr><th>Name</th> <th>Address1</th> <th>Address2</th>
<th>Email</th></tr>";
while ($arr=mysql_fetch_row($var))
{
echo "<tr><td>$arr[0]</td> <td>$arr[1]</td> <td>$arr[2]</td>
<td>$arr[3]</td> </tr>";
} echo"</table>"; mysql_free_result($var); mysql_close($link);
?>
<hr>
</body>
</html>
******************************Output***********************************

Dept. of ISE, RRIT Bangalore

28

Web Programming Laboratory

2013

***************************Terminal Output (database) *********************

12. Build a Rails application to accept book information viz. Accession number, title,
authors, edition and publisher from a web page and store the information in a database
and to search for a book with the title specified by the user and to display the search
results with proper headings.
Run Rail exe to start the program
Check weather both Apache and My-Sql is started else start it
Next click on menuRail ApplicationManage rail Application
In Dos Prompt do the following steps
1. Create Books Database-OPEN the rails console
mysql u root
mysql>create database v7_development;
mysql>use v7_development;
mysql>create table books(id int primary key auto_increment, acc_no varchar(20) not null,
title text not null, authors text not null, edition text not null, publisher text not null);
mysql>exit;
2.Creating lab12 project
Rails d mysql v7
3.Creating Controller, Model and View Form Database
cd v7
ruby script/generate scaffold Book acc_no:string
publisher:text

title:text

authors:text edition:text

4.Starting Rails Server


ruby script/server

Dept. of ISE, RRIT Bangalore

29

Web Programming Laboratory

2013

5.Executing In Web Server (eq: Firefox)


http://localhost:3000/books

6.Creating Main(New) Controller For Search


ruby script/generate controller main
7.Opening Main Controller Program
>notepad app\controllers\main_controller.rb [notepad will write the following code and save
it]
class MainController < ApplicationController
def welcome
@num_books=Book.count
end
def result
@bookid=params[:sid]
@bookz=Book.find(:all,:conditions => "id=#{@bookid}")
end
end
8.Create Result View File
>notepad app\views\main\result.rhtml [notepad will write the following code and save it]
<html>
<title>welcome
</title>
<body>
<p>Enter book id<%=@bookid%></p>
<table border=1>
<tr><th>book id
</th><th>acc_no</th><th>title</th><th>authors</th><th>edition</th><th>publisher</th>
</tr>
<%@bookz.each do |bk|
@id=bk.id
@acc_no=bk.acc_no
@title=bk.title
@authors=bk.authors
@edition=bk.edition
@publisher=bk.publisher%>
<tr>
<td><%=@id%></td>
<td><%=@acc_no%></td>
Dept. of ISE, RRIT Bangalore

30

Web Programming Laboratory

2013

<td><%=@title%></td>
<td><%=@authors%></td>
<td><%=@edition%></td>
<td><%=@publisher%></td>
</tr>
<%end%>
</table>
</form>
</body>
</html>
9.Create Welcome View File
>notepad app\views\main\welcome.rhtml [notepad will write the following code and save it]
<html>
<title> welcome
</title>
<body>
<p>total no of books=<%=@num_books%></p>
<form action="result">
enter <input type="text" name="sid"/>
<input type="submit" value="search"/>
</form>
</body>
</html>
10.Starting Rails Server
Ruby script/server
11.Executing In Web Server
http://localhost:3000/main/welcome

*******************************Output******************************

Dept. of ISE, RRIT Bangalore

31

Web Programming Laboratory

Dept. of ISE, RRIT Bangalore

2013

32

Вам также может понравиться