HINDUSTHAN POLYTECHNIC COLLEGE
COIMBATORE – 641 032
LABORATORY RECORD
NAME
[Link]
CLASS
YEAR / SEMESTER YEAR : SEMESTER :
Certified that this is the bonafide record of work done by the above student for
the_______________________________________________________________Laboratory
during the year 2025 -2026
INTERNAL MARK
Staff in-Charge Head of the Department
Submitted for the Practical Examination Held on ______________________________
Internal Examiner External Examiner
Index
[Link]
PHP program using five string and array functions
Aim:
To Write PHP code to implement any five strings and array functions
Program:
<?php
// 1. String function: strlen() - Get length of a string
$str = "Hello World";
echo "Length of string: " . strlen($str) . "<br>";
// 2. String function: strtoupper() - Convert to uppercase
echo "Uppercase: " . strtoupper($str) . "<br>";
// 3. String function: str_replace() - Replace text within a string
echo "Replace 'World' with 'PHP': " . str_replace("World", "PHP", $str) . "<br>";
// 4. Array function: array_push() - Add elements to an array
$fruits = ["Apple", "Banana"];
array_push($fruits, "Orange", "Mango");
echo "Fruits after push: ";
print_r($fruits);
echo "<br>";
// 5. Array function: array_merge() - Merge two arrays
$vegetables = ["Carrot", "Potato"];
$merged = array_merge($fruits, $vegetables);
echo "Merged array: ";
print_r($merged);
echo "<br>";
?>
Sample output
Length of string: 11
Uppercase: HELLO WORLD
Replace 'World' with 'PHP': Hello PHP
Fruits after push: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango
)
Merged array: Array ( [0] => Apple [1] => Banana [2] => Orange [3] =>
Mango [4] => Carrot [5] => Potato )
Result:
The PHP program executed successfully and displayed correct outputs for all five string
and array functions.
[Link] HTML form with PHP to collect student biodata and SSLC
marks, calculate total and average
Aim:
To Design the HTML form to collect student biodata and SSLC Mark, Process the collected
data in the PHP and Find Total and Average for Mark
Program:
html
<!DOCTYPE html>
<html>
<head>
<title>Student Marks</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="[Link]" method="post">
Name: <input type="text" name="name"><br><br>
Roll Number: <input type="text" name="roll"><br><br>
Kannada: <input type="number" name="kannada"><br>
English: <input type="number" name="english"><br>
Maths: <input type="number" name="maths"><br>
Science: <input type="number" name="science"><br>
Social Science: <input type="number" name="social"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Php script
<?php
$name = $_POST['name'];
$roll = $_POST['roll'];
$kannada= $_POST['kannada'];
$english= $_POST['english'];
$maths = $_POST['maths'];
$science= $_POST['science'];
$social = $_POST['social'];
$total = $kannada + $english + $maths + $science + $social;
$average = $total / 5;
echo "Name: $name <br>";
echo "Roll Number: $roll <br>";
echo "Total Marks: $total <br>";
echo "Average Marks: $average <br>";
?>
Sample output
Name: Ramesh
Roll Number: 101
Total Marks: 400
Average Marks: 80
Result:
The HTML form collected student details and marks. The PHP script processed the
data and correctly calculated and displayed the total and average marks.
[Link] PHP application to display student result by register number from
database
Aim:
To Develop the simple application which display result of the student by getting
register number as user input
Program
Create database
CREATE DATABASE school;
Use the database
USE school;
Create table to store student results
CREATE TABLE students (register_number INT PRIMARY KEY, name VARCHAR(255),
maths INT, science INT,english INT);
Insert sample student records
INSERT INTO students (register_number, name, maths, science, english) VALUES
(101, 'Anu', 85, 90, 78),
(102, 'Ajay', 90, 85, 92),
(103, 'Janani', 78, 92, 85);
PHP Application
<?php
// Connect to database
$conn = mysqli_connect("localhost", "root", "", "college");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$reg_no = $_POST["register_number"];
// Simple query
$sql = "SELECT * FROM students WHERE register_number = $reg_no";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
$total = $row["maths"] + $row["science"] + $row["english"];
$average = $total / 3;
echo "Register Number: " . $row["register_number"] . "<br>";
echo "Name: " . $row["name"] . "<br>";
echo "Maths: " . $row["maths"] . "<br>";
echo "Science: " . $row["science"] . "<br>";
echo "English: " . $row["english"] . "<br><br>";
echo "Total Marks: $total <br>";
echo "Average Marks: $average <br>";
} else {
echo "No record found!";
}
}
?>
<!-- Simple Form -->
<form method="post">
Register Number: <input type="text" name="register_number" required>
<input type="submit" value="Get Result">
</form>
Sample output
Register Number: 102
Register Number: 102
Name: Ajay
Maths: 90
Science: 85
English: 92
Total Marks: 267
Average Marks: 89
Result
The application connected to the database, retrieved the student’s marks using the
register number, and displayed the result. For invalid input, “No results found” was shown.
[Link] PHP login page validating username and password,
redirecting to [Link] on success
Aim:
To Develop the simple login page, which validates the username, and password
(assume
username, password and student_name are stored in the database). If username and password
are correct, the page should redirect to [Link]file and display the student_name in that
page. If username or password is incorrect page should remain in login page itself.
Program:
CREATE DATABASE student_database;
USE student_database;
CREATE TABLE students (
username VARCHAR(255) PRIMARY KEY,
password VARCHAR(255),
student_name VARCHAR(255)
);
INSERT INTO students VALUES
('john', 'password123', 'John Doe'),
('jane', 'password456', 'Jane Doe'),
('bob', 'password789', 'Bob Smith');
Login page
[Link]
<?php
$conn = mysqli_connect("localhost", "root", "", "student_database");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
$sql = "SELECT * FROM students WHERE username='$username' AND
password='$password'";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
$student_name = $row["student_name"];
header("Location: [Link]?student_name=$student_name");
exit;
} else {
echo "Invalid username or password.";
}
}
?>
<form method="post">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
[Link]
<?php
$student_name = $_GET["student_name"];
echo "Welcome, $student_name!";
?>
Sample output
Input (form submission on [Link]):
Username: john
Password: password123
Redirected Output (on [Link]):
Welcome, John Doe!
Result
The login page validated username and password against the database. On success, it
redirected to [Link] and displayed the student’s name. On failure, it remained on the
login page with an error message.
[Link]
jQuery code to disable right-click on webpage
Aim:
To write the code to disable right-click option in the webpage using the jQuery
Program:
<!DOCTYPE html>
<html>
<head>
<title>Disable Right Click</title>
<!-- jQuery CDN -->
<script src="[Link]
<script>
$(document).ready(function(){
// Disable right-click
$(document).on("contextmenu", function(e){
[Link]();
alert("Right-click is disabled on this page!");
});
});
</script>
</head>
<body>
<h2>Right-click Disabled Example</h2>
<p>Try right-clicking anywhere on this page.</p>
</body>
</html>
Sample output
[Alert Box]
Right-click is disabled on this page!
Result
Right-click was disabled on the webpage. The context menu did not appear when the
user attempted to right-click.
[Link] AJAX application to display college details by code without
reloading the page
Aim
To Develop the simple application which display details of the collegeby getting college
code as input using AJAX without reloading the page (assume college details like code, name,
courses_offered, address, hostel facility,etc., are already available in the database)
Procedure
Step 1: Set up your MySQL Database
CREATE DATABASE college_db;
USE college_db;
CREATE TABLE colleges (code VARCHAR(10) PRIMARY KEY, name VARCHAR(255),
courses_offered VARCHAR(255),address VARCHAR(255), hostel_facility
VARCHAR(50));
Step 2: Insert Some Sample Data
INSERT INTO colleges VALUES
('C101', 'Hindusthan Polytechnic College', 'CSE, ECE, MECH', 'Coimbatore, TN',
'Available'),
('C102', 'PSG Polytechnic College', 'EEE, CIVIL, IT', 'Coimbatore, TN', 'Available'),
('C103', 'CKPC', 'Diploma in Mechanical, Diploma in Computer', 'Erode, TN', 'Not
Available');
Step 3:
php
<?php
$conn = mysqli_connect("localhost", "root", "", "college_db");
$code = $_POST['college_code'];
$sql = "SELECT * FROM colleges WHERE code='$code'";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
echo "Code: " . $row['code'] . "<br>";
echo "Name: " . $row['name'] . "<br>";
echo "Courses: " . $row['courses_offered'] . "<br>";
echo "Address: " . $row['address'] . "<br>";
echo "Hostel: " . $row['hostel_facility'];
} else {
echo "No details found!";
}
?>
html
<!DOCTYPE html>
<html>
<head>
<title>College Details</title>
<script src="[Link]
<script>
function getDetails() {
var code = $("#code").val();
$.post("[Link]", {college_code: code}, function(data){
$("#result").html(data);
});
}
</script>
</head>
<body>
<h2>Enter College Code:</h2>
<input type="text" id="code">
<button onclick="getDetails()">Get Details</button>
<div id="result"></div>
</body>
</html>
Step 5: Test the Application
1. Ensure your web server is running and PHP is configured correctly.
2. Place [Link] and get_college_details.php in your web server's document root (e.g.,
htdocs).
3. Make sure the MySQL database (college_db) is running, and the colleges table is
populated with sample data.
4. Open the [Link] file in a browser, enter a valid college code, and click "Get
Details" to see the results.
Sample output
Input (entered in the form):
Code
C101
Output (displayed in the browser):
Code
Code: C101
Name: Hindusthan Polytechnic College
Courses: CSE, ECE, MECH
Address: Coimbatore, TN
Hostel: Available
Result:
The application fetched and displayed college details (code, name, courses, address,
hostel facility) dynamically using AJAX without reloading the page. For invalid codes, “No
details found” was displayed.
[Link]
[Link] application to upload a file to server
Aim:
To upload a file to the server using [Link], you can use the express framework along with
the multer middleware, which is designed to handle multipart/form-data, commonly used for
file uploads.
Procedure
Steps:
1. Set up your [Link] environment:
o Install [Link] (if not installed).
o Create a project directory and initialize it with npm init.
2. Install required dependencies:
o Express: A web framework for [Link].
o Multer: A middleware for handling multipart/form-data.
Run the following command in your project directory:
npm install express multer
Step 1: Create the [Link] server with file upload functionality.
Here’s a complete [Link] script using Express and Multer for uploading files to the server.
// Import required modules
const express = require('express');
const multer = require('multer');
const path = require('path');
// Initialize the express app
const app = express();
// Set up storage configuration for multer
const storage = [Link]({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // Directory to save uploaded files
},
filename: (req, file, cb) => {
// Generate a unique filename with the file's original extension
cb(null, [Link]() + [Link]([Link]));
}
});
// Initialize multer with the storage configuration
const upload = multer({ storage: storage });
// Create an 'uploads' directory (if it doesn't exist)
const fs = require('fs');
const uploadDir = './uploads';
if () {
[Link](uploadDir);
}
// Create an endpoint to handle file upload
[Link]('/upload', [Link]('file'), (req, res) => {
if (![Link]) {
return [Link](400).send('No file uploaded.');
}
[Link]({
message: 'File uploaded successfully!',
file: [Link]
});
});
// Serve a simple HTML form for file upload
[Link]('/', (req, res) => {
[Link](`
<html>
<body>
<h1>Upload a File</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
`);
});
// Set the server to listen on port 3000
[Link](3000, () => {
[Link]('Server is running on [Link]
});
Step 2: Test the Application
1. Run the server:
o In your terminal, run the following command:
bash
Copy
node [Link]
Replace [Link] with the filename of your script if it's different.
2. Access the form:
o Open a browser and navigate to [Link]
o You should see an HTML form allowing you to select and upload a file.
3. Upload a file:
o Choose a file and click the "Upload" button.
o After successful upload, the server will respond with a message and details
about the uploaded file (including its path).
Step 3: Handling Errors
To improve the app and handle potential errors (e.g., file size limits, incorrect file types), you
can add additional configurations in the multer middleware.
Example of limiting file size to 10MB:
const upload = multer({
storage: storage,
limits: { fileSize: 10 * 1024 * 1024 } // 10MB
});
Sample output
✅ Step 1: Run the Server
In your project directory:
bash
node [Link]
Output in terminal:
Code
Server is running on [Link]
✅ Step 2: Access the Upload Form
Open a browser and go to:
Code
[Link]
You’ll see a simple HTML form:
Code
Upload a File
[Choose File]
[Upload]
✅ Step 3: Upload a File
Suppose you select a file named [Link] and click Upload.
Server Response (JSON):
json
{
"message": "File uploaded successfully!",
"file": {
"fieldname": "file",
"originalname": "[Link]",
"encoding": "7bit",
"mimetype": "text/plain",
"destination": "uploads/",
"filename": "[Link]",
"path": "uploads/[Link]",
"size": 1234
}
}
The file is saved in the uploads/ directory with a unique timestamp-based filename.
The JSON response confirms the upload and shows metadata (original name, type, size,
path).
✅ Step 4: Error Handling Example
If you try uploading a file larger than 10MB (with the limits option enabled):
js
const upload = multer({
storage: storage,
limits: { fileSize: 10 * 1024 * 1024 } // 10MB
});
Response:
Code
Error: File too large
If you submit the form without selecting a file:
Code
No file uploaded.
Result:
The [Link] application successfully uploaded files to the server and stored them in
the designated folder. A confirmation message was displayed after upload.
[Link]
[Link] application to send an email
Aim
To develop a simple [Link] code to send an email, we can use the nodemailer package.
Below is a basic example demonstrating how to send an email using a Gmail account.
Procedure
Steps to Set Up the [Link] Email Sending:
1. Set up your [Link] environment:
o Initialize a new [Link] project by running:
npm init –y
2. Install nodemailer: Run the following command to install the nodemailer package:
npm install nodemailer
3. Here’s the code to send an email using Gmail as the service. Ensure you use a valid
Gmail account and password.
1. Create a new file ([Link])
// Import the nodemailer module
const nodemailer = require('nodemailer');
// Create a transporter object using default SMTP transport (Gmail)
const transporter = [Link]({
service: 'gmail', // Gmail service
auth: {
user: 'your-email@[Link]', // Your Gmail email address
pass: 'your-email-password' // Your Gmail password or app password
}
});
// Set up email data
const mailOptions = {
from: 'your-email@[Link]', // Sender email address
to: 'recipient-email@[Link]', // Recipient email address
subject: 'Test Email from [Link]', // Email subject
text: 'Hello, this is a test email sent using [Link] and Nodemailer!' // Email body
text
};
// Send the email
[Link](mailOptions, (error, info) => {
if (error) {
[Link]('Error:', error);
} else {
[Link]('Email sent successfully: ' + [Link]);
}
});
Step 2: Test the Email Sending
1. Run the server:
o In your terminal, run the following command:
node [Link]
This will trigger the email sending process.
2. Check your email inbox:
You should receive the email in the recipient's inbox.
Sample output
Step 1: Initialize and Install
bash
npm init -y
npm install nodemailer
This sets up your [Link] project and installs Nodemailer.
Step 2: Run the Script
bash
node [Link]
✅ Expected Output in Terminal
If everything is configured correctly (valid Gmail + password/app password):
Code
Email sent successfully: 250 2.0.0 OK 1671881234 abcsm567890q.12 - gsmtp
Expected Result in Recipient’s Inbox
From: your-email@[Link]
To: recipient-email@[Link]
Subject: Test Email from [Link]
Body:
Code
Hello, this is a test email sent using [Link] and Nodemailer!
Result
The [Link] application connected to the mail server and successfully sent an email. A
success message was displayed after sending.