PHP Basics: Scripts and Authentication
PHP Basics: Scripts and Authentication
"
to the Browser
Objective:
To create a basic PHP script that outputs the message "Hello, World!" in a web browser.
This experiment serves as an introduction to PHP and basic server-side scripting.
Materials:
Procedure:
<?php
echo "Hello, World!";
?>
c. Save the file with a .php extension. For this experiment, name the file
[Link].
3. Save the File to the Web Server Directory:
a. Locate the root directory of your web server:
i. For XAMPP, this is typically C:\xampp\htdocs\.
ii. For WAMP, this is usually C:\wamp64\www\.
iii. For MAMP, this is generally Applications/MAMP/htdocs/.
b. Save the [Link] file in this directory.
4. Run the PHP Script:
a. Open your web browser.
b. Navigate to [Link]
5. Observe the Output:
a. The browser should display the text: Hello, World!
Expected Output:
When the steps are followed correctly, the web browser will display the message
"Hello, World!" indicating that the PHP script has been executed successfully on the
server side and the result has been sent to the browser.
Experiment 2: Build a Basic Web-Based Calculator
Objective:
Materials:
Procedure:
<html>
<head>
<title>Basic Calculator</title>
</head>
<body>
<form method="POST" action="[Link]">
Enter First Number: <input type="number" name="num1"
required><br>
Enter Second Number: <input type="number" name="num2"
required><br>
Select Operation:
<select name="operation">
<option value="add">Add</option>
<option value="sub">Subtract</option>
<option value="mul">Multiply</option>
<option value="div">Divide</option>
</select><br>
<button type="submit">Calculate</button>
</form>
</body>
</html>
c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
3. Create the PHP Script:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to process the form data and perform
calculations:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operation = $_POST['operation'];
switch ($operation) {
case "add":
$result = $num1 + $num2;
break;
case "sub":
$result = $num1 - $num2;
break;
case "mul":
$result = $num1 * $num2;
break;
case "div":
if ($num2 != 0) {
$result = $num1 / $num2;
} else {
echo "Cannot divide by zero!";
exit;
}
break;
default:
echo "Invalid operation selected.";
exit;
}
Expected Output:
When the steps are followed correctly, the web-based calculator will display the result
of the arithmetic operation selected by the user.
Experiment 3: Create a User Authentication System
Objective:
To build a secure user authentication system that allows users to log in and log out. This
experiment will involve creating a login form, validating user credentials, and
maintaining a logged-in state using sessions.
Materials:
Procedure:
sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
sql
INSERT INTO users (username, password) VALUES ('admin',
PASSWORD('12345'));
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="POST" action="[Link]">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password"
required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
5. Create the Login Script:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle login requests:
<?php
session_start();
$conn = new mysqli('localhost', 'root', '', 'auth_system');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
if ($result->num_rows > 0) {
$user = $result->fetch_assoc();
if (password_verify($password, $user['password'])) {
$_SESSION['username'] = $username;
header("Location: [Link]");
} else {
echo "Invalid password.";
}
} else {
echo "No user found with that username.";
}
}
$conn->close();
?>
php
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: [Link]");
exit();
}
?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<a href="[Link]">Logout</a>
</body>
</html>
php
<?php
session_start();
session_unset();
session_destroy();
header("Location: [Link]");
exit();
?>
Expected Output:
When the steps are followed correctly, the user authentication system will allow users
to log in and log out securely. Upon successful login, users will be redirected to a
welcome page, and upon logging out, they will be redirected back to the login page.
Experiment 4: Build a To-Do List Application
Objective:
To create a web-based to-do list application that allows users to add, edit, and delete
tasks. This experiment will involve creating a user interface for task management and
implementing server-side logic to handle these operations.
Materials:
Procedure:
sql
CREATE TABLE tasks (
id INT AUTO_INCREMENT PRIMARY KEY,
task VARCHAR(255) NOT NULL,
status VARCHAR(10) NOT NULL DEFAULT 'pending'
);
html
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form method="POST" action="add_task.php">
<input type="text" name="task" required placeholder="New
Task">
<button type="submit">Add Task</button>
</form>
<ul id="taskList">
<?php
$conn = new mysqli('localhost', 'root', '', 'todo_app');
$result = $conn->query("SELECT * FROM tasks");
while ($row = $result->fetch_assoc()) {
echo "<li>{$row['task']} <a
href='edit_task.php?id={$row['id']}'>Edit</a> <a
href='delete_task.php?id={$row['id']}'>Delete</a></li>";
}
$conn->close();
?>
</ul>
</body>
</html>
c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
4. Create the PHP Script for Adding Tasks:
a. Open your text editor and create a new file named add_task.php.
b. Add the following PHP code to handle adding tasks:
php
<?php
$task = $_POST['task'];
$conn = new mysqli('localhost', 'root', '', 'todo_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
php
<?php
$id = $_GET['id'];
$conn = new mysqli('localhost', 'root', '', 'todo_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$task = $_POST['task'];
$sql = "UPDATE tasks SET task='$task' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
header("Location: [Link]");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
$result = $conn->query("SELECT * FROM tasks WHERE id=$id");
$row = $result->fetch_assoc();
echo "<form method='POST'>
<input type='text' name='task' value='{$row['task']}'
required>
<button type='submit'>Update Task</button>
</form>";
}
$conn->close();
?>
php
<?php
$id = $_GET['id'];
$conn = new mysqli('localhost', 'root', '', 'todo_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Expected Output:
When the steps are followed correctly, the to-do list application will allow users to add,
edit, and delete tasks. The tasks will be displayed in a list format with options to edit or
delete each task.
Experiment 5: Design a Contact Form that Sends User Messages via
Email
Objective:
To create a contact form that allows users to send messages via email when submitted.
This experiment involves designing the form, implementing server-side validation to
ensure data integrity, and sending the email using PHP.
Materials:
Procedure:
html
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="POST" action="send_email.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="message">Message:</label>
<textarea id="message" name="message"
required></textarea><br>
<button type="submit">Send</button>
</form>
</body>
</html>
c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
3. Create the PHP Script for Handling Form Submission:
a. Open your text editor and create a new file named send_email.php.
b. Add the following PHP code to handle the form submission and send the
email:
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate input fields
$name = filter_input(INPUT_POST, 'name',
FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email',
FILTER_VALIDATE_EMAIL);
$message = filter_input(INPUT_POST, 'message',
FILTER_SANITIZE_STRING);
Expected Output:
When the steps are followed correctly, the contact form will validate the input fields
and send the user's message via email. The user will receive feedback on whether the
message was sent successfully or if there were any errors.
Experiment 6: Build an Online Quiz System with Multiple-Choice
Questions
Objective:
To create an online quiz system that presents multiple-choice questions, collects user
responses, and keeps track of the user's score. This experiment involves creating an
interactive web interface, storing questions and user responses, and calculating the
final score.
Materials:
Procedure:
sql
CREATE TABLE questions (
id INT AUTO_INCREMENT PRIMARY KEY,
question TEXT NOT NULL,
option1 VARCHAR(255) NOT NULL,
option2 VARCHAR(255) NOT NULL,
option3 VARCHAR(255) NOT NULL,
option4 VARCHAR(255) NOT NULL,
correct_option INT NOT NULL
);
<?php
$conn = new mysqli('localhost', 'root', '', 'quiz_app');
if ($conn->connect_error) {
<html>
<head>
<title>Online Quiz</title>
</head>
<body>
<h1>Online Quiz</h1>
<form method="POST" action="[Link]">
<?php while ($row = $result->fetch_assoc()) { ?>
<p><?php echo $row['question']; ?></p>
<input type="radio" name="question<?php echo
$row['id']; ?>" value="1"> <?php echo $row['option1']; ?><br>
<input type="radio" name="question<?php echo
$row['id']; ?>" value="2"> <?php echo $row['option2']; ?><br>
<input type="radio" name="question<?php echo
$row['id']; ?>" value="3"> <?php echo $row['option3']; ?><br>
<input type="radio" name="question<?php echo
$row['id']; ?>" value="4"> <?php echo $row['option4']; ?><br>
<?php } ?>
<button type="submit">Submit</button>
</form>
</body>
</html>
<?php
$conn->close();
?>
c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
5. Create the PHP Script to Process Quiz Results:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to process the user responses and calculate
the score:
<?php
$conn = new mysqli('localhost', 'root', '', 'quiz_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$score = 0;
$result = $conn->query("SELECT * FROM questions");
if ($selected_option == $row['correct_option']) {
$score++;
}
}
$conn->close();
?>
Expected Output:
When the steps are followed correctly, the online quiz system will display multiple-
choice questions, collect user responses, and calculate the final score based on the
user's answers.
Experiment 7: Develop a User Registration Form that Collects User
Data, Validates It, and Stores It in a Database
Objective:
To create a user registration form that collects user data, validates the input, and stores
the data in a database. This experiment covers designing the form, implementing
server-side validation to ensure data integrity, and inserting the validated data into a
database.
Materials:
Procedure:
sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE
);
html
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>Register</h1>
<form method="POST" action="[Link]">
<label for="username">Username:</label>
<input type="text" id="username" name="username"
required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"
required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<button type="submit">Register</button>
</form>
</body>
</html>
c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
4. Create the PHP Script for Handling Form Submission:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle the form submission, validate the
input, and store the data in the database:
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = filter_input(INPUT_POST, 'username',
FILTER_SANITIZE_STRING);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = filter_input(INPUT_POST, 'email',
FILTER_VALIDATE_EMAIL);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
} else {
echo "Invalid input. Please check your form fields.";
}
} else {
echo "Invalid request method.";
}
?>
Expected Output:
When the steps are followed correctly, the user registration form will validate the input
fields and store the user's data in the database. The user will receive feedback on
whether the registration was successful or if there were any errors.
Explanation:
HTML Form: The form collects user input (username, password, and email) and
sends it to the PHP script for processing.
PHP Script: The script validates the form data, sanitizes the input to prevent
security issues, hashes the password for secure storage, and inserts the data
into the database.
Server-Side Validation: Ensures that the input fields contain valid data before
storing it in the database.
This experiment demonstrates how to create a user registration form with server-side
validation and data storage using HTML, PHP, and MySQL, providing a foundational
understanding of web form processing, data validation, and secure data handling.
Experiment 8: Create a Website to Perform CRUD Operations on a
Database
Objective:
To develop a web application that allows users to perform Create, Read, Update, and
Delete (CRUD) operations on a database. This experiment includes designing the user
interface, implementing server-side logic to handle these operations, and interacting
with a database.
Materials:
Procedure:
sql
CREATE TABLE items (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
html
<html>
<head>
<title>CRUD Application</title>
</head>
<body>
<h1>CRUD Application</h1>
<form method="POST" action="[Link]">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="description">Description:</label>
<textarea id="description" name="description"
required></textarea><br>
<button type="submit">Create</button>
</form>
<h2>Items</h2>
<ul>
<?php
$conn = new mysqli('localhost', 'root', '', 'crud_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
</ul>
</body>
</html>
c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
4. Create the PHP Script for Creating Items:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle creating items:
php
<?php
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$description = filter_input(INPUT_POST, 'description',
FILTER_SANITIZE_STRING);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
} else {
echo "Invalid input.";
}
?>
php
<?php
$conn = new mysqli('localhost', 'root', '', 'crud_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$name = filter_input(INPUT_POST, 'name',
FILTER_SANITIZE_STRING);
$description = filter_input(INPUT_POST, 'description',
FILTER_SANITIZE_STRING);
$conn->close();
?>
php
<?php
$id = $_GET['id'];
$conn = new mysqli('localhost', 'root', '', 'crud_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Expected Output:
When the steps are followed correctly, the CRUD application will allow users to create,
read, update, and delete items in the database. The user will be able to manage items
through a web interface.
Experiment 9: Develop a Simple E-Commerce Shopping Cart
Objective:
To create a simple e-commerce shopping cart that allows users to add and remove
products, calculate the total price, and proceed to checkout. This experiment involves
designing the user interface, implementing server-side logic to handle cart operations,
and managing data using a database.
Materials:
Procedure:
sql
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description TEXT NOT NULL
);
sql
INSERT INTO products (name, price, description) VALUES
('Product 1', 10.00, 'Description for product 1'),
('Product 2', 20.00, 'Description for product 2'),
('Product 3', 30.00, 'Description for product 3');
php
<?php
session_start();
$conn = new mysqli('localhost', 'root', '', 'ecommerce');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_id = $_POST['product_id'];
if (isset($_POST['add_to_cart'])) {
if (!in_array($product_id, $_SESSION['cart'])) {
$_SESSION['cart'][] = $product_id;
}
} elseif (isset($_POST['remove_from_cart'])) {
if (($key = array_search($product_id,
$_SESSION['cart'])) !== false) {
unset($_SESSION['cart'][$key]);
}
}
}
<html>
<head>
<title>E-Commerce Shopping Cart</title>
</head>
<body>
<h1>Products</h1>
<ul>
<?php while ($row = $result->fetch_assoc()) { ?>
<li>
<?php echo $row['name']; ?> - $<?php echo
$row['price']; ?><br>
<?php echo $row['description']; ?><br>
<form method="POST" action="">
<input type="hidden" name="product_id"
value="<?php echo $row['id']; ?>">
<?php if (in_array($row['id'],
$_SESSION['cart'])) { ?>
<button type="submit"
name="remove_from_cart">Remove from Cart</button>
<?php } else { ?>
<button type="submit" name="add_to_cart">Add
to Cart</button>
<?php } ?>
</form>
</li>
<?php } ?>
</ul>
<h2>Shopping Cart</h2>
<ul>
<?php
$total_price = 0;
if (!empty($_SESSION['cart'])) {
$cart_ids = implode(',', $_SESSION['cart']);
$cart_result = $conn->query("SELECT * FROM products
WHERE id IN ($cart_ids)");
while ($cart_row = $cart_result->fetch_assoc()) {
echo "<li>{$cart_row['name']} -
${cart_row['price']}</li>";
$total_price += $cart_row['price'];
}
} else {
echo "<li>Your cart is empty.</li>";
}
?>
</ul>
<p>Total Price: $<?php echo $total_price; ?></p>
<form method="POST" action="[Link]">
<button type="submit" name="checkout">Proceed to
Checkout</button>
</form>
</body>
</html>
<?php
$conn->close();
?>
php
<?php
session_start();
When the steps are followed correctly, the e-commerce shopping cart will allow users
to add and remove products, calculate the total price, and proceed to checkout. The
user will receive feedback on the cart operations and the checkout process.
Experiment 10: Develop a Simple E-Commerce Shopping Cart
Objective:
To create a simple e-commerce shopping cart that allows users to add and remove
products, calculate the total price, and proceed to checkout. This experiment involves
designing the user interface, implementing server-side logic to handle cart operations,
and managing data using a database.
Materials:
Procedure:
sql
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description TEXT NOT NULL
);
sql
INSERT INTO products (name, price, description) VALUES
('Product 1', 10.00, 'Description for product 1'),
('Product 2', 20.00, 'Description for product 2'),
('Product 3', 30.00, 'Description for product 3');
php
<?php
session_start();
$conn = new mysqli('localhost', 'root', '', 'ecommerce');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_id = $_POST['product_id'];
if (isset($_POST['add_to_cart'])) {
if (!in_array($product_id, $_SESSION['cart'])) {
$_SESSION['cart'][] = $product_id;
}
} elseif (isset($_POST['remove_from_cart'])) {
if (($key = array_search($product_id,
$_SESSION['cart'])) !== false) {
unset($_SESSION['cart'][$key]);
}
}
}
<html>
<head>
<title>E-Commerce Shopping Cart</title>
</head>
<body>
<h1>Products</h1>
<ul>
<?php while ($row = $result->fetch_assoc()) { ?>
<li>
<?php echo $row['name']; ?> - $<?php echo
$row['price']; ?><br>
<?php echo $row['description']; ?><br>
<form method="POST" action="">
<input type="hidden" name="product_id"
value="<?php echo $row['id']; ?>">
<?php if (in_array($row['id'],
$_SESSION['cart'])) { ?>
<button type="submit"
name="remove_from_cart">Remove from Cart</button>
<?php } else { ?>
<button type="submit" name="add_to_cart">Add
to Cart</button>
<?php } ?>
</form>
</li>
<?php } ?>
</ul>
<h2>Shopping Cart</h2>
<ul>
<?php
$total_price = 0;
if (!empty($_SESSION['cart'])) {
$cart_ids = implode(',', $_SESSION['cart']);
$cart_result = $conn->query("SELECT * FROM products
WHERE id IN ($cart_ids)");
while ($cart_row = $cart_result->fetch_assoc()) {
echo "<li>{$cart_row['name']} -
${cart_row['price']}</li>";
$total_price += $cart_row['price'];
}
} else {
echo "<li>Your cart is empty.</li>";
}
?>
</ul>
<p>Total Price: $<?php echo $total_price; ?></p>
<form method="POST" action="[Link]">
<button type="submit" name="checkout">Proceed to
Checkout</button>
</form>
</body>
</html>
<?php
$conn->close();
?>
php
<?php
session_start();
When the steps are followed correctly, the e-commerce shopping cart will allow users
to add and remove products, calculate the total price, and proceed to checkout. The
user will receive feedback on the cart operations and the checkout process.