0% found this document useful (0 votes)
24 views88 pages

WT Allexp

Web technology experiments

Uploaded by

reetu reethika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views88 pages

WT Allexp

Web technology experiments

Uploaded by

reetu reethika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Experiment 1:

Install the Following on local Machine

-Apache Webserver (if not installed)


-Tomcat Application Server Locally
-Install Mysql (if not Installed)
-Install PHP and Configure it to work with Apache WebServer and mysql(if not
already configured)

Steps to Install:
Step 1:
Open the XAMPP website. Go to https://www.apachefriends.org/index.html in your

computer's web browser.

Step 2:
Click XAMPP for Windows. It's a grey button near the bottom of the page.

 Depending on your browser, you may first have to select a save location or
verify the download.
Step 3:
Double-click the downloaded file. This file should be named something like xampp-
win32-7.2.4-0-VC15-installer, and you'll find it in the default downloads location
(e.g., the "Downloads" folder or the desktop).
Step 4:
Click Next. It's at the bottom of the setup window.

Step 5:
Select aspects of XAMPP to install. Review the list of XAMPP attributes on the left
side of the window; if you see an attribute that you don't want to install as part of
XAMPP, uncheck its box.

 By default, all attributes are included in your XAMPP installation.


Step 6:
Select an installation location. Click the folder-shaped icon to the right of the current
installation destination, then click a folder on your computer.

 If you have the UAC activated on your computer, avoid installing XAMPP in
your hard drive's folder (e.g., OS (C:)).
 You can select a folder (e.g., Desktop) and then click Make New Folder to
create a new folder and select it as the installation destination.

Step-7:
Begin installing XAMPP. Click Next at the bottom of the window to do so. XAMPP will begin

installing its files into the folder that you selected.


Step 8:
Click Finish when prompted. It's at the bottom of the XAMPP window. Doing so will close the
window and open the XAMPP Control Panel, which is where you'll access your servers.

Step-9:

Click Save. Doing so opens the main Control Panel page


Step-10:
Start XAMPP from its installation point. If you need to open the XAMPP Control Panel
in the future, you can do so by opening the folder in which you installed XAMPP, right
-clicking the orange-and-white xampp-control icon, clicking Run as administrator,
and clicking Yes when prompted.

 When you do this, you'll see red X marks to the left of each server type (e.g.,
"Apache"). Clicking one of these will prompt you to click Yes if you want to
install the server type's software on your computer.

 Counterintuitively, double-clicking the xampp_start icon doesn't start XAMPP.

Step-11:

Resolve issues with Apache refusing to run. On some Windows 10 computers, Apache
won't run due to a "blocked port". This can happen for a couple of reasons, but there's a
relatively easy fix:[1]

 Click Config to the right of the "Apache" heading.

 Click Apache (httpd.conf) in the menu.

 Scroll down to the "Listen 80" section (you can press Ctrl+F and type in l i s t e n 8 0 to
find it faster).
 Replace 8 0 with any open port (e.g., 8 1 or 9 0 8 0 ).

 Press Ctrl+S to save the changes, then exit the text editor.

 Restart XAMPP by clicking Quit and then re-opening it in administrator mode from its
folder.
Experiment 2:

Write an Html Page include javascript that takes a given set of Integer number and
shows them after sorting in descending order

Source Code:

Sortdesc.html

<html>

<head>

<title>Number in Descending Order</title>

<script language="javascript">

