Php
WEB DEVELOPMENT PHP LAB
1. Write the process of installation of web server.
Installing a web server with PHP typically involves a few steps. Here's a
general guide for installing a common web server, Apache, with PHP. Please note
that specific steps may vary based on your operating system. This guide assumes
you are using a Linux distribution, but similar steps can be applied to other
operating systems.
Installing Apache and PHP on Linux:
Update Package Lists:
bash
Copy code
sudo apt update
Install Apache:
bash
Copy code
sudo apt install apache2
Install PHP and Mod for Apache:
bash
Copy code
sudo apt install php libapache2-mod-php
Restart Apache:
bash
Copy code
sudo systemctl restart apache2
Test PHP:
Create a PHP info file to test if PHP is working:
bash
Copy code
echo "<?php phpinfo(); ?>" | sudo tee
/var/www/html/info.php
Open a web browser and navigate to http://localhost/info.php
or http://your_server_ip/info.php.
If PHP is working, you'll see the PHP information page.
Additional Steps (Optional):
Install MySQL:
If your application requires a database, you might want to install MySQL or
another database server.
bash
Copy code
sudo apt install mysql-server
Install phpMyAdmin (Optional):
To manage your MySQL databases via a web interface:
bash
Copy code
sudo apt install phpmyadmin
Follow the setup process, and then access phpMyAdmin at http://localhost/phpmyadmin or http://your_server_ip/phpmyadmin.
Installing on Windows or macOS:
Windows:
You can use software packages like XAMPP or WampServer that bundle Apache,
PHP, MySQL, and phpMyAdmin into a single installer.
macOS:
You can use MAMP or Homebrew to install Apache, PHP, and MySQL.
Configuration:
Apache's configuration files are usually located in /etc/apache2/ on Linux.
You can configure virtual hosts, modules, and other settings in these files.
PHP configuration is typically in /etc/php/ directory.
Remember to follow the security best practices for your environment, such
as setting up firewalls, securing database servers, and keeping software
up-to-date. The specific steps might vary based on your distribution or
operating system, so refer to the documentation for your specific environment
for more accurate instructions.
2. Write programs to print all details of your php server. Use phpinfoO.
To retrieve and display all details about your PHP server, you can create a
simple PHP script that utilizes the phpinfo() function. Create a file, for
example, phpinfoO.php, and add the following code:
php
Copy code
<?php
// phpinfoO.php
// Output all information about PHP
phpinfo();
?>
Save this file in your web server's document root directory. Then, you can
access it through a web browser by navigating to http://your_server_ip/phpinfoO.php
or http://localhost/phpinfoO.php.
This script will display a comprehensive overview of your PHP
configuration, modules, server information, and more. Note that exposing such
detailed information about your server may pose security risks, so be cautious
about making this information publicly accessible. It's recommended to remove
or secure this file once you have gathered the necessary information.
3. Write a program to give demo of ECHO and PRINT command.
Certainly! Both echo and print are used in PHP to output data to the
browser or console. Here's a simple PHP script that demonstrates the use of
echo and print:
php
Copy code
<?php
// echoPrintDemo.php
// Using echo to output text
echo "Hello, this is a demonstration of the echo command. ";
// Using echo to output variables
$variable = "PHP is powerful!";
echo $variable;
// Using print to output text
print "<br>This is a demonstration of the print command. ";
// Using print to output variables
$anotherVariable = "Both echo and print can be used to display text.";
print $anotherVariable;
?>
Save this file, for example, as echoPrintDemo.php, in your web server's
document root directory. Then, access it through a web browser by navigating to
http://your_server_ip/echoPrintDemo.php
or http://localhost/echoPrintDemo.php.
This script demonstrates the use of both echo and print to output text and
variables. Note that echo can take multiple parameters separated by commas,
while print can only take one parameter. In practice, echo is more commonly
used for its simplicity and flexibility.
4. Write a program to implement the string functions .
Certainly! PHP provides a wide range of string functions that allow you to
manipulate and work with strings efficiently. Here's a simple PHP script that
demonstrates some common string functions:
php
Copy code
<?php
// stringFunctionsDemo.php
// String declaration
$string = "Hello, World! This is a PHP string functions demo.";
// 1. String Length
$length = strlen($string);
echo "1. String Length: " . $length . "<br>";
// 2. String to Uppercase
$uppercaseString = strtoupper($string);
echo "2. Uppercase: " . $uppercaseString .
"<br>";
// 3. String to Lowercase
$lowercaseString = strtolower($string);
echo "3. Lowercase: " . $lowercaseString .
"<br>";
// 4. Substring
$substring = substr($string, 0, 10); // Get the first 10 characters
echo "4. Substring: " . $substring . "<br>";
// 5. String Replace
$replacedString = str_replace("PHP", "JavaScript",
$string);
echo "5. String Replace: " . $replacedString .
"<br>";
// 6. String Concatenation
$concatenatedString = $string . " " . $uppercaseString;
echo "6. Concatenation: " . $concatenatedString .
"<br>";
// 7. String Trim
$whitespaceString = " Trim
this string ";
$trimmedString = trim($whitespaceString);
echo "7. String Trim: " . $trimmedString .
"<br>";
// 8. String Position
$position = strpos($string, "PHP");
echo "8. String Position of 'PHP': " . $position .
"<br>";
// 9. String Repeat
$repeatedString = str_repeat("Repeat ", 3);
echo "9. String Repeat: " . $repeatedString .
"<br>";
// 10. String Shuffle
$shuffledString = str_shuffle($string);
echo "10. String Shuffle: " . $shuffledString .
"<br>";
// Feel free to explore more PHP string functions as needed.
?>
Save this file, for example, as stringFunctionsDemo.php, in your web server's
document root directory. Access it through a web browser by navigating to http://your_server_ip/stringFunctionsDemo.php
or http://localhost/stringFunctionsDemo.php.
This script showcases various string functions in PHP, but there are many
more available. Refer to the official PHP documentation for a comprehensive
list and details on each string function.
5. Write a program to print Fibonacci series upto given number.
Certainly! Here's a simple PHP program that prints the Fibonacci series up
to a given number:
php
Copy code
<?php
// fibonacciSeries.php
// Function to generate Fibonacci series up to a given number
function generateFibonacci($n) {
$fibonacciSeries = array(0, 1);
for ($i = 2; $i < $n; $i++) {
$fibonacciSeries[$i] =
$fibonacciSeries[$i - 1] + $fibonacciSeries[$i - 2];
}
return $fibonacciSeries;
}
// Given number to generate Fibonacci series up to
$givenNumber = 10;
// Call the function
$fibonacciSeries = generateFibonacci($givenNumber);
// Print the Fibonacci series
echo "Fibonacci series up to {$givenNumber} : " . implode(",
", $fibonacciSeries);
?>
Save this file as fibonacciSeries.php in your web server's document root
directory. Access it through a web browser by navigating to http://your_server_ip/fibonacciSeries.php
or http://localhost/fibonacciSeries.php.
In this example, the generateFibonacci function generates the Fibonacci
series up to the given number ($n). The series is then printed using echo. You
can change the value of $givenNumber to generate the Fibonacci series up to a
different number.
6. Write a menu driven program to implement a calculator
which performs only addition, subtraction, multiplication
and division. The operation should happen based on user
choice.
Certainly! Here's a simple menu-driven PHP calculator program that performs
addition, subtraction, multiplication, and division based on user input:
php
Copy code
<?php
// calculator.php
// Function to perform addition
function add($num1, $num2) {
return $num1 + $num2;
}
// Function to perform subtraction
function subtract($num1, $num2) {
return $num1 - $num2;
}
// Function to perform multiplication
function multiply($num1, $num2) {
return $num1 * $num2;
}
// Function to perform division
function divide($num1, $num2) {
// Check if the denominator is
not zero to avoid division by zero
if ($num2 != 0) {
return $num1 / $num2;
} else {
return "Cannot divide by
zero";
}
}
// Display menu and get user choice
echo "Simple Calculator\n";
echo "1. Addition\n";
echo "2. Subtraction\n";
echo "3. Multiplication\n";
echo "4. Division\n";
echo "Enter your choice (1-4): ";
$userChoice = readline();
// Get user input for numbers
echo "Enter first number: ";
$num1 = readline();
echo "Enter second number: ";
$num2 = readline();
// Perform calculation based on user choice
switch ($userChoice) {
case 1:
$result = add($num1, $num2);
echo "Result: {$num1} +
{$num2} = {$result}\n";
break;
case 2:
$result = subtract($num1,
$num2);
echo "Result: {$num1} -
{$num2} = {$result}\n";
break;
case 3:
$result = multiply($num1,
$num2);
echo "Result: {$num1} *
{$num2} = {$result}\n";
break;
case 4:
$result = divide($num1, $num2);
echo "Result: {$num1} /
{$num2} = {$result}\n";
break;
default:
echo "Invalid choice.
Please enter a number between 1 and 4.\n";
}
?>
Save this file as calculator.php and run it in a PHP environment. The
program will prompt the user to select an operation and enter two numbers, and
then it will display the result based on the chosen operation.
7. Write a program sort ten number by using array.
Certainly! Below is a simple PHP program that sorts an array of ten numbers
using the sort() function:
php
Copy code
<?php
// sortNumbers.php
// Array of ten numbers
$numbers = array(5, 2, 8, 1, 9, 3, 7, 4, 10, 6);
// Display the original array
echo "Original Array: " . implode(", ", $numbers) .
"\n";
// Sort the array in ascending order
sort($numbers);
// Display the sorted array
echo "Sorted Array: " . implode(", ", $numbers) .
"\n";
?>
Save this file as sortNumbers.php in your web server's document root
directory. Access it through a web browser by navigating to http://your_server_ip/sortNumbers.php
or http://localhost/sortNumbers.php.
This program initializes an array of ten numbers, sorts them in ascending
order using the sort() function, and then displays the original and sorted
arrays. You can customize the array with your own set of numbers if needed.
8. Write a program to demonstrate the concept of associative
array.
Certainly! In PHP, an associative array is an array that uses named keys instead
of numerical indices. Here's a simple program that demonstrates the concept of
associative arrays:
php
Copy code
<?php
// associativeArrayDemo.php
// Creating an associative array
$student = array(
"name" => "John
Doe",
"age" => 20,
"grade" =>
"A",
"subjects" =>
array("Math", "English", "Science")
);
// Accessing and displaying elements of the associative array
echo "Student Name: " . $student["name"] .
"\n";
echo "Age: " . $student["age"] . "\n";
echo "Grade: " . $student["grade"] . "\n";
echo "Subjects: " . implode(", ",
$student["subjects"]) . "\n";
// Modifying an element in the associative array
$student["age"] = 21;
// Adding a new element to the associative array
$student["address"] = "123 Main St";
// Displaying the modified associative array
echo "\nModified Student Information:\n";
echo "Student Name: " . $student["name"] .
"\n";
echo "Age: " . $student["age"] . "\n";
echo "Grade: " . $student["grade"] . "\n";
echo "Subjects: " . implode(", ",
$student["subjects"]) . "\n";
echo "Address: " . $student["address"] .
"\n";
?>
Save this file as associativeArrayDemo.php in your web server's document
root directory. Access it through a web browser by navigating to http://your_server_ip/associativeArrayDemo.php
or http://localhost/associativeArrayDemo.php.
In this program, an associative array named $student is created with keys
such as "name," "age," "grade," and
"subjects." The program then demonstrates how to access, modify, and
add elements to the associative array. Associative arrays are useful for
organizing data with named keys for better readability and understanding of the
data structure.
9. Write a program to demonstrate thle concept of multidimensional array.
Certainly! In PHP, a multidimensional array is an array that contains one
or more arrays as its elements. Here's a simple program that demonstrates the
concept of a multidimensional array:
Copy code
<?php
// multidimensionalArrayDemo.php
// Creating a multidimensional array
$students = array(
array("name" =>
"John Doe", "age" => 20, "grade" =>
"A", "subjects" => array("Math",
"English", "Science")),
array("name" =>
"Jane Smith", "age" => 22, "grade" =>
"B", "subjects" => array("History",
"Art", "Physics")),
array("name" =>
"Bob Johnson", "age" => 21, "grade" =>
"C", "subjects" => array("Chemistry",
"Geography", "Music"))
);
// Accessing and displaying elements of the multidimensional array
echo "Student 1:\n";
echo "Name: " . $students[0]["name"] . "\n";
echo "Age: " . $students[0]["age"] . "\n";
echo "Grade: " . $students[0]["grade"] .
"\n";
echo "Subjects: " . implode(", ",
$students[0]["subjects"]) . "\n";
echo "\nStudent 2:\n";
echo "Name: " . $students[1]["name"] . "\n";
echo "Age: " . $students[1]["age"] . "\n";
echo "Grade: " . $students[1]["grade"] .
"\n";
echo "Subjects: " . implode(", ",
$students[1]["subjects"]) . "\n";
echo "\nStudent 3:\n";
echo "Name: " . $students[2]["name"] . "\n";
echo "Age: " . $students[2]["age"] . "\n";
echo "Grade: " . $students[2]["grade"] .
"\n";
echo "Subjects: " . implode(", ",
$students[2]["subjects"]) . "\n";
?>
Save this file as multidimensionalArrayDemo.php in your web server's
document root directory. Access it through a web browser by navigating to http://your_server_ip/multidimensionalArrayDemo.php
or http://localhost/multidimensionalArrayDemo.php.
In this program, a multidimensional array named $students is created with
three sub-arrays, each representing a student's information. The program then
demonstrates how to access and display elements of the multidimensional array.
Multidimensional arrays are useful for representing tabular data or nested
structures.
10. Write a program to demonstrate the concept of Classes &
and objects. Create a "password". login form When with user two
enters text fields "Kalinga called "`as a "login" user .
Certainly! Below is an example of a simple PHP program that demonstrates
the concept of classes and objects by creating a basic login form with a
"User" class:
Copy code
<?php
// User.php
class User {
private $username;
private $password;
// Constructor to initialize the username and password
public function
__construct($username, $password) {
$this->username =
$username;
$this->password =
$password;
}
// Method to validate login
credentials
public function
validateLogin($enteredUsername, $enteredPassword) {
if ($enteredUsername ==
$this->username && $enteredPassword == $this->password) {
return true;
} else {
return false;
}
}
}
// Usage of the User class
$user = new User("Kalinga", "called");
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get user input from the form
$enteredUsername =
$_POST["username"];
$enteredPassword =
$_POST["password"];
// Validate login credentials
using the User class
if ($user->validateLogin($enteredUsername,
$enteredPassword)) {
echo "Login successful!
Welcome, {$enteredUsername}.";
} else {
echo "Invalid username
or password. Please try again.";
}
}
?>
<!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>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">
<label
for="username">Username:</label>
<input
type="text" name="username" required><br>
<label
for="password">Password:</label>
<input
type="password" name="password" required><br>
<input
type="submit" value="Login">
</form>
</body>
</html>
Save this file as loginForm.php in your web server's document root
directory. Access it through a web browser by navigating to http://your_server_ip/loginForm.php
or http://localhost/loginForm.php.
This program defines a User class with a constructor to set the username
and password and a method (validateLogin) to validate login credentials. The
HTML part of the code creates a simple login form with fields for entering the
username and password. The PHP part checks the submitted form data against the
predefined username and password in the User class and displays a success or
error message accordingly.
11. Name and "University" as a password it should be redirected
to a Welcome.HTML page or toSorry.HTML in
case of wrong username/password .
Certainly! Below is an updated version of the PHP program that redirects to
different pages based on the entered username and password:
PHP
Copy code
<?php
// User.php
class User {
private $username;
private $password;
// Constructor to initialize the
username and password
public function
__construct($username, $password) {
$this->username =
$username;
$this->password =
$password;
}
// Method to validate login
credentials
public function
validateLogin($enteredUsername, $enteredPassword) {
return ($enteredUsername ==
$this->username && $enteredPassword == $this->password);
}
}
// Usage of the User class
$user = new User("name", "University");
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get user input from the form
$enteredUsername =
$_POST["username"];
$enteredPassword =
$_POST["password"];
// Validate login credentials
using the User class
if ($user->validateLogin($enteredUsername, $enteredPassword)) {
// Redirect to Welcome.HTML
on successful login
header("Location:
Welcome.HTML");
exit();
} else {
// Redirect to Sorry.HTML on
invalid credentials
header("Location: Sorry.HTML");
exit();
}
}
?>
<!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>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">
<label
for="username">Username:</label>
<input
type="text" name="username" required><br>
<label
for="password">Password:</label>
<input
type="password" name="password" required><br>
<input
type="submit" value="Login">
</form>
</body>
</html>
In this version, after validating the login credentials, the program uses
the header function to redirect to either "Welcome.HTML" or
"Sorry.HTML" based on whether the login is successful or not. Make
sure to replace "Welcome.HTML" and "Sorry.HTML" with the
actual file names or paths you intend to use. Also, ensure that there is no
output (including whitespace) before the header function is called to avoid
issues with redirection.
12. Create a database in MySql and connect that database from PHP.
To create a MySQL database and connect to it using PHP, you need to follow
these steps:
Step 1: Create a MySQL Database
You can use a MySQL client or a tool like phpMyAdmin to create a database.
Here's an example using MySQL command line:
sql
Copy code
CREATE DATABASE mydatabase;
Replace "mydatabase" with your desired database name.
Step 2: Create a Table
Let's create a simple table within the database:
sql
Copy code
USE mydatabase;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY
KEY,
username VARCHAR(50),
password VARCHAR(50)
);
Step 3: PHP Connection
Now, you can create a PHP script to connect to the MySQL database:
php
Copy code
<?php
// db_connection.php
$hostname = 'localhost'; // Replace with your MySQL server hostname
$username = 'root'; // Replace
with your MySQL username
$password = ''; // Replace
with your MySQL password
$database = 'mydatabase'; // Replace with your MySQL database name
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed:
" . $conn->connect_error);
}
echo "Connected successfully";
?>
Replace the values of $hostname, $username, $password, and $database with
your MySQL server details.
Step 4: Test the Connection
Create another PHP script to test the database connection:
php
Copy code
<?php
// test_connection.php
include 'db_connection.php'; // Include the connection script
// Perform a simple query to test the connection
$query = "SELECT * FROM users";
$result = $conn->query($query);
if ($result) {
echo "Query executed
successfully!";
} else {
echo "Error executing query:
" . $conn->error;
}
// Close the connection
$conn->close();
?>
Place both scripts (db_connection.php and test_connection.php) in your web
server's document root directory. Access test_connection.php through a web
browser to see if the connection is successful.
Make sure to replace the database details and credentials with your actual
MySQL server details. Additionally, consider using secure practices for
database access, such as using a separate user with limited privileges and
avoiding hardcoding sensitive information in your scripts.
13. Write a program to Update, insert and delete the values of table in
database
Certainly! Below is an example PHP script that demonstrates how to update,
insert, and delete values in a MySQL database table:
php
Copy code
<?php
// db_connection.php
$hostname = 'localhost'; // Replace with your MySQL server hostname
$username = 'root'; // Replace
with your MySQL username
$password = ''; // Replace
with your MySQL password
$database = 'mydatabase'; // Replace with your MySQL database name
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed:
" . $conn->connect_error);
}
?>
<?php
// update_insert_delete.php
include 'db_connection.php'; // Include the connection script
// Update data in the table
$updateQuery = "UPDATE users SET password = 'newpassword' WHERE
username = 'john_doe'";
if ($conn->query($updateQuery) === TRUE) {
echo "Record updated
successfully<br>";
} else {
echo "Error updating record:
" . $conn->error . "<br>";
}
// Insert data into the table
$insertQuery = "INSERT INTO users (username, password) VALUES
('new_user', 'new_user_password')";
if ($conn->query($insertQuery) === TRUE) {
echo "Record inserted
successfully<br>";
} else {
echo "Error inserting
record: " . $conn->error . "<br>";
}
// Delete data from the table
$deleteQuery = "DELETE FROM users WHERE username = 'old_user'";
if ($conn->query($deleteQuery) === TRUE) {
echo "Record deleted
successfully<br>";
} else {
echo "Error deleting record:
" . $conn->error . "<br>";
}
// Close the connection
$conn->close();
?>
In this example:
The update_insert_delete.php script includes the database connection script
(db_connection.php).
It updates a user's password in the users table.
It inserts a new user into the users table.
It deletes an old user from the users table.
Make sure to replace the database details and credentials with your actual
MySQL server details. Additionally, customize the table and column names
according to your database schema.
Remember to handle database operations with caution, especially when
dealing with user input, to prevent SQL injection. Consider using prepared
statements or parameterized queries for more secure interactions with the
database.
14. Create a form with a text box asking to enter your favorite city with a
submit button when the user enters the city and clicks the submit button
another php page should be opened displaying "-Welcome to the city" .
Certainly! Below is an example of a simple PHP program that includes an
HTML form asking the user to enter their favorite city. Upon submission,
another PHP page is opened, displaying a welcome message to the entered city:
Form Page (city_form.php):
php
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Favorite City
Form</title>
</head>
<body>
<h2>Enter Your Favorite
City</h2>
<form
action="welcome_city.php" method="post">
<label
for="city">Favorite City:</label>
<input
type="text" name="city" required>
<input
type="submit" value="Submit">
</form>
</body>
</html>
Welcome Page (welcome_city.php):
php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the entered city from the
form
$favoriteCity =
$_POST["city"];
// Display the welcome message
echo "<h2>Welcome to
{$favoriteCity}!</h2>";
} else {
// If accessed directly without
submitting the form, redirect to the form page
header("Location:
city_form.php");
exit();
}
?>
Save these files in your web server's document root directory. Access the
city_form.php page through a web browser by navigating to http://your_server_ip/city_form.php
or http://localhost/city_form.php.
Enter your favorite city in the form, click the submit button, and you will
be redirected to the welcome_city.php page displaying a welcome message to the
entered city. If you access welcome_city.php directly without submitting the
form, it will redirect you to the form page.
15. Write a program to design login form in which find the greatest number
amongst three numbers .
Certainly! Below is an example of a PHP program that designs a login form
and, upon successful login, finds the greatest number among three input
numbers:
Login and Number Comparison Page (login_and_compare.php):
php
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Login and Number
Comparison</title>
</head>
<body>
<?php
// Check if form is submitted
if
($_SERVER["REQUEST_METHOD"] == "POST") {
// Get user input from the
form
$username =
$_POST["username"];
$password =
$_POST["password"];
// Validate login credentials
(for demonstration purposes)
if ($username ==
"user" && $password == "pass") {
// If login is
successful, display the number comparison form
echo
"<h2>Welcome, {$username}!</h2>";
?>
<h3>Find the
Greatest Number</h3>
<form
action="" method="post">
<label
for="num1">Number 1:</label>
<input
type="number" name="num1" required><br>
<label
for="num2">Number 2:</label>
<input
type="number" name="num2" required><br>
<label
for="num3">Number 3:</label>
<input
type="number" name="num3" required><br>
<input
type="submit" value="Find Greatest Number">
</form>
<?php
// Check if the number
comparison form is submitted
if
($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the entered
numbers
$num1 =
$_POST["num1"];
$num2 =
$_POST["num2"];
$num3 = $_POST["num3"];
// Find the greatest number
$greatestNumber =
max($num1, $num2, $num3);
// Display the result
echo
"<p>The greatest number among {$num1}, {$num2}, and {$num3} is:
{$greatestNumber}</p>";
}
?>
<?php
} else {
// If login fails,
display an error message
echo
"<p>Invalid username or password. Please try again.</p>";
}
}
?>
<h2>Login Form</h2>
<form action=""
method="post">
<label
for="username">Username:</label>
<input
type="text" name="username" required><br>
<label
for="password">Password:</label>
<input
type="password" name="password" required><br>
<input type="submit"
value="Login">
</form>
</body>
</html>
In this example, the program first displays a login form. If the login is
successful (for demonstration purposes, using hardcoded credentials), it shows
a form to input three numbers. After submitting the number comparison form, it
calculates and displays the greatest number among the entered numbers.
Save this file as login_and_compare.php in your web server's document root
directory. Access it through a web browser by navigating to http://your_server_ip/login_and_compare.php
or http://localhost/login_and_compare.php.
16. WAP for Marksheet generation.
Certainly! Below is an example of a PHP program that generates a marksheet
based on the input of student details and marks. The program calculates the
total marks, percentage, and grade and displays them in the marksheet:
php
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Marksheet
Generation</title>
</head>
<body>
<?php
// Check if the form is submitted
if
($_SERVER["REQUEST_METHOD"] == "POST") {
// Get student details and
marks from the form
$studentName =
$_POST["student_name"];
$rollNumber =
$_POST["roll_number"];
$subject1 =
$_POST["subject1"];
$subject2 =
$_POST["subject2"];
$subject3 =
$_POST["subject3"];
// Calculate total marks,
percentage, and grade
$totalMarks = $subject1 +
$subject2 + $subject3;
$percentage = ($totalMarks /
300) * 100;
// Determine the grade based
on percentage
if ($percentage >= 90) {
$grade = 'A';
} elseif ($percentage >= 80) {
$grade = 'B';
} elseif ($percentage >=
70) {
$grade = 'C';
} elseif ($percentage >=
60) {
$grade = 'D';
} else {
$grade = 'F';
}
?>
<h2>Marksheet</h2>
<p><strong>Student Name:</strong> <?php echo
$studentName; ?></p>
<p><strong>Roll
Number:</strong> <?php echo $rollNumber; ?></p>
<p><strong>Subject 1 Marks:</strong> <?php echo
$subject1; ?></p>
<p><strong>Subject
2 Marks:</strong> <?php echo $subject2; ?></p>
<p><strong>Subject 3 Marks:</strong> <?php echo
$subject3; ?></p>
<p><strong>Total
Marks:</strong> <?php echo $totalMarks; ?></p>
<p><strong>Percentage:</strong> <?php echo
number_format($percentage, 2) . '%'; ?></p>
<p><strong>Grade:</strong> <?php echo $grade;
?></p>
<?php
} else {
?>
<h2>Enter Student
Details and Marks</h2>
<form action=""
method="post">
<label for="student_name">Student
Name:</label>
<input
type="text" name="student_name" required><br>
<label
for="roll_number">Roll Number:</label>
<input
type="text" name="roll_number" required><br>
<label
for="subject1">Subject 1 Marks:</label>
<input
type="number" name="subject1" required><br>
<label
for="subject2">Subject 2 Marks:</label>
<input
type="number" name="subject2" required><br>
<label
for="subject3">Subject 3 Marks:</label>
<input
type="number" name="subject3" required><br>
<input
type="submit" value="Generate Marksheet">
</form>
<?php
}
?>
</body>
</html>
Save this file as marksheet.php in your web server's document root
directory. Access it through a web browser by navigating to http://your_server_ip/marksheet.php
or http://localhost/marksheet.php.
Comments
Post a Comment