School of Engineering & Technology
Department: CSE Session: 2024-25
Program: BCA (AI&DS) Semester: V
Course Code: ETCA227A Number of students:
Course Name: Web Based Faculty: Dr. Surabhi Shanker
Programming using PHP
WEB BASED PROGRAMMING USING PHP
ASSIGNMENT :02
Name: Tejas Juneja
Roll No: 2201060035
Course: BCA(AI & DS)
Section - A
Submitted to: Mrs. Surabhi Shankar
1. Functions in PHP: Write a PHP program that defines
a function to calculate the factorial of a number. The
number should be provided by the user, and the
function should return the result?
Input:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Factorial Calculator</title>
</head>
<body>
<h1>Factorial Calculator</h1>
<form method="POST" action="">
<label for="number">Enter a number:</label>
<input type="number" name="number" required><br><br>
<input type="submit" value="Calculate Factorial">
</form>
<?php
// Function to calculate factorial
function factorial($n) {
if ($n == 0 || $n == 1) {
return 1;
} else {
return $n * factorial($n - 1);
// Processing the form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = $_POST['number'];
if ($number >= 0) {
$result = factorial($number);
echo "<h2>Factorial of $number is $result</h2>";
} else {
echo "<h2>Please enter a non-negative number.</h2>";
?>
</body>
</html>
OUTPUT:
2. Passing by Value and Reference: Create a PHP script
that demonstrates passing variables by value and by
reference in functions. Display how modifying a
variable within the function behaves differently in each
case?
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Passing by Value and Reference</title>
</head>
<body>
<h1>Passing by Value and Reference in PHP</h1>
<?php
// Function that modifies the variable (passing by value)
function modifyByValue($num) {
$num += 10;
echo "<p>Inside modifyByValue: \$num is $num</p>";
}
// Function that modifies the variable (passing by reference)
function modifyByReference(&$num) {
$num += 10;
echo "<p>Inside modifyByReference: \$num is $num</p>";
}
// Demonstration of passing by value
$a = 5;
echo "<h2>Passing by Value</h2>";
echo "<p>Before calling modifyByValue: \$a is $a</p>";
modifyByValue($a);
echo "<p>After calling modifyByValue: \$a is still $a
(unchanged)</p>";
// Demonstration of passing by reference
$b = 5;
echo "<h2>Passing by Reference</h2>";
echo "<p>Before calling modifyByReference: \$b is $b</p>";
modifyByReference($b);
echo "<p>After calling modifyByReference: \$b is now $b
(changed)</p>";
?>
</body>
</html>
OUTPUT:
3. Working with Forms (GET and POST Methods): Design
a login form that collects a username and password.
Validate the inputs using PHP and display a success or
error message based on the user's input using the POST
method?
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<!-- Login Form -->
<form method="POST" action="">
<label for="username">Username:</label>
<input type="text" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
<?php
// Predefined username and password (For demo purposes)
$validUsername = "user123";
$validPassword = "password123";
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get username and password from form input
$username = $_POST['username'];
$password = $_POST['password'];
// Basic validation: Check if username and password match
predefined values
if ($username === $validUsername && $password ===
$validPassword) {
echo "<h3>Login successful! Welcome, $username.</h3>";
} else {
echo "<h3 style='color: red;'>Error: Invalid username or
password.</h3>";
}
}
?>
</body>
</html>
Output:
4. HTML Form Controls and PHP Integration: Develop a form
that takes user feedback (name, email, rating, comments) and
stores the input in an array. Then display the collected feedback
on a separate page using the GET method?
CODE:
<!-- feedback_form.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>User Feedback Form</title>
</head>
<body>
<h2>User Feedback Form</h2>
<!-- Feedback Form -->
<form method="GET" action="display_feedback.php">
<label for="name">Name:</label>
<input type="text" name="name" ><br><br>
<label for="email">Email:</label>
<input type="email" name="email"><br><br>
<label for="rating">Rating (1-5):</label>
<select name="rating" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select><br><br>
<label for="comments">Comments:</label><br>
<textarea name="comments" rows="5" cols="30"
required></textarea><br><br>
<input type="submit" value="Submit Feedback">
</form>
</body>
</html>
CODE:
<!-- display_feedback.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Display Feedback</title>
</head>
<body>
<h2>Collected User Feedback</h2>
<?php
// Check if all data is present
if (isset($_GET['name']) && isset($_GET['email']) &&
isset($_GET['rating']) && isset($_GET['comments'])) {
// Retrieve data and sanitize
$feedback = [
'name' => htmlspecialchars($_GET['name']),
'email' => htmlspecialchars($_GET['email']),
'rating' => htmlspecialchars($_GET['rating']),
'comments' => htmlspecialchars($_GET['comments'])
];
// Display the feedback
echo "<p><strong>Name:</strong> " . $feedback['name'] . "</p>";
echo "<p><strong>Email:</strong> " . $feedback['email'] . "</p>";
echo "<p><strong>Rating:</strong> " . $feedback['rating'] . " out of
5</p>";
echo "<p><strong>Comments:</strong> " .
nl2br($feedback['comments']) . "</p>";
} else {
echo "<p>Error: All fields are required.</p>";
}
?>
</body>
</html>
OUTPUT:
5. Cookies: Create a PHP script that sets a cookie to store the
user’s preferred language (e.g., English, French, Spanish).
The next time the user visits the page, display a greeting
message in the selected language using the stored cookie?
CODE:
<!-- language_selection.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Select Your Preferred Language</title>
</head>
<body>
<?php
// Check if the user has already set a preferred language cookie
if (isset($_COOKIE['language'])) {
// Retrieve the language from the cookie
$language = $_COOKIE['language'];
// Display greeting based on the stored language
switch ($language) {
case 'English':
echo "<h2>Welcome!</h2>";
break;
case 'French':
echo "<h2>Bienvenue!</h2>";
break;
case 'Spanish':
echo "<h2>¡Bienvenido!</h2>";
break;
default:
echo "<h2>Welcome!</h2>";
break;
}
} else {
// Display form to select language if no cookie is set
echo '<h2>Select Your Preferred Language:</h2>';
}
?>
<!-- Language Selection Form -->
<form method="POST" action="">
<label for="language">Choose Language:</label>
<select name="language" required>
<option value="English">English</option>
<option value="French">French</option>
<option value="Spanish">Spanish</option>
</select>
<br><br>
<input type="submit" value="Save Language">
</form>
<?php
// Set the cookie if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['language'])) {
// Set the cookie for 30 days
$selectedLanguage = $_POST['language'];
setcookie('language', $selectedLanguage, time() + (30 * 24 * 60 * 60));
// Cookie valid for 30 days
// Display a message to confirm the language was set
echo "<p>Preferred language set to: " .
htmlspecialchars($selectedLanguage) . "</p>";
// Refresh the page to apply the cookie immediately
header("Refresh:0");
}
?>
</body>
</html>
OUTPUT:
6. Sessions: Write a PHP script to implement a shopping cart
system. Use sessions to add and remove items from the cart, and
display the cart's content on a separate page?
CODE:
<!-- shopping.php -->
<?php
session_start();
// Initialize the cart if it doesn't exist
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Handle adding items to the cart
if (isset($_POST['add_to_cart'])) {
$item = $_POST['item'];
$price = $_POST['price'];
// Add item to session cart
$_SESSION['cart'][] = ['item' => $item, 'price' => $price];
echo "<p>$item has been added to your cart.</p>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Simple Shopping Cart</title>
</head>
<body>
<h2>Shopping Page</h2>
<!-- Shopping items -->
<form method="POST" action="">
<label for="item">Item 1:</label>
<input type="hidden" name="item" value="Item 1">
<input type="hidden" name="price" value="10">
<input type="submit" name="add_to_cart" value="Add to Cart
($10)">
</form>
<form method="POST" action="">
<label for="item">Item 2:</label>
<input type="hidden" name="item" value="Item 2">
<input type="hidden" name="price" value="20">
<input type="submit" name="add_to_cart" value="Add to Cart
($20)">
</form>
<form method="POST" action="">
<label for="item">Item 3:</label>
<input type="hidden" name="item" value="Item 3">
<input type="hidden" name="price" value="30">
<input type="submit" name="add_to_cart" value="Add to Cart
($30)">
</form>
<p><a href="cart.php">View Cart</a></p>
</body>
</html>
<!-- cart.php -->
<?php
session_start();
// Handle removing items from the cart
if (isset($_GET['remove'])) {
$index = $_GET['remove'];
// Remove item from session cart
unset($_SESSION['cart'][$index]);
$_SESSION['cart'] = array_values($_SESSION['cart']); // Reindex
array
}
// Initialize message
$message = '';
// Check if cart is empty
if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
$message = "Your cart is empty.";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Shopping Cart</title>
</head>
<body>
<h2>Your Shopping Cart</h2>
<?php if ($message): ?>
<p><?php echo $message; ?></p>
<?php else: ?>
<table border="1" cellpadding="5" cellspacing="0">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($_SESSION['cart'] as $index => $cartItem): ?>
<tr>
<td><?php echo htmlspecialchars($cartItem['item']); ?></td>
<td><?php echo htmlspecialchars($cartItem['price']); ?>
USD</td>
<td>
<a href="cart.php?remove=<?php echo $index;
?>">Remove</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<p><a href="shopping.php">Go Back to Shopping</a></p>
</body>
</html>
7. Maintaining User State: Create a login system using
sessions. When a user logs in successfully, store their
username in a session and display a personalized welcome
message on subsequent pages until they log out?
CODE:
<!-- login.php -->
<?php
session_start(); // Start a session
// Check if the user is already logged in
if (isset($_SESSION['username'])) {
header("Location: welcome.php"); // Redirect to welcome page
exit();
}
// Handle login form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
// Hardcoded username and password for demonstration
$valid_username = "user";
$valid_password = "password";
// Simple authentication
if ($username === $valid_username && $password ===
$valid_password) {
$_SESSION['username'] = $username; // Store username in
session
header("Location: welcome.php"); // Redirect to welcome page
exit();
} else {
$error_message = "Invalid username or password.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<?php if (isset($error_message)) echo "<p
style='color:red;'>$error_message</p>"; ?>
<form method="POST" action="">
<label for="username">Username:</label>
<input type="text" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
<!-- welcome.php -->
<?php
session_start(); // Start a session
// Check if the user is logged in
if (!isset($_SESSION['username'])) {
header("Location: login.php"); // Redirect to login page if not logged in
exit();
}
// Get the username from the session
$username = $_SESSION['username'];
// Handle logout
if (isset($_GET['logout'])) {
session_destroy(); // Destroy the session
header("Location: login.php"); // Redirect to login page
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome Page</title>
</head>
<body>
<h2>Welcome, <?php echo htmlspecialchars($username); ?>!</h2>
<p>You are logged in.</p>
<!-- Logout link -->
<p><a href="welcome.php?logout=true">Logout</a></p>
</body>
</html>