function ndesc() {

var num_array = new Array();

var num = document.forms["frm1"].num.value;

document.forms["frm1"].desc.value = "";

var nums = num.split(',');

var len = num.split(',').length;

for (var i = 0; i < len; i++) {

num_array.push(nums[i]);

function sortN(a, b) {

return b - a;

}
document.forms["frm1"].desc.value = num_array.sort(sortN);

</script>

</head>

<body>

<form name="frm1">

<center>

<h3> Numbers in Descending Order</h3>

</center>

<br />

<center>Enter Numbers separated by Comma : <input type="text" name="num"


</input><br /></center>

<br />

<center>

<input type="button" name="inwords" value="In Descending Order"


onclick="ndesc()"></input>

</center>

<br /><br />

<center>Number in Descending Order : <input type="text" name="desc"


</input></center>

<br />

</form>

</body>
</html>

Output:
Experiment 3:

Write an HTML page including any required JavaScript that takes a number from
one text field in the range of 0 to 999 and shows it in another text field in words. If the
number is out of range, it should show “out of range” and if it is not a number, it
should show “not a
number” message in the result box.

Source Code:

Conv.html
<html>

<head>

<title>Number in words</title>

<script language="javascript">

function convert() {

var num = document.forms["frm1"].num.value;

document.forms["frm1"].words.value = "";

if (isNaN(num)) {

alert("Not a Number");

else if (num < 0 || num > 999) {

alert("Out of Range");
}

else {

var len = num.length;

var words = "";

for (var i = 0; i < len; i++) {

var n = num.substr(i, 1);

switch (n) {

case '0': words += "Zero "; break;

case '1': words += "One "; break;

case '2': words += "Two "; break;

case '3': words += "Three "; break;

case '4': words += "Four "; break;

case '5': words += "Five "; break;

case '6': words += "Six "; break;

case '7': words += "Seven "; break;

case '8': words += "Eight "; break;

default: words += "Nine ";

document.forms["frm1"].words.value = words;

</script>

</head>
<body>

<form name="frm1">

<center>

<h3>NUMBER IN WORDS</h3>

</center>

<br />

<center>Enter a Number :<input type="text" name="num" </input><br


/></center>

<br />

<center><input type="button" name="inwords" value="In Words"


onclick="convert()"></input></center>

<br /><br />

<center>Number in Words :<input type="text" name="words" </input></center>

<br />

</form>

</body>

</html>
Output:
Experiment 4:

Write an HTML page that has one input, which can take multi line text and a submit
button. Once the user clicks the submit button, it should show the number of
characters, words and lines in the text entered using an alert message. Words are
separated with white space and lines are separated with new line character.

Exp4.html

<html>

<head>

<title>Lines,words,characters</title>
<script language="javascript">

function count()

var str=document.getElementById('inputstring').value;

var result='';

result+='The number of characters are'+str.length+'\n';

var arr=str.split(' ');

result+='The number of words are'+arr.length+'\n';

var a=str.split('\n');

result+='The number of lines are'+a.length;

alert(result);

</script></head>

<body>

<form name="frm1">

<center><b>Enter Multiple lines of text </b><br/><br/><textarea id="inputstring"


cols="50" rows="5"></textarea><br/><br/>

<input type="button" value="Count" onclick="count()"></input><br/><br/>

</form>

</body>

</html>

Output:
Input:

Result:
Experiment 5:

Write an HTML page that contains a selection box with a list of 5 countries. When
the user selects a country, its capital should be printed next to the list. Add CSS to
customize the properties of the font of the capital (color, bold and font size).

Exp5.html

<html>

<title>Capitals of Countries</title>

<head>

<style>

h1{

color:blue;

font-family:verdana;

font-size:300%;
}

select{

// A reset of styles, including removing the default dropdown arrow

appearance: none;

// Additional resets for further consistency

background-color: #fff;

border: 3;

border-radius: 0.35em;

padding: 0.25em 0.5em;

margin: 0;

width: 40%;

font-family: verdana;

font-size: inherit;

cursor: pointer;

line-height: inherit;

</style>

<script language="javascript">

function OnDropDownChange(dropDown)

var selectedValue = dropDown.options[dropDown.selectedIndex].value;


document.getElementById("txtSelectedCapital").innerHTML = selectedValue;

</script>

</head>

<body>

<form action = "">

<center>

<b>Select a Country :</b> <select name = "Countries"


onChange="OnDropDownChange(this);">

<option value="">--Select a country--</option>

<option value="New Delhi">India</option>

<option value="Wellington">New Zealand</option>

<option value="Paris">France</option>

<option value="Athens">Greece</option>

<option value="Madrid">Spain</option>

<option value="Beijing">China</option>

<option value="Islamabad">Pakistan</option>

<option value="Japan">Japan</option>

</select>

<h1 id="txtSelectedCapital" type="text"></h1>

</center>

</form>

</body>
</html>

Output :

Selection of Value:

Displaying the value of selected Index:


Experiment 6: Create an XML document that contains 10 users information. Write a
java program, which takes user id as input and returns the user details by taking the
user information from XML document using

a)DOM parser

b)SAX parser

Procedure: write the java and xml files. Compile and run the java file.

AIM: Takes User Id as input and returns the user details using XML with DOM

Java DOM Parser: DOM stands for Document Object Model. The DOM API provides
the classes to read and write an XML file. DOM reads an entire document. It is useful
when reading small to medium size XML files. It is a tree-based parser and a little slow
when compared to SAX and occupies more space when loaded into memory. We
can insert and delete nodes using the DOM API.
We have to follow the below process to extract data from an XML file in Java.

 Instantiate XML file:


 Get root node: We can use getDocumentElement() to get the root node
and the element of the XML file.
 Get all nodes: On using getElementByTagName() Returns a NodeList of
all the Elements in document order with a given tag name and are
contained in the document.
 Get Node by text value: We can use getElementByTextValue() method in
order to search for a node by its value.
 Get Node by attribute value: we can use the getElementByTagName()
method along with getAttribute() method.

PROGRAM:

employees.xml

<employees>
<employee id="111">
<firstName>Naresh</firstName>
<lastName>Gupta</lastName>
<location>India</location>
</employee>
<employee id="222">
<firstName>Kumar</firstName>
<lastName>Gussin</lastName>
<location>Russia</location>
</employee>
<employee id="333">
<firstName>David</firstName>
<lastName>Feezor</lastName>
<location>USA</location>
</employee>

<employee id="444">
<firstName>Lokesh</firstName>
<lastName>Gupta</lastName>
<location>India</location>
</employee>
<employee id="555">
<firstName>Vishnu</firstName>
<lastName>Gussin</lastName>
<location>Russia</location>
</employee>
<employee id="666">
<firstName>Veeru</firstName>
<lastName>Feezor</lastName>
<location>USA</location>
</employee>
<employee id="777">
<firstName>Pavan</firstName>
<lastName>Feezor</lastName>
<location>USA</location>

</employee>
<employee id="888">
<firstName>Narayana</firstName>
<lastName>Gussin</lastName>
<location>Russia</location>
</employee>
<employee id="999">
<firstName>David</firstName>
<lastName>Feezor</lastName>
<location>USA</location>
</employee>
<employee id="1000">
<firstName>Sunder</firstName>
<lastName>Feezor</lastName>
<location>USA</location>
</employee>
</employees>

ReadXML.java:
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.Scanner;
public class ReadXML {
public static void main(String a[]) throws Exception{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

//Build Document
Document document = builder.parse(new
File("C:\\Users\\Naresh\\Desktop\\employees.xml"));

//Normalize the XML Structure; It's just too important !!


document.getDocumentElement().normalize();

//Here comes the root node


Element root = document.getDocumentElement();

//Get all employees


NodeList nList =
document.getElementsByTagName("employee");
System.out.println("enter employee id:");

Scanner s=new Scanner(System.in);


String id=s.next();
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
if(eElement.getAttribute("id").equals(id)){
System.out.println("First Name : " +
eElement.getElementsByTagName("firstName").item(0).getTextConten
t());
System.out.println("Last Name : " +
eElement.getElementsByTagName("lastName").item(0).getTextContent
());
System.out.println("Location : " +
eElement.getElementsByTagName("location").item(0).getTextContent())
;
}
}
}
}
}

OUTPUT:-

Enter Employee Id: 222

B) Java SAX Parser


SAX Parser in java provides API to parse XML documents. SAX parser is a lot
more different from DOM parser because it doesn’t load complete XML into
memory and read XML document sequentially. In SAX, parsing is done by
the ContentHandler interface and this interface is implemented
by DefaultHandler class.

Let’s now see an example on extracting data from XML using Java SAX
Parser.
Create a java file for SAX parser. In this case, we have created
GfgSaxXmlExtractor.java
student.xml

<?xml version="1.0" encoding="UTF-8"?>


<students-details>
<student>
<studentid>561</studentid>
<name>Ramu</name>
<address>ECIL</address>
<gender>Male</gender>
</student>
<student>
<studentid>562</studentid>
<name>Ramya</name>
<address>KBHP</address>
<gender>Female</gender>
</student>
<student>
<studentid>563</studentid>
<name>Mahi</name>
<address>BHEL</address>
<gender>Male</gender>
</student>
<student>
<studentid>564</studentid>
<name>Manvi</name>
<address>KOTI</address>
<gender>Female</gender>
</student>
<student>
<studentid>565</studentid>
<name>Ammu</name>
<address>ECIL</address>
<gender>Female</gender>
</student>
</students-details>
import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserxml extends DefaultHandler
{
boolean studentid = true,name = false,address = false,gender = false;
int flag=0,c=0;
String sid,sname,sadd,sgender,tid;
public void startDocument()
{
System.out.println("begin parsing document");
System.out.print("Enter student ID:\t");
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
tid = reader.readLine();
}catch(Exception e){}
}
public void startElement(String url,String localname, String qName, Attributes att){
if (qName.equalsIgnoreCase("studentid"))
{
studentid = true;
}
else if (qName.equalsIgnoreCase("name") && flag==1)
{
name = true;
}
else if (qName.equalsIgnoreCase("address")&& flag==1)
{
address = true;
}
else if (qName.equalsIgnoreCase("gender")&& flag==1)
{
gender = true;
}
}

public void characters(char[] ch,int start,int length){


if (studentid)
{
String x=new String(ch, start, length);
if(x.equals(tid))
{
flag=1;sid=x; c=1;
}
else
flag=0;
studentid = false;
}
else if (name)
{
sname=new String(ch, start, length); name = false;
}
else if (address)
{
sadd=new String(ch, start, length); address = false;
}
else if (gender)
{
sgender=new String(ch, start, length); gender = false;
}
}
public void endElement(String url,String localname, String qName){}
public void endDocument()
{
if(c==0)
System.out.println("student Id is not present.Try Again!!!");
else
{
System.out.println("\n\n STUDENT-DETAILS");
System.out.println("===================");
System.out.println("student id :\t" +sid);
System.out.println("student Name :\t" +sname);
System.out.println("Adress :\t" +sadd);
System.out.println("Gender :\t" +sgender);
}
}
public static void main(String[] arg)throws Exception{
SAXParser p=SAXParserFactory.newInstance().newSAXParser();
p.parse(new FileInputStream("student.xml"), new SAXParserxml());
}
}
Experiment 7:

A user validation web application, where the user submits the login name and
password to the server. The name and password are checked against the data already
available in database and if the data matches, a successful login page is returned.
Otherwise a failure message is shown to the user.

Login.html

<html>

<head>

<title> Login</title>

</head>

<body>

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

<div align="center">

<b><h3>Member Login</h3> </b></td>

<h2>Username:<input type="text" name="Uname" ></h2>

<h2>Password:<input type="password" name="pwd"></h2>

<input type="submit" value="submit">

</div>

</form>

</body>

</html>
database.php

<?php

$mysql_host='localhost';

$mysql_user='root';

$mysql_password='';

$name=$_POST['Uname'];

$pwd=$_POST['pwd'];

$conn=@mysqli_connect($mysql_host,$mysql_user,$mysql_password);

if($conn)

if(@mysqli_select_db($conn,'login'))

{
//echo "successfully conected";

else

echo "connection failed to DB";

else

die('connection error');

$query="select * from user";

$get=mysqli_query($conn,$query);

if($get)

while($retrieve=mysqli_fetch_assoc($get))

if($name==$retrieve['Uname'] && $pwd==$retrieve['Password'])

echo "Welcome".$name ;

return true;
}

else{

echo "Invalid username or Password";

return false;

else

echo "Query not executed";

?>

Output:
Experiment 8:

Modify the above program to use an XML file instead of database.

Aim:

A user validation web application, where the user submits the login name and
password to the server. The name and password are checked against the data
already available in xml file (users.xml) and if the data matches, a successful login
page is returned. Otherwise a failure message is shown to the user.

Source Code:

users.xml

<?xml version="1.0"?>
<users>

<user>

<userid>madhu</userid>

<password>12345</password>

</user>

<user>

<userid>naveen</userid>

<password>12345</password>

</user>

<user>

<userid>durga</userid>

<password>12345</password>

</user>

<user>

<userid>ramesh</userid>

<password>12345</password>

</user>

</users>

Loginxml.php

<html>

<head>
<title>Login </title>

</head>

<body>

<form name="form1" method="post">

<table align="center" width="80%" border="0" cellpadding="3" cellspacing="1">

<tr >

<td colspan=2 align="center">

<b><h3>Member Login</h3> </b></td>

</tr>

<br/>

<tr>

<td>Username : </td>

<td><input name="uname" type="text"></td>

</tr>

<tr>

<td>Password : </td>

<td><input name="pwd" type="password"></td>

</tr>

<tr>

<td></td>

<td ><input type="submit" name="Submit" value="Login"></td>

</tr>

</table>

</form>
<?php

if(isset($_POST["Submit"]))

$uname=$_POST["uname"];

$pwd=$_POST["pwd"];

$xml=simplexml_load_file("users.xml") or die("Error: Cannot create object");

foreach($xml->children() as $users)

if($users->userid==$uname)

if($users->password==$pwd)

echo "<center><b>Hello..".$uname . ", ";

echo "Login Successful</b></center> ";

return;

else

echo "<center><b>Invalid Password...</b></center>";

return;

}
echo "<center><b>Invalid Login..</b></center>";

?>

</body>

</html>

Output:
Experiment 9:

Modify the above program to use AJAX to show the result on the same page below
the

submit button.

Aim:

A user validation page web application, where the user submits the login name and
password to the server. The name and password are checked against the data
already available in database and if the data matches, a successful login Message is
returned. Otherwise a failure message is shown to the user. Use AJAX to show the
result on the same page below the button.

Index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>

<body>
<form id="loginForm">
<input type="text" placeholder="Name" id="name" required>
<input type="text" placeholder="Password" id="pwd" required>
<button type="submit">Submit</button>
</form>
<div id="result"></div>

<script>
var xhttp = new XMLHttpRequest();
var loginForm = document.getElementById('loginForm');
loginForm.addEventListener("submit",submit,false);
function submit(e)
{
e.preventDefault();
var username = document.getElementById('name').value;
var userpwd = document.getElementById('pwd').value;
var result = document.getElementById("result");

xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {

var xmlDoc = xhttp.responseXML;


var name =
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
var pwd =
xmlDoc.getElementsByTagName("pwd")[0].childNodes[0].nodeValue;
console.log(name+pwd);
if(name == username && pwd == userpwd){
result.innerHTML = '<h1>Successfully logged in</h1>';

else{
result.innerHTML = '<h1>Wrong Details</h1>';
}
loginForm.reset();
}
};

xhttp.open("GET", "users.xml", true);


xhttp.send();
}
</script>
</body>
</html>

Login.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>

<body>
<h1>Successfully logged in</h1>
</body>
</html>

Users.xml

<?xml version="1.0" encoding="utf-8"?>


<users>
<name>kumar</name>
<pwd>admin</pwd>
</users>

OUTPUT:-
Experiment 10:

A simple calculator web application that takes two numbers and an operator (+,-,/,* and %)
from an HTML page and returns the result page with the operation performed on the
operands.

Calc.php

<?php

ini_set('display_errors',0);

if( isset( $_REQUEST['calculate'] ))

$operator=$_REQUEST['operator'];

if($operator=="+")

$add1 = $_REQUEST['fvalue'];

$add2 = $_REQUEST['lvalue'];

$res= $add1+$add2;

if($operator=="-")

$add1 = $_REQUEST['fvalue'];

$add2 = $_REQUEST['lvalue'];

$res= $add1-$add2;

if($operator=="*")

$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];

$res =$add1*$add2;

if($operator=="/")

$add1 = $_REQUEST['fvalue'];

$add2 = $_REQUEST['lvalue'];

$res= $add1/$add2;

if($_REQUEST['fvalue']==NULL && $_REQUEST['lvalue']==NULL)

echo "<script language=javascript> alert(\"Please Enter values.\");</script>";

else if($_REQUEST['fvalue']==NULL)

echo "<script language=javascript> alert(\"Please Enter First value.\");</script>";

else if($_REQUEST['lvalue']==NULL)

echo "<script language=javascript> alert(\"Please Enter second value.\");</script>";

?>

<form>
<table style="border:groove #00FF99">

<tr>

<td style="background-color:aqua; color:red; font-family:'Times New


Roman'">Enter First Number</td>

<td colspan="1">

<input name="fvalue" type="text" style="color:red"/></td>

<tr>

<td style="color:burlywood; font-family:'Times New Roman'">Select


Operator</td>

<td>

<select name="operator" style="width: 63px">

<option>+</option>

<option>-</option>

<option>*</option>

<option>/</option>
</select></td>

</tr>

<tr>

<td style="background-color:aqua; color:red; font-family:'Times New


Roman'">Enter First Number</td>

<td class="auto-style5">

<input name="lvalue" type="text" style="color:red"/></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="calculate" value="Calculate"


style="color:wheat;background-color:rosybrown" /></td>
</tr>

<tr>

<td style="background-color:aqua;color:red">Output = </td>

<td style="color:darkblue"><?php echo $res;?></td>

</tr>

</table>

</form>

Output:
Experiment 11:
Modify the above program such that it stores each query in database and checks the
database first for result. If the query is already available in the DB, it returns the value that
was previously computed (from DB) or it computes the result and returns it after storing the
new query and result in DB.
<html>
<body>

<h2>Welcome</h2>
<fieldset style="width:280px">
<legend>Calculator</legend>
<form method="post">
<br/>Number 1: <input type="text" name="num1" id="num1"><br/>
<br/>Number 2: <input type="text" name="num2" id="num2"><br/>
<br/>Operation: &nbsp;&nbsp;
+ <input type="radio" name="Operation" id="add" value="+" checked="checked">
&nbsp;&nbsp;
- <input type="radio" name="Operation" id="sub" value="-"> &nbsp;&nbsp;
* <input type="radio" name="Operation" id="mul" value="*"> &nbsp;&nbsp;
/ <input type="radio" name="Operation" id="div" value="/"> &nbsp;&nbsp;
<br/><br/>
<input type="submit" name="submit" id="submit" />
<br/>
</form>
</fieldset>
<?php

if($_POST)
{

echo '<fieldset style="width:280px">


<legend>Result</legend>';
if($_POST["num1"]=="" || $_POST["num2"]=="")
{
if($_POST["num1"]=="")
echo "Please enter Number 1 <br/>";
if($_POST["num2"]=="")
echo "Please enter Number 2 <br/>";
}else
if($_POST["num2"]==0)
{

echo "Number 2 should not be Zero. this is divided by zero error.";


}
else
{
echo $_POST["num1"] . " " . $_POST["Operation"] . " " . $_POST["num2"] . " = ";

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "calc";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT result FROM operations where number1=".$_POST["num1"]." and


number2=".$_POST["num2"]." and operation='".$_POST["Operation"]."'" ;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["result"];
}
echo "<br/> Result is displayed from database";
} else {
$resultVal=0;

switch($_POST["Operation"])
{
case "-":
echo $resultVal=$_POST["num1"] - $_POST["num2"];
break;
case "*":
echo $resultVal=$_POST["num1"] * $_POST["num2"];
break;
case "/":
echo $resultVal=$_POST["num1"] / $_POST["num2"];
break;
default:
echo $resultVal=$_POST["num1"] + $_POST["num2"];
break;
}

$sql = "INSERT INTO `employee`.`operations`


(`number1`,
`number2`,
`operation`,
`result`)
VALUES (".$_POST["num1"].",
".$_POST["num2"].",
'".$_POST["Operation"]."',
".$resultVal.");";
$result = $conn->query($sql);
echo "<br/> This is first time operation is queried.";
}
$conn->close();

}
echo "</fieldset>";
}

