Edited PR 9
Edited PR 9
Date: _________________
Practical No.9: Email and Validation
a. Write PHP script to validate form including name, email using
appropriate functions.
b. Write PHP script for sending plain text email, HTML email and
attachments with email.
A. Objective:
Forms validation and sending email are important if we talk about input of form. By
practical students will be able to learn from validation and sending email details from
form.
105 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
Students will be able to perform validation and to email data entered in form by users
using PHP.
G. Prerequisite Theory:
Form Validation
Form validation in PHP is the process of verifying that the data submitted by a user
through a web form is valid, complete, and meets the required format. An HTML form
contains various input fields such as text box, checkbox, radio buttons, submit button,
and checklist, etc. These input fields need to be validated, which ensures that the user
has entered information in all the required fields and also validates that the
information provided by the user is valid and correct.
PHP validates the data at the server-side, which is submitted by HTML form. You need
to validate a few things:
Empty String
The code below checks that the field is not empty. If the user leaves the required field
empty, it will show an error message. Put these lines of code to validate the required
field.
if (empty ($_POST["name"])) {
$errMsg = "Error! Kindly Enter the Name.";
echo $errMsg;
} else {
$name = $_POST["name"];
}
Validate String
The code below checks that the field will contain only alphabets and whitespace, for
example - name. If the name field does not receive valid input from the user, then it
will show an error message:
106 | Page
Web Development using PHP (4341604)
Validate Numbers
The below code validates that the field will only contain a numeric value. For example -
Mobile no. If the Mobile no field does not receive numeric data from the user, the code
will display an error message:
Validate Email
A valid email must contain @ and . symbols. PHP provides various methods to validate
the email address. Here, we will use regular expressions to validate the email address.
The below code validates the email address provided by the user through HTML form.
If the field does not contain a valid email address, then the code will display an error
message:
107 | Page
Web Development using PHP (4341604)
Validate URL
The below code validates the URL of website provided by the user via HTML form. If
the field does not contain a valid URL, the code will display an error message, i.e., "URL
is not valid".
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-
a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}
Input length
The input length validation restricts the user to provide the value between the
specified range, for Example - Mobile Number. A valid mobile number must have 10
digits. The given code will help you to apply the length validation on user input:
Syntax:
mail(to, subject, message, headers, parameters);
Here,
To: Required. Specifies receiver or receivers of the mail.
Subject: Required. Specifies the subject of the email.
Message: Required. Defines the message to be sent.
Headers: Optional. Specifies additional headers, like From, Cc, and Bcc.
Parameters: Optional. Specifies an additional parameter to the sendmail program
108 | Page
Web Development using PHP (4341604)
<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";
mail($to,$subject,$txt,$headers);
?>
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "<h1>This is HTML Email</h1> \r\n";
$message .= "<h1>This is HTML Heading.</h1>";
109 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
NA
J. Source code:
A) Write PHP script to validate form including name, email using appropriate functions.
<!DOCTYPE html>
<html>
<head>
<title>PHP Form Validation</title>
</head>
<body>
<?php
// Define variables and set them to empty values
$name = $email = "";
$nameErr = $emailErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate Name
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and spaces are allowed";
}
}
110 | Page
Web Development using PHP (4341604)
// Validate Email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
<?php
// Display validated input if no errors
if ($_SERVER["REQUEST_METHOD"] == "POST" && empty($nameErr) && empty($emailErr)) {
echo "<h3>Form Submitted Successfully!</h3>";
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
}
?>
</body>
</html>
111 | Page
Web Development using PHP (4341604)
A) Input/Output:
B) Write PHP script for sending plain text email, HTML email and attachments
with email
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Email Configuration
$to = "[email protected]"; // Change to recipient email
$from = "[email protected]"; // Change to sender email
$fromName = "Your Name";
$smtpHost = "smtp.example.com"; // Change SMTP server
$smtpUser = "[email protected]"; // Change SMTP username
$smtpPass = "your_password"; // Change SMTP password
$smtpPort = 587; // Change SMTP port if needed
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$emailType = $_POST['email_type'];
try {
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = $smtpHost;
$mail->SMTPAuth = true;
$mail->Username = $smtpUser;
$mail->Password = $smtpPass;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = $smtpPort;
$mail->setFrom($from, $fromName);
$mail->addAddress($to);
112 | Page
Web Development using PHP (4341604)
// Attach a file
$filePath = "path/to/your/file.pdf"; // Change to your file path
if (file_exists($filePath)) {
$mail->addAttachment($filePath);
} else {
echo "Attachment file not found!";
exit;
}
}
// Send Email
$mail->send();
echo "<p style='color:green;'>Email sent successfully!</p>";
<!DOCTYPE html>
<html>
<head>
<title>PHP Email Sender</title>
</head>
113 | Page
Web Development using PHP (4341604)
<body>
<h2>Send Email</h2>
<form method="post">
<label>Select Email Type:</label>
<select name="email_type">
<option value="plain">Plain Text Email</option>
<option value="html">HTML Email</option>
<option value="attachment">Email with Attachment</option>
</select>
<br><br>
<input type="submit" value="Send Email">
</form>
</body>
</html>
B) Input/Output:
Send Email
Select Email Type: [Dropdown]
(Plain Text Email, HTML Email, Email with Attachment)
[Send Email Button]
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
114 | Page
Web Development using PHP (4341604)
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
115 | Page