0% found this document useful (0 votes)
6 views

tybcs_solution

The document contains multiple slips of code examples in PHP, HTML, JavaScript, and XML. These examples cover various functionalities such as session tracking, user preferences with cookies, login authentication, form validation, and generating Fibonacci numbers. Each slip demonstrates specific programming tasks or concepts relevant to web development.

Uploaded by

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

tybcs_solution

The document contains multiple slips of code examples in PHP, HTML, JavaScript, and XML. These examples cover various functionalities such as session tracking, user preferences with cookies, login authentication, form validation, and generating Fibonacci numbers. Each slip demonstrates specific programming tasks or concepts relevant to web development.

Uploaded by

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

Slip 1:

Q. 1)Write a PHP script to keep track of number of times the web page has been
accessed (Use SessionTracking)

<?php
// Start the session
session_start();

// Check if the counter is already set in the session


if (isset($_SESSION['counter'])) {
// Increment the counter by 1
$_SESSION['counter']++;
} else {
// If the counter is not set, initialize it to 1
$_SESSION['counter'] = 1;
}

// Display the number of times the page has been accessed


echo "This page has been accessed " . $_SESSION['counter'] . " times.";
?>

-----------------------------------------------------------------------------------
------------------------------------------------------
slip 2:

<!DOCTYPE html>
<html>
<head>
<title>Preferences</title>
</head>
<body>
<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Save preferences in cookies
setcookie("font_style", $_POST['font_style'], time() + (86400 * 30), "/");
setcookie("font_size", $_POST['font_size'], time() + (86400 * 30), "/");
setcookie("font_color", $_POST['font_color'], time() + (86400 * 30), "/");
setcookie("bg_color", $_POST['bg_color'], time() + (86400 * 30), "/");
// Redirect to display preferences page
header("Location: {$_SERVER['PHP_SELF']}");
exit();
}
// Reset preferences when reset button is clicked
if (isset($_POST['reset'])) {
setcookie("font_style", "", time() - 3600, "/");
setcookie("font_size", "", time() - 3600, "/");
setcookie("font_color", "", time() - 3600, "/");
setcookie("bg_color", "", time() - 3600, "/");
header("Location: {$_SERVER['PHP_SELF']}");
exit();
}
?>
<?php
// Display form to set preferences
if (!isset($_COOKIE['font_style'])) {
// If preferences are not set, show the form
?>
<h2>Select Your Preferences</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="font_style">Font Style:</label>
<select name="font_style">
<option value="Arial">Arial</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Verdana">Verdana</option>
</select><br><br>
<label for="font_size">Font Size:</label>
<select name="font_size">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select><br><br>
<label for="font_color">Font Color:</label>
<input type="color" name="font_color"><br><br>
<label for="bg_color">Background Color:</label>
<input type="color" name="bg_color"><br><br>
<input type="submit" value="Save Preferences">
</form>
<?php
} else {
// If preferences are set, display them
?>
<h2>Selected Preferences</h2>
<div style="font-family:<?php echo $_COOKIE['font_style']; ?>;
font-size:<?php echo $_COOKIE['font_size']; ?>;
color:<?php echo $_COOKIE['font_color']; ?>;
background-color:<?php echo $_COOKIE['bg_color']; ?>;
padding: 20px;">
This is a sample text with selected preferences.
</div>
<br>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="reset" value="true">
<input type="submit" value="Reset Preferences">
</form>
<?php
}
?>
</body>
</html>
-----------------------------------------------------------------------------------
------------------------------------------------------
slip 3:

Login.php
<?php
session_start();
// Initialize variables
$max_attempts = 3;
$valid_username = "user"; // Change this to your valid username
$valid_password = "password"; // Change this to your valid password
$error = "";
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
// Check if username and password are correct
if ($username == $valid_username && $password == $valid_password) {
$_SESSION["authenticated"] = true;
header("Location: welcome.php");
exit();
} else {
$_SESSION["attempts"] = isset($_SESSION["attempts"]) ? $_SESSION["attempts"] + 1 :
1;
$attempts_left = $max_attempts - $_SESSION["attempts"];
if ($_SESSION["attempts"] >= $max_attempts) {
$error = "Maximum login attempts reached. Please try again later.";
session_destroy();
} else {
$error = "Invalid username or password. You have $attempts_left attempt(s) left.";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
<p style="color: red;"><?php echo $error; ?></p>
</body>
</html>

Welcome.php
<?php
session_start();
// Check if user is authenticated
if (!isset($_SESSION["authenticated"]) || $_SESSION["authenticated"] !== true) {
// If not authenticated, redirect to login page
header("Location: login.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Welcome!</h2>
<p>You have successfully logged in.</p>
</body>
</html>

-----------------------------------------------------------------------------------
------------------------------------------------------
slip 4:
-----------------------------------------------------------------------------------
------------------------------------------------------
slip 5 :

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


<Items>
<Item>
<item-name>Laptop</item-name>
<item-rate>50000</item-rate>
<item-quantity>10</item-quantity>
</Item>
<Item>
<item-name>Mobile Phone</item-name>
<item-rate>20000</item-rate>
<item-quantity>20</item-quantity>
</Item>
<Item>
<item-name>Television</item-name>
<item-rate>30000</item-rate>
<item-quantity>15</item-quantity>
</Item>
<Item>
<item-name>Refrigerator</item-name>
<item-rate>40000</item-rate>
<item-quantity>12</item-quantity>
</Item>
<Item>
<item-name>Air Conditioner</item-name>
<item-rate>60000</item-rate>
<item-quantity>8</item-quantity>
</Item>
</Items>
-----------------------------------------------------------------------------------
----------------------------------------------------
slip 6:

php file:
<?php
$xml = simplexml_load_file("slip6.xml");

echo "Attributes: <br>";


foreach ($xml->book[0]->attributes() as $name => $value) {
echo "$name: $value <br>";
}

echo "<br>Elements:<br>";
foreach ($xml->book[0]->children() as $child) {
echo $child->getName() . ": " . $child . "<br>";
}
?>

xml file:
<?xml version="1.0" encoding="UTF8"?>
<library>
<book id="1">
<title>The catcher in the Rye </title>
<author> J.D.Salinger</author>
<year>1951</year>
</book>
<br><br>
<book id="2">
<title>To Kill a Mockingbird</title>
<author>Haper Lee</author>
<year>1960</year>
</book>
<library>
-----------------------------------------------------------------------------------
----------------------------------------------------
slip 7:
-----------------------------------------------------------------------------------
-----------------------------------------------------
slip 8:

Q. 1)Write a JavaScript to display message ‘Exams are near, have you started
preparing for?’ (usealert box ) and Accept any two numbers from user and display
addition of two number .(Use Prompt andconfirm box)
Slip8.html
<!DOCTYPE html>
<head>
<title>JavaScript Task</title>
<script>
// Display an alert with a message
alert("Exams are near, have you started preparing for?");

// Accept two numbers from the user using prompt


var num1 = prompt("Enter the first number:");
var num2 = prompt("Enter the second number:");

// Convert the prompt inputs to numbers (as they are initially strings)
num1 = parseFloat(num1);
num2 = parseFloat(num2);

// Use confirm box to ask if the user wants to calculate the sum
var userConfirm = confirm("Do you want to calculate the addition of the two
numbers?");

if (userConfirm) {
// If the user confirms, calculate and display the sum
var sum = num1 + num2;
alert("The sum of the two numbers is: " + sum);
} else {
// If the user cancels, display a message
alert("You chose not to calculate the sum.");
}
</script>
</head>
<body>

</body>
</html>

-----------------------------------------------------------------------------------
-----------------------------------------------------
slip 9:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Membership Form</title>
<script>
function validateForm() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;

// Validate Username: At least 6 characters long


if (username.length < 6) {
alert("Username must be at least 6 characters long!");
return false; // Prevent form submission
}

// Validate Password: At least 6 characters long, contains at least 1


digit and 1 special character
var passwordPattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])[A-Za-z0-9!@#$%^&*]
{6,}$/;
if (password.length < 6) {
alert("Password must be at least 6 characters long!");
return false; // Prevent form submission
} else if (!passwordPattern.test(password)) {
alert("Password must contain at least one digit and one special
character!");
return false; // Prevent form submission
}

// If everything is okay, show success message


alert("Form submitted successfully!");
return true; // Allow form submission
}
</script>
</head>
<body>

<h2>Membership Form</h2>

<form onsubmit="return validateForm()">


Username (at least 6 characters):
<input type="text" id="username" name="username" required><br><br>

Password (at least 6 characters, 1 digit, 1 special character):


<input type="password" id="password" name="password" required><br><br>

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


</form>

</body>
</html>

-----------------------------------------------------------------------------------
-----------------------------------------------------
sip 10:

<!DOCTYPE html>
<html>
<head>
<title>Insert Text Before and After Paragraph</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

<p id="myParagraph">This is a sample paragraph.</p>

<button id="insertText">Insert Text</button>

<script>
$(document).ready(function() {
$("#insertText").click(function() {
$("#myParagraph").before("<b>Text before paragraph: </b>");
$("#myParagraph").after("<b>Text after paragraph: </b>");
});
});
</script>

</body>
</html>
-----------------------------------------------------------------------------------
-----------------------------------------------------
slip 11:

-----------------------------------------------------------------------------------
-----------------------------------------------------
slip 12:

-----------------------------------------------------------------------------------
-----------------------------------------------------
slip 13:

-----------------------------------------------------------------------------------
-----------------------------------------------------
slip 14:

-----------------------------------------------------------------------------------
-----------------------------------------------------
slip 15:

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

slip 16:

-----------------------------------------------------------------------------------
-----------------------------------------------------
slip 17:
Q. 1) Write a Java Script Program to show Hello Good Morning message onload event
using alert box
and display the Student registration from. [Marks 15]

<html>

<head>
<title>Hello Good Morning</title>
<script> window.onload = function () {
alert("Hello! Good Morning");

};

function showRegistrationForm() {
document.getElementById("registrationForm").style.display = "block";
}
</script>
</head>

<body>
<h2>Student Registration Form</h2>
<form>
Name:
<input type="text" id="name" name="name"><br><br>
Email:
<input type="email" id="email" name="email"><br><br>
Phone:
<input type="text" id="phone" name="phone"><br><br>
<input type="submit" value="Submit"> </form>
</div>

<button onclick="showRegistrationForm()">Show Registration Form</button>


</body>

</html>
-----------------------------------------------------------------------------------
---------------------------------------------------
slip 18:

<!DOCTYPE html>
<html>
<head>
<title>Simple Fibonacci Generator</title>
</head>
<body>
<h1>Fibonacci Numbers</h1>
<button onclick="generateFibonacci()">Generate Fibonacci</button>
<p id="output"></p>

<script>
function generateFibonacci() {
var n = parseInt(prompt("Enter the number of terms:"));
var n1 = 0, n2 = 1, result = "";

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


result += n1 + (i < n - 1 ? ", " : ""); // Add a comma except for the last
number
var nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}

document.getElementById("output").textContent = result;
}
</script>
</body>
</html>
-----------------------------------------------------------------------------------
----------------------------------------------------
slip 19 :

slip19.html
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
</head>
<body>
<h1>User Login</h1>
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>

<script src="Slip19.js"></script>
</body>
</html>

slip19.js
const form = document.getElementById('myForm');
form.addEventListener('submit', (e) =>
{
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (username === '' || password === '')
{
alert('Please enter both username and password.');
e.preventDefault();
} else if (username.length < 4 || username.length > 20)
{
alert('Username must be between 4 and 20 characters.');
e.preventDefault();
} else if (password.length < 8)
{
alert('Password must be at least 8 characters.');
e.preventDefault();
} else
{
alert('Form submitted successfully!');
}
});
-----------------------------------------------------------------------------------
----------------------------------------------------
slip 20:

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


<students>
<student>
<rollno>101</rollno>
<name>John Doe</name>
<address>123 Main St, City, Country</address>
<college>ABC University</college>
<course>Computer Science</course>
</student>
<student>
<rollno>102</rollno>
<name>Jane Smith</name>
<address>456 Elm St, City, Country</address>
<college>XYZ College</college>
<course>Electrical Engineering</course>
</student>
<student>
<rollno>103</rollno>
<name>Michael Brown</name>
<address>789 Oak St, City, Country</address>
<college>LMN Institute</college>
<course>Civil Engineering</course>
</student>
<student>
<rollno>104</rollno>
<name>Emily Johnson</name>
<address>101 Pine St, City, Country</address>
<college>XYZ College</college>
<course>Mechanical Engineering</course>
</student>
<student>
<rollno>105</rollno>
<name>Chris Lee</name>
<address>202 Birch St, City, Country</address>
<college>ABC University</college>
<course>Information Technology</course>
</student>
</students>

-----------------------------------------------------------------------------------
---------------------------------------------------
slip 21:
-----------------------------------------------------------------------------------
----------------------------------------------------
slip 22:

slip 23:

-----------------------------------------------------------------------------------
----------------------------------------------------
slip 24:
slip24A.php

<?php
// Create student.xml file if it doesn't exist
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"
?><students></students>');

// Add student data to XML


$student1 = $xml->addChild('student');
$student1->addChild('rollno', '101');
$student1->addChild('name', 'John Doe');
$student1->addChild('address', '123 Main St');
$student1->addChild('college', 'XYZ University');
$student1->addChild('course', 'Computer Science');
$student2 = $xml->addChild('student');
$student2->addChild('rollno', '102');
$student2->addChild('name', 'Jane Smith');
$student2->addChild('address', '456 Elm St');
$student2->addChild('college', 'XYZ University');
$student2->addChild('course', 'Electrical Engineering');

$student3 = $xml->addChild('student');
$student3->addChild('rollno', '103');
$student3->addChild('name', 'Michael Brown');
$student3->addChild('address', '789 Oak St');
$student3->addChild('college', 'XYZ University');
$student3->addChild('course', 'Computer Science');

// Save the XML file


$xml->asXML('student.xml');
echo "student.xml file created successfully!";
?>

slip24B.php

<?php
// Load the XML file
$xml = simplexml_load_file('student.xml');

// Initialize variables
$course = "";
$students = [];

// Process the form if it's submitted


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$course = $_POST['course'];

// Filter students based on the course


foreach ($xml->student as $student) {
if ((string)$student->course == $course) {
$students[] = $student;
}
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Details</title>
</head>
<body>
<h1>Student Details by Course</h1>

<!-- Form to input course -->


<form method="POST">
Enter Course:
<input type="text" name="course" id="course" required>
<input type="submit" value="Search">
</form>
<!-- Display results if the form is submitted -->
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST'): ?>
<?php if ($students): ?>
<table border="1">
<tr><th>Roll No</th><th>Name</th><th>Course</th></tr>
<?php foreach ($students as $student): ?>
<tr>
<td><?php echo $student->rollno; ?></td>
<td><?php echo $student->name; ?></td>
<td><?php echo $student->course; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<p>No students found for this course.</p>
<?php endif; ?>
<?php endif; ?>
</body>
</html>
-----------------------------------------------------------------------------------
---------------------------------------------------------
slip 29:

<?php
// Initialize variables
$fibResult = "";
$sumResult = 0;

// Check if form is submitted


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$number = $_POST['number'];

$a = 0;
$b = 1;
$fibResult = "Fibonacci Series: ";
for ($i = 0; $i < $number; $i++) {
$fibResult .= $a . " ";
$next = $a + $b;
$a = $b;
$b = $next;
}

// Calculate sum of digits


$sumResult = array_sum(str_split($number));
}
?>

<!DOCTYPE html>
<head>

<title>Fibonacci and Sum of Digits</title>


</head>
<body>
<h1>Fibonacci Series and Sum of Digits</h1>

<!-- Form to accept number from the user -->


<form method="POST" action="">
Enter a number:
<input type="number" name="number" id="number" required>
<input type="submit" value="Submit">
</form>

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST'): ?>


<h2>Results:</h2>
<p><strong><?php echo $fibResult; ?></strong></p>
<p><strong>Sum of digits: </strong><?php echo $sumResult; ?></p>
<?php endif; ?>

</body>
</html>
-----------------------------------------------------------------------------------
------------------------------------------------------

slip 30:
-----------------------------------------------------------------------------------
-------------------------------------------------------

You might also like