?>

</body>
</html>
Output:

Validations performed on above program


EXPERIMENT 12:

A web application that takes a name as input and on submit it shows a hello
<name> page where name is taken from the request. It shows the start time at the
right top corner of the page and provides a logout button. On clicking this button, it
should show a logout page with Thank You <name > message with the duration of
usage (hint: Use session to store name and time).

Source Code:

Login.html
<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Session Tracking</title>

</head>

<body bgcolor="#03c6fc">

<h2 align="center">Enter Name to Start Session</h2>

<center>

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

<table>

<tr><td><label for="name" ><b>Name:</b></label></td>

<td><input type="name" name="text1"><br></td></tr>

<br>

<tr></tr>

<tr></tr>

<tr><td colspan=2><center><input type="submit" name="Submit"


value="Submit"></center></td></tr>

</form>

<center>
</body>

</html>

Home.php

<?php

session_start();

date_default_timezone_set("Asia/Calcutta");

$_SESSION['luser'] = $_POST['text1'];

$_SESSION['start'] = time();

$tm=$_SESSION['start'];

print "<body bgcolor='#03c6fc'><b><p align='right'>Session started at " .


date("h:i:sa",$tm) . "<br>";

print "<center><form action='Logout.php' method='post'>";

print "<input type='submit' value='Logout'></p>";

