3.
Server-Side Scripting (PHP)
SOP 1 : Write a PHP program to check if a person is eligible to vote or not. The program
should include the following-
• Minimum age required for vote is 18.
• Use PHP functions.
• Use Decision making statement.
INPUTS: sop1php.html
<!DOCTYPE html>
<html>
<head>
<title>SOP1 PHP </title>
</head>
<body>
<H1> Age Check to Vote ! ! ! </h1>
<form method="post" action="agechk.php">
Enter my age :
<input type="text" name="txt_age" >
<br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Output:
INPUTS: agechk.php
<?php
if (isset($_POST['submit']))
{
$age = $_POST['txt_age'];
if($age>=18)
{
echo "You are Eligible for Vote";
}
else
{
echo "You are not Eligible for Vote";
}
}
?>
Output:
SOP 2 : Write a PHP function to count the total number of vowels (a,e,i,o,u) from the string.
Accept a string by using HTML form.
INPUTS: sop2php.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vowel Counter</title>
</head>
<body>
<h1>Vowel Counter</h1>
<form action="vowel_count.php" method="post">
<label for="inputString">Enter a string:</label>
<textarea id="inputString" name="inputString" rows="4" cols="50"
required></textarea><br><br>
<input type="submit" value="Count Vowels">
</form>
</body>
</html>
Output:
INPUTS: vowel_count.php
<?php
function countVowels($str) {
// Convert string to lowercase to handle both uppercase and
lowercase vowels
$str = strtolower($str);
// Define an array of vowels
$vowels = array('a', 'e', 'i', 'o', 'u');
// Initialize the vowel count
$count = 0;
// Iterate through each character in the string
for ($i = 0; $i < strlen($str); $i++) {
// Check if the character is a vowel
if (in_array($str[$i], $vowels)) {
$count++;
}
}
return $count;
}
// Check if form data is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the input string from the form
$inputString = $_POST['inputString'];
// Ensure the input is not empty
if (!empty($inputString)) {
// Call the function and get the vowel count
$vowelCount = countVowels($inputString)
// Display the result
echo "<h1>Vowel Count Result</h1>";
echo "<p>The total number of vowels in the provided string is:
<strong>$vowelCount</strong></p>";
} else {
echo "<p>Please provide a string to count vowels.</p>";
}
} else {
echo "<p>Invalid request method.</p>";
}
?>
Output:
SOP 3 : Write a PHP program to perform the following operations on an associative array.
• Display elements of an array along with their keys.
• Display the size of an array.
• Delete an element from an array from the given index.
INPUTS: sop3.php
<?php
// Sample associative array
$associativeArray = array(
"first" => "Apple",
"second" => "Banana",
"third" => "Cherry",
"fourth" => "Date",
"fifth" => "Elderberry"
);
// Function to display elements with their keys
function displayArray($array) {
echo "<h2>Array Elements and Their Keys:</h2>";
echo "<ul>";
foreach ($array as $key => $value) {
echo "<li><strong>Key:</strong> $key,
<strong>Value:</strong> $value</li>";
}
echo "</ul>";
}
// Function to display the size of the array
function displayArraySize($array) {
$size = count($array);
echo "<h2>Array Size:</h2>";
echo "<p>The size of the array is: <strong>$size</strong></p>";
}
// Function to delete an element from the array by key
function deleteElementByKey(&$array, $keyToDelete) {
if (array_key_exists($keyToDelete, $array)) {
unset($array[$keyToDelete]);
echo "<h2>Element Deleted:</h2>";
echo "<p>Element with key <strong>$keyToDelete</strong>
has been deleted.</p>";
} else {
echo "<h2>Error:</h2>";
echo "<p>Key <strong>$keyToDelete</strong> does not exist
in the array.</p>";
}
}
// Display the array elements with keys
displayArray($associativeArray);
// Display the size of the array
displayArraySize($associativeArray);
// Define the key to delete
$keyToDelete = 'third'; // Change this value to test different keys
// Delete the element with the specified key
deleteElementByKey($associativeArray, $keyToDelete);
// Display the updated array
displayArray($associativeArray);
// Display the updated size of the array
displayArraySize($associativeArray);
?>
Output:
SOP 4 : Write a PHP program to save marks of English, Hindi, Marathi, Maths and
Information Technology in an array. Display marks of individual subject along with total
marks and percentage.
INPUTS: sop4.php
<?php
// Function to calculate the total marks and percentage
function calculateResults($marksArray) {
$totalMarks = array_sum($marksArray);
$totalSubjects = count($marksArray);
$percentage = ($totalMarks / ($totalSubjects * 100)) * 100; //
Assuming each subject is out of 100 marks
return array(
'totalMarks' => $totalMarks,
'percentage' => $percentage
);
}
// Define marks for each subject
$marksArray = array(
'English' => 85,
'Hindi' => 78,
'Marathi' => 88,
'Maths' => 92,
'Information Technology' => 90
);
// Calculate results
$results = calculateResults($marksArray);
// Display individual subject marks
echo "<h1>Marks Details</h1>";
echo "<ul>";
foreach ($marksArray as $subject => $marks) {
echo "<li><strong>$subject:</strong> $marks</li>";
}
echo "</ul>";
// Display total marks and percentage
echo "<h2>Total Marks and Percentage</h2>";
echo "<p>Total Marks:
<strong>{$results['totalMarks']}</strong></p>";
echo "<p>Percentage: <strong>" .
number_format($results['percentage'], 2) . "%</strong></p>";
?>
Output:
SOP 5 : Write a PHP program to save marks of English, Hindi, Marathi, Maths and
information technology in an array for 5 students and display totals marks and percentage
of each students using ‘foreach’.
INPUTS: sop5.php
<?php
// Define marks for each student
$studentsMarks = array(
'Student1' => array(
'English' => 85,
'Hindi' => 78,
'Marathi' => 88,
'Maths' => 92,
'Information Technology' => 90
),
'Student2' => array(
'English' => 75,
'Hindi' => 82,
'Marathi' => 80,
'Maths' => 85,
'Information Technology' => 88
),
'Student3' => array(
'English' => 90,
'Hindi' => 84,
'Marathi' => 91,
'Maths' => 87,
'Information Technology' => 93
),
'Student4' => array(
'English' => 78,
'Hindi' => 70,
'Marathi' => 75,
'Maths' => 80,
'Information Technology' => 85
),
'Student5' => array(
'English' => 88,
'Hindi' => 76,
'Marathi' => 82,
'Maths' => 90,
'Information Technology' => 89
)
);
// Function to calculate total marks and percentage
function calculateStudentResults($marksArray) {
$totalMarks = array_sum($marksArray);
$totalSubjects = count($marksArray);
$percentage = ($totalMarks / ($totalSubjects * 100)) * 100; //
Assuming each subject is out of 100 marks
return array(
'totalMarks' => $totalMarks,
'percentage' => $percentage
);
}
// Display results for each student
echo "<h1>Student Marks and Results</h1>";
foreach ($studentsMarks as $student => $marks) {
// Calculate results for the current student
$results = calculateStudentResults($marks);
// Display individual subject marks
echo "<h2>$student</h2>";
echo "<ul>";
foreach ($marks as $subject => $mark) {
echo "<li><strong>$subject:</strong> $mark</li>";
}
echo "</ul>";
// Display total marks and percentage
echo "<p>Total Marks:
<strong>{$results['totalMarks']}</strong></p>";
echo "<p>Percentage: <strong>" .
number_format($results['percentage'], 2) . "%</strong></p>";
echo "<hr>";
}
?>
Output:
SOP 6 : Write a program using PHP to calculate Electricity bill by accepting the limits.
• For first 100 units - Rs. 4
• For next 100 units - Rs. 5
• For next all units - Rs. 6
INPUTS: sop6php.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Electricity Bill Calculator</title>
</head>
<body>
<h1>Electricity Bill Calculator</h1>
<form action="calculate_bill.php" method="post">
<label for="units">Enter number of units consumed:</label>
<input type="number" id="units" name="units" min="0"
required>
<input type="submit" value="Calculate Bill">
</form>
</body>
</html>
Output:
INPUTS: calculate_bill.php
<?php
// Function to calculate electricity bill
function calculateElectricityBill($units) {
$bill = 0;
// Calculate bill based on the units
if ($units <= 100) {
$bill = $units * 4;
} elseif ($units <= 200) {
$bill = (100 * 4) + (($units - 100) * 5);
} else {
$bill = (100 * 4) + (100 * 5) + (($units - 200) * 6);
}
return $bill;
}
// Check if form data is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the number of units from the form input
$units = isset($_POST['units']) ? (int)$_POST['units'] : 0;
// Ensure the number of units is a positive number
if ($units >= 0) {
// Calculate the electricity bill
$totalBill = calculateElectricityBill($units);
// Display the result
echo "<h1>Electricity Bill Calculation</h1>";
echo "<p>Number of Units: <strong>$units</strong></p>";
echo "<p>Total Bill: <strong>Rs. $totalBill</strong></p>";
} else {
echo "<p>Please enter a valid number of units.</p>";
}
} else {
echo "<p>Invalid request method.</p>";
}
?>
Output:
SOP 7 : Write a PHP Program to insert a roll number and student name in a database (use
postgresql data to create database). Accept roll number and name from the user.
INPUTS: sop7php.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Student Data Insertion</title>
</head>
<body>
<h1>Insert Student Data</h1>
<form action="insert_student.php" method="post">
<label for="roll_number">Roll Number:</label>
<input type="text" id="roll_number" name="roll_number"
required><br><br>
<label for="name">Student Name:</label>
<input type="text" id="name" name="name"
required><br><br>
<input type="submit" value="Insert">
</form>
</body>
</html>
Output:
INPUTS: insert_student.php
<?php
// Database connection parameters
$host = 'localhost'; // or your database host
$port = '5432'; // default PostgreSQL port
$dbname = 'studentdb';
$user = 'your_db_user'; // replace with your PostgreSQL username
$password = 'your_db_password'; // replace with your PostgreSQL
password
// Create a connection string
$conn_string = "host=$host port=$port dbname=$dbname
user=$user password=$password";
// Establish a connection to the PostgreSQL database
$conn = pg_connect($conn_string);
if (!$conn) {
die("Error: Unable to connect to the database.");
}
// Function to insert student data into the database
function insertStudent($rollNumber, $name, $conn) {
$query = "INSERT INTO students (roll_number, name) VALUES
($1, $2)";
$result = pg_query_params($conn, $query, array($rollNumber,
$name));
if ($result) {
return "Student data inserted successfully.";
} else {
return "Error: " . pg_last_error($conn);
}
}
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve and sanitize input data
$rollNumber = isset($_POST['roll_number']) ?
trim($_POST['roll_number']) : '';
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
// Validate input
if (!empty($rollNumber) && !empty($name)) {
// Insert student data into the database
$message = insertStudent($rollNumber, $name, $conn);
} else {
$message = "Both roll number and name are required.";
}
// Close the database connection
pg_close($conn);
} else {
$message = "Invalid request method.";
}
// Display the message
echo "<h1>Insert Student Data</h1>";
echo "<p>$message</p>";
?>