Web Applications Development using PHP & MYSQL
V Semester UT-III
M NAGA V VARA PRASAD, Assistant Professor, CS, BVRC (III Chem)
UT-III Syllabus
Working with Forms: Creating Forms, Accessing Form Input with User defined Arrays, Combining HTML and
PHP code on a single Page, Using Hidden Fields to save state, Redirecting the user, Sending Mail on Form
Submission, and Working with File Uploads, Managing files on server, Exception handling.
Working With Forms:
HTML FORM: HTML form is a section of a document which contains controls such as text fields, password fields, checkboxes,
radio buttons, submit button, menus etc.
Syntax:
<form>
<!--form elements-->
</form>
FORM ELEMENTS:
These are the following HTML <form> elements:
1. <label> : It defines label for <form> elements.
2. <input> : It is used to get input data from the form in various types such as text, password, email, etc by changing its type.
3. <button> : It defines a clickable button to control other elements or execute a functionality.
4. <select> : It is used to create a drop-down list.
5. <textarea>: It is used to get input long text content.
6. <fieldset> : It is used to draw a box around other form elements and group the related data.
7. <legend> : It defines caption for field set elements.
8. <datalist> : It is used to specify pre-defined list options for input controls.
9. <output> : It displays the output of performed calculations.
10. <option> : It is used to define options in a drop-down list.
11. <optgroup>: It is used to define group-related options in a drop-down list.
Creating forms:
Creating forms in PHP involves two main parts:
The HTML form – This is used to collect user input.
The PHP script – This processes the data submitted by the form.
Step-by-Step Example: Simple Form Handling in PHP
1. Create the HTML Form
Save as: [Link]
<form action="[Link]" method="post">
Name: <input type="text" name="name" required><br><br>
Email: <input type=“email" name="email" required><br><br><br>
<input type="submit" value="Submit">
</form>
• action="[Link]" — The PHP file that will handle the form data.
• method="post" — Sends data securely (not visible in URL). You can also use get.
2. Create the PHP Script to Handle Form Data
Save as: [Link]
<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Collect and sanitize input
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
// Display the input
echo "Your name is: " . $name . "<br>";
echo "Your email is: " . $email;
}
else
{
echo "Form not submitted properly.";
}
?>
• $_POST['name'] — Gets the value of the name field.
• htmlspecialchars() — Prevents XSS by converting special characters.
Accessing Form Input with User defined Arrays:
Creating Student Details Form:
Creating Student Details Form in PHP involves two main parts:
1. The HTML form – This is used to collect users to input student details such as:
• Student Number
• Student Name
• Student Class (BSC, BCA, MCA)
• Gender
• Area of Interests (checkboxes: cricket, football, volleyball)
On submission, the form data is sent via POST method to the file:
2. The PHP script – The Student Data Processing and submitted by the form.
• Checks if the form was submitted using POST.
• Retrieves and displays:
• Student Number (sno)
• Student Name (sname)
• Student Class (studentclass)
• Gender (gender)
• Interests (array from checkboxes)
Step-by-Step Example: Student Details Form Handling in PHP
1. Create the HTML Form
Save as: Creating _Student_Details.html
<form action="Creating_Student_Details.php" method="POST">
<table border="1" bgcolor="#fcba03" align="center" cellpadding="5">
<tr>
<th colspan="2">STUDENT DATA ENTRY FORM</th>
</tr>
<tr>
<td>Student Number</td>
<td><input type="text" name="sno" placeholder="Enter your regd no"></td>
</tr>
<tr>
<td>Student Name</td>
<td><input type="text" name="sname" placeholder="Enter your name"></td>
</tr>
<tr>
<td>Student Class</td>
<td>
<select name="studentclass">
<option value="">Select Section</option>
<option>BSC</option>
<option>BCA</option>
<option>MCA</option>
</select>
</td>
</tr>
<tr>
<td>Gender</td>
<td>
<input type="radio" name="gender" value="M"> Male
<input type="radio" name="gender" value="F"> Female
</td>
</tr>
<tr>
<td>Area of Interests</td>
<td>
<input type="checkbox" name="interests[ ]" value="cricket"> Cricket
<input type="checkbox" name="interests[ ]" value="football"> Football
<input type="checkbox" name="interests[ ]" value="volleyball"> Volleyball
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
• interests[ ] is a way to send multiple values for the same field name to PHP
• <tr> -- Table Row
• <td> -- Data Cell( element) in a table row.
• <th> -- Table Header Cell (Text is bold and centered by default)
• colspan—Merge Columns(Add colspan=“number” in <td> or <th>
2. Create the PHP Script to Handle Form Data
Save as: Creating_Student_Details.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
echo "Your regd number is: " . ($_POST['sno'] ?? ‘ ') . "<br>";
echo "Name is: " . ($_POST['sname'] ?? ‘ ') . "<br>";
echo "Class is: " . ($_POST['studentclass'] ?? ‘ ') . "<br>";
echo "Gender is: " . ($_POST['gender'] ?? ‘ ') . "<br>";
if (!empty($_POST['interests'])) {
echo "Interests: " . implode(", ", $_POST['interests']);
} else {
echo "No interests selected.";
}
} else {
echo "Please submit the form.";
}
?>
• !empty( ) is used for multiple checkbox handling.
• Used implode(", ", $_POST['interests']) instead of a loop for cleaner output.
• Kept ?? '' for safe default values if the field is missing.
• Still works for multiple interests (interests[ ]).
Explain how HTML and PHP can be combined on a single page with an example:
HTML is a markup language used to structure content (headings, paragraphs, tables, etc.) in a webpage.
PHP is a server-side scripting language used to make webpages dynamic (perform calculations, fetch data, generate output).
PHP is embedded inside HTML using <?php ... ?> tags.
The browser only receives the final HTML output, since PHP is executed on the server first.
Example Program:
<!doctype html>
<html>
<head>
<title>Combining HTML and PHP</title>
</head>
<body>
<h1>
<?php
echo "Hello, this is an example of combining HTML and PHP!";
?>
</h1>
<p>
Today’s date is:
<?php
echo date("l, d F Y"); // Prints day, date, month, year
?>
</p>
</body>
</html>
Output on Browser:
Hello, this is an example of combining HTML and PHP!
Today’s date is: Tuesday, 19 August 2025
Note: date("l, d F Y") – format string
l (lowercase L)Full name of the day → Tuesday
d Day of the month (two digits) → 19
F Full month name → August
Y 4-digit year → 2025
Explain the use of hidden fields in maintaining state in forms:
We want to collect user details in two steps (like a multi-page form), and we use a hidden field to pass data from the first form
to the second.
We’ll build a 2-step form that:
Step 1: Takes name and email
Step 2: Uses hidden fields to carry that info and ask for age
Final Step: Displays all data
Step 1: [Link]
<!-- [Link] -->
<form action="[Link]" method="post">
<label>Name:</label>
<input type="text" name="name" required><br><br>
<label>Email:</label>
<input type="email" name="email" required><br><br>
<input type="submit" value="Next">
</form>
Step 2: [Link]
<?php
// Check if data came from form1
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
}
else
{
echo "Invalid access.";
exit;
}
?>
<form action="[Link]" method="post">
<!-- Hidden fields to carry name and email -->
<input type="hidden" name="name" value="<?php echo $name; ?>">
<input type="hidden" name="email" value="<?php echo $email; ?>">
<label>Age:</label>
<input type="number" name="age" required><br><br>
<input type="submit" value="Submit All">
Final Step: [Link]
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$age = htmlspecialchars($_POST['age']);
echo "Name: $name <br>";
echo "Email: $email <br>";
echo "Age: $age";
}
else
{
echo "No data submitted.";
}
?>
Write a PHP program to send an email on form submission:
PHP Mail and File Uploads
1. PHP mail( ) Function
Used to send email directly from PHP scripts.
Syntax:
mail(to, subject, message, headers, parameters);
Parameters:
• to (Required) → Receiver’s email (multiple allowed, comma-separated).
• subject (Required) → Subject of the mail (no newline allowed).
• message (Required) → Body of the mail (lines separated by \n, max 70 chars/line).
• headers (Optional) → Extra headers like From, Cc, Bcc (separated with \r\n).
• parameters (Optional) → Extra options for the mail program.
Return Value:
TRUE → If mail sent successfully.
FALSE → If sending failed.
Explain the steps involved in uploading files to the server in PHP :
2. File Uploads in PHP
PHP supports single and multiple file uploads.
$_FILES Superglobal
When a file is uploaded, PHP stores its info in the $_FILES array:
• $_FILES['file']['tmp_name'] → Temp location on server.
• $_FILES['file']['name'] → Original file name.
• $_FILES['file']['size'] → File size in bytes.
• $_FILES['file']['type'] → MIME type of file.
• $_FILES['file']['error'] → Error code (if any).
File Upload Process
1. User opens form with browse & submit button.
2. User selects a file → path shown in text field.
3. File sent to temporary directory on server.
4. PHP script checks and moves file to target directory.
5. Confirmation shown to user.
HTML Form ([Link]):
<form action="[Link]" method="post" enctype="multipart/form-data">
Select File: <input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
PHP Script ([Link]):
<?php
$target_path = "e:/";
$target_path = $target_path . basename($_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path))
{
echo "File uploaded successfully!";
}
else
{
echo "Sorry, file not uploaded, please try again!";
}
?>
Output:
• File uploaded successfully! → if success
• Sorry, file not uploaded, please try again! → if failure
Managing files on server:
PHP is a server-side programming language. It allows us to create, access and manipulate files stored on the web server
using PHP file system functions.
With PHP, you can:
• Create / Open a file
• Closing a file
• Write / Read data
• Rename / Move a file
• Delete a file
1. Create / Open a File
We use fopen( ) function: To work with a file you first need to open the file.
Syntax:
fopen("filename", "mode");
Common Modes:
• "w" → Write (create new or overwrite)
• "a" → Append (add at the end)
• "r" → Read (file must exist)
Example:
<?php
$file = fopen("[Link]", "w"); // create file
if ($file)
{
echo "File created!";
fclose($file); // close file
}
?>
Output:
File created!
2. Write to a File
You can write data to a file using fwrite( ) function.
Example:
<?php
$file = fopen("[Link]", "w");
fwrite($file, "Hello! I am learning PHP file handling.");
fclose($file);
echo "Data Saved Successfully";
?>
Output:
Data Saved Successfully
3. Closing a File
You need to close a file using fclose() function.
Syntax:
fclose($file);
4. Read from a File
To read data from a file using fread( ) function.
Example:
<?php
$file = fopen("[Link]", "r");
echo fread($file, filesize("[Link]"));
fclose($file);
?>
Output:
Hello! I am learning PHP file handling.
5. Rename or Move a File
You can rename a file using rename( ) function.
Example:
<?php
$oldName = "[Link]";
$newName = "[Link]";
if (file_exists($oldName)) {
if (rename($oldName, $newName)) {
echo "File renamed from $oldName to $newName.";
}
else {
echo "Failed to rename the file.";
}
}
else {
echo "File '$oldName' does not exist.";
}
?>
Output:
File renamed from [Link] to [Link].
5. Rename or Move a File
You can rename a file using rename( ) function.
Example:
<?php
$oldName = "[Link]";
$newName = "[Link]";
if (file_exists($oldName)) {
if (rename($oldName, $newName)) {
echo "File renamed from $oldName to $newName.";
}
else {
echo "Failed to rename the file.";
}
}
else {
echo "File '$oldName' does not exist.";
}
?>
Output:
File renamed from [Link] to [Link].
6. Delete a File
The PHP unlink( ) function is used to delete file.
Example:
<?php
if (file_exists("[Link]"))
{
unlink("[Link]"); // delete file
echo "File deleted!";
}
else
{
echo "File not found!";
}
?>
Output:
File deleted!
Explain exception handling in PHP using try, catch, and throw with examples:
What is Exception Handling?
• Exception handling is a mechanism to manage runtime errors in a program.
• Instead of breaking the program when an error occurs, PHP allows you to catch the error and handle it gracefully.
Basic Structure of PHP Exception Handling:
try
{
// Code that might cause an error (exception)
}
catch (Exception $e)
{
// Code that runs if an error happens
}
finally
{
// Optional: code that always runs, error or not
}
Example 1: Simple Exception Handling
<?php
try
{
// Forcing an error
throw new Exception("Oops! Something went wrong.");
echo "This will not run if exception occurs.";
}
catch (Exception $e)
{
echo "Caught an exception: " . $e->getMessage();
}
finally
{
echo "<br>This always runs!";
}
?>
Output:
Caught an exception: Oops! Something went wrong.
This always runs!
Custom Exception:
You can create your own exception type by defining a class.
<?php
class MyException extends Exception { }
try
{
throw new MyException("Custom error happened.");
}
catch (MyException $e)
{
echo "Caught my custom exception: " . $e->getMessage();
}
?>
Output:
Caught my custom exception: Custom error happened.
Key Points
Term What it means
try → Block of code to test for errors.
throw → Used to create (raise) an exception.
catch → Handles the exception (error message).
finally → Always executes, whether error occurs or not.
Custom exceptions can be created using a class that extends Exception.
Example 2: Division Program with try–throw–catch–finally
<?php
// Function to divide two numbers
function divideNumbers($num1, $num2)
{
if ($num2 == 0)
{
throw new Exception("You cannot divide by zero.");
}
return $num1 / $num2;
}
try
{
echo "Starting division...<br>";
$a = 10;
$b = 0; // Change this to 2 to see success
$result = divideNumbers($a, $b);
echo "Result: $result<br>";
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage( ) . "<br>";
}
finally
{
echo "This is the finally block. It runs at the end.<br>";
}
?>
Output (if $b = 0):
Starting division...
Error: You cannot divide by zero.
This is the finally block. It runs at the end.
Output (if $b = 2):
Starting division...
Result: 5
This is the finally block. It runs at the end.
Channels:
⮚ @sivatutorials747 –Pdf Material