print "</form></center>";

print "<center>Hello " . $_SESSION['luser']."</center></b></body>";

?>

Logout.php

<?php

session_start();

date_default_timezone_set("Asia/Calcutta");

print "<body bgcolor='#03c6fc'><p align='right'>Session started at " .


date("h:i:sa",time()) . "</p><br>";

print "<b><center>Thank you " . $_SESSION['luser']."</center>";

$sessiontime = time() - $_SESSION['start'];

print "<center><br> Your session duration: " . $sessiontime . "


seconds</center></b></body>";

session_destroy();

?>
Output:
Experiment 13:

A web application that takes name and age from an HTML page. If the age is less
than 18, it should send a page with “Hello <name>, you are not authorized to visit the
site” message, where <name> should be replaced with the entered name.
Otherwise it should send “Welcome <name> to this site” message.

Source Code:

Exp13.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Age Authorization</title>
</head>
<body bgcolor="#03c6fc">
<center><h2>Enter Name and Age</h2></center>
<center>
<form method="POST">
<br><br>
<table>
<tr><td><label for="name" ><b>Name:</b></label></td>
<td><input type="name" name="name"><br></td></tr>
<br>
<tr></tr>
<tr><td><label for="age" ><b>Age:</b></label></td>
<td><input type="number" name="age"></td></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr><td colspan=2><center><input type="submit" name="Submit"
value="Submit"></center></td></tr>
</table>
</form>
</center>
<?php

if(isset($_POST["Submit"])){
// ob_end_clean();
$n=$_POST['name'];
$a=$_POST['age'];
if($a>=18){
echo
"<center><h2>Welcome</h2></center>"."<center><h2>".$n."</h2></center>";
}
else{
echo "<center><h2> Unauthorized Access
</h2></center>"."<center><h2>".$n."</h2></center>";
}
}
?>
</body>
</html>
Outputs:
Experiment 14:

A Web Application for implementation:

The User is first served a login page which takes user’s name and password.After
Submitting the details the server check these values against the data from a
database and takes following decisions

If name and password matches , serves a welcome page with user’s full name

If name matches and password doesn’t matche , serves a ”password mismatch”


page

If name is not found in the database,serves a registration page,where user’s full


name is asked and on submitting the full name . It stores,the login name,password
and fullname in database(hint:use session for storing the submitted login name and
password)

Source Code:

Regist.html

<!DOCTYPE html>

<html>

<head>

<title>Registration</title>

</head>

<body>

<center><h2>Enter Login Details</h2></center>

<center>

<form method="POST" action="Submit1.php">

<table>

<tr>
<td>

<label for="name">Username:</label>

</td>

<td>

<input type="name" name="name" >

</td>

</tr>

<tr>

<td>

<label for="password" name="">Password:</label>

</td>

<td>

<input type="password" name="password">

</td>

</tr>

<tr></tr>

<tr><td colspan="2" align="center"><input type="Submit"


name="Submit"></td></tr>

</table>

</form>

</center>

</body>

</html>
Submit1.php

<?php

$mysql_host='localhost';

$mysql_user='root';

$mysql_password='';

$name=$_POST['name'];

$pwd=$_POST['password'];

$conn=@mysqli_connect($mysql_host,$mysql_user,$mysql_password);

ob_end_clean();

if($conn)

if(@mysqli_select_db($conn,'login1'))

{}

else

echo "connection failed to DB";

else

die('connection error');

$c=0;

$c1=0;
$c2=0;

$query="select * from user_pass";

$get=mysqli_query($conn,$query);

if($get)

while($retrieve=mysqli_fetch_assoc($get))

if($name==$retrieve['Username'] && $pwd==$retrieve['Password'])

echo "<head><title>Welcome</title></head>";

echo "<center><h3><b>Welcome ".$name." </b></h3></center>" ;

return true;

else if($name==$retrieve['Username'] && $pwd!=$retrieve['Password'])

$c2+=1;

else{

$c++;

$c1++;

if($c==$c1 && $c2==0){


echo "<head><title>Register</title></head>";

echo "<center><h2>There is no User with Username ".$name." So,Kindly


Register Before Trying to Log in</h2></center>";

echo "<center><h2>Enter to Register</h2></center>";

echo "<center><form action='Submit2.php' method='POST'>";

echo "<table><tr><td>Username:</td><td><input type='name'


name='new_user'></td></tr>";

echo "<table><tr><td>Password:</td><td><input type='password'


name='new_pass'></td></tr>";

echo "<tr><td colspan='2' align='center'><input type='Submit'


name='Submit'></td></tr></center></table>";

else{

echo "<head><title>Invalid Password</title></head>";

echo "<center><h3><b>Wrong Password Try Again</b></h3></center>";

else

echo "Query not executed";

Submit2.php

<?php

$mysql_host='localhost';

$mysql_user='root';
$mysql_password='';

$name=$_POST['new_user'];

$pwd=$_POST['new_pass'];

$conn=@mysqli_connect($mysql_host,$mysql_user,$mysql_password);

if($conn)

if(@mysqli_select_db($conn,'login1'))

//echo "successfully conected";

else

echo "connection failed to DB";

else

die('connection error');

$get=mysqli_query($conn,"Insert into user_pass values('$name','$pwd')");

if($get)

echo "<head><title>Succesfull Registration</title></head>";

echo "<center><h2>Registered Succesfully</h2>";


echo "<b><a href='Regist.html'>Click here to Login</a><b></center>";

else

echo "Query not executed";

?>

Output:

Username and Password Matched Case:


Username matches but password doesn’t match case:
Username doesn’t Exist Case:
Experiment 15:

A web application that lists all cookies stored in the browser on clicking “List
Cookies” button. Add cookies if necessary.

Source Code:

setCookies.php

<html>

<head>

<title> Set Cookies </title>

</head>

<body bgcolor="#81d6b1"> <br>

<center>

<?php

setcookie('Cookie_1','Cookie_1_Value',time() + 86400);

setcookie('Cookie_2',"Cookie_2_Value",time() + 86400);

print "<h2><b><hr>Two cookies are set now for 24hrs<hr></b></h2>";

?>

</center>

</body>

</html>

listCookies.php

<html>

<head>

<title> Cookies </title>


</head>

<body bgcolor="#81d6b1">

<center>

<h1>Cookies Are:</h1>

<br><br>

<form action="" method="post">

<br><br>

<input type="submit" value="LIST COOKIES" name="list">

<br><br>

</form>

</center>

<?php

error_reporting(0);

if($_POST['list'])

foreach($_COOKIE as $key=>$val)

echo "<center>".$key." is ".$val."<br>

</center>";

?>

</body>
</html>

Output:
Lead 1:
Write a program to check whether the given number is Armstrong number or not
using PHP Script

Source Code:

Arm.php

<html>

<head>

<title>Armstrong Number Checker</title>

</head>

<body>

<center>

<h1>Enter the Number</h1>

<form method="POST" action="">

<table>

<tr>

<td>Number:</td>

<td><input type="number" name="num"></td>

</tr>

<tr>

<td colspan=2 align='center'>

<input type="Submit" name="Submit">

</td>

</tr>
</table>

</form>

<br>

<?php

if(isset($_POST['Submit'])){

$num=$_POST['num'];

if($num<0)

echo "Please Enter a positive value";

else{

$s=0;

$temp=$num;

$c=0;

$temp1=$temp;

while($temp1>0){

$c++;

$temp1=intdiv($temp1,10);

while($temp>0){

$x=$temp%10;

$s+=$x**$c;

$temp=intdiv($temp,10);

if($num==$s)
echo "<h3><b>Given Number ".$num." is a Armstrong Number</b></h3>";

else

echo "<h3><b>Given Number ".$num." is not a Armstrong


Number</b></h3>";

} }

?>

</center>

</body>

</html>

Output:
Lead2:
Write a program to print Fibonacci Series using PHP Script

Source Code:

Fib.php
<html>

<head>

<title>Fibonacci Generator</title>

</head>

<body>

<center>

<h1>Enter the Intial Values and Length of Series</h1>

<form method="POST" action="">

<table>

<tr>

<td>First Number:</td>

<td><input type="number" name="num1"></td>

</tr>

<tr>

<td>Second Number:</td>

<td><input type="number" name="num2"></td>

</tr>
<tr>

<td>Series Length:</td>

<td><input type="number" name="n"></td>

</tr>

<tr>

<td colspan=2 align='center'>

<input type="Submit" name="Submit">

</td>

</tr>

</table>

</form>

<br>

<?php

if(isset($_POST['Submit'])){

$num1=$_POST['num1'];

$num2=$_POST['num2'];

$n=$_POST['n'];

echo "<h3><b>Series is ".$num1." ".$num2." ";

for($i=0;$i<$n;$i++){

$tp=$num2;

$num2=$num1+$num2;

$num1=$tp;

echo $num2." ";


}

?>

</center>

</body>

</html>

Output:

You might also like