0% found this document useful (0 votes)
16 views11 pages

Edited PR 9

This document outlines a practical exercise for web development using PHP, focusing on form validation and email sending. Students will learn to validate user input for name and email, and send plain text, HTML emails, and attachments using PHP scripts. The practical aims to enhance students' skills in PHP programming, coding standards, and teamwork.

Uploaded by

lathiyaparth61
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views11 pages

Edited PR 9

This document outlines a practical exercise for web development using PHP, focusing on form validation and email sending. Students will learn to validate user input for name and email, and send plain text, HTML emails, and attachments using PHP scripts. The practical aims to enhance students' skills in PHP programming, coding standards, and teamwork.

Uploaded by

lathiyaparth61
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Web Development using PHP (4341604)

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.

B. Expected Program Outcomes (POs)

Basic and Discipline specific knowledge: Apply knowledge of basic mathematics,


science and engineering fundamentals and engineering specialization to solve the
engineering problems.
Problem analysis: Identify and analyse well-defined engineering problems using
codified standard methods.
Design/ development of solutions: Design solutions for engineering well-defined
technical problems and assist with the design of systems components or processes to
meet specified needs.
Engineering Tools, Experimentation and Testing: Apply modern engineering tools
and appropriate technique to conduct standard tests and measurements.
Project Management: Use engineering management principles individually, as a team
member or a leader to manage projects and effectively communicate about well-
defined engineering activities.
Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes in field of engineering.

C. Expected Skills to be developed based on competency:

“Develop a webpage using PHP”


This practical is expected to develop the following skills.
1. Apply validation to name, email using appropriate function.
2. Create script for sending email, HTML email and attachments with email.
3. Follow coding standards and debug program to fix errors.

D. Expected Course Outcomes(Cos)

CO2: Create User defined functions in PHP programming.

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.

F. Expected Affective domain Outcome(ADos)

1) Follow safety practices.


2) Follow Coding standards and practices.
3) Demonstrate working as a leader/ a team member.
4) Follow ethical practices.
5) Maintain tools and equipment.

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)

$name = $_POST ["Name"];


if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
} else {
echo $name;
}

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:

$mobileno = $_POST ["Mobile_no"];


if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
echo $mobileno;
}

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:

$email = $_POST ["Email"];


$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-
z]{2,3})$^";
if (!preg_match ($pattern, $email) ){
$ErrMsg = "Email is not valid.";
echo $ErrMsg;
} else {
echo "Your valid email address is: " .$email;
}

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:

$mobileno = strlen ($_POST ["Mobile"]);


$length = strlen ($mobileno);
if ( $length < 10 && $length > 10) {
$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else {
echo "Your Mobile number is: " .$mobileno;
}

Sending Email in PHP


Use the mail() function in PHP to send the email. The mail() function requires at least
three parameters: the recipient email address, the subject, and the message body.

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)

Sending plain text email

<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";

mail($to,$subject,$txt,$headers);
?>

Sending HTML email

<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "<h1>This is HTML Email</h1> \r\n";
$message .= "<h1>This is HTML Heading.</h1>";

$header = "From:[email protected] \r\n";


$header .= "MIME-Version: 1.0 \r\n";
$header .= "Content-type: text/html;charset=UTF-8 \r\n";

$result = mail ($to,$subject,$message,$header);


if( $result == true ){
echo "Message sent successfully...";
}else{
echo "Sorry, unable to send mail...";
}
?>

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

5 Web Browser Edge, Firefox, Chrome or similar

I. Safety and necessary Precautions followed

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";
}
}
}

// Function to sanitize input data


function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<!-- Form -->


<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span style="color:red">* <?php echo $nameErr; ?></span>
<br><br>

Email: <input type="text" name="email" value="<?php echo $email; ?>">


<span style="color:red">* <?php echo $emailErr; ?></span>
<br><br>

<input type="submit" value="Submit">


</form>

<?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;

require 'vendor/autoload.php'; // Load PHPMailer

// 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)

// Handling different email types


if ($emailType == "plain") {
$mail->isHTML(false);
$mail->Subject = "Plain Text Email";
$mail->Body = "Hello, this is a plain text email!";
}
elseif ($emailType == "html") {
$mail->isHTML(true);
$mail->Subject = "HTML Email Example";
$mail->Body = "<h2 style='color:blue;'>Hello, this is an HTML email!</h2>
<p>This email contains <b>bold</b> and <i>italic</i> text.</p>";
$mail->AltBody = "Hello, this is an HTML email!";
}
elseif ($emailType == "attachment") {
$mail->isHTML(true);
$mail->Subject = "Email with Attachment";
$mail->Body = "<h3>Hello, this email contains an attachment.</h3>";
$mail->AltBody = "Hello, this email contains an attachment.";

// 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>";

} catch (Exception $e) {


echo "<p style='color:red;'>Email could not be sent. Error: {$mail->ErrorInfo}</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]

✔ Email sent successfully!

K. Practical related Quiz.

1. preg_match() function is used to Perform pattern matching using regular expressions


in PHP. It checks if a string matches a given pattern.

2. For sending email mail() function is used in PHP.


3. Empty() function checks wheather a variable is empty.

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

You might also like