0% found this document useful (0 votes)
21 views26 pages

TY CO PHP Unit 04

This document covers the creation and validation of forms in web development using PHP, detailing various form controls such as text boxes, radio buttons, and checkboxes. It explains the use of GET and POST methods for data submission, the importance of validation, and how to manage cookies and sessions. Additionally, it includes examples of handling multiple forms and submit buttons on a single webpage to enhance user experience.
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)
21 views26 pages

TY CO PHP Unit 04

This document covers the creation and validation of forms in web development using PHP, detailing various form controls such as text boxes, radio buttons, and checkboxes. It explains the use of GET and POST methods for data submission, the importance of validation, and how to manage cookies and sessions. Additionally, it includes examples of handling multiple forms and submit buttons on a single webpage to enhance user experience.
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/ 26

Unit-IV Creating and validating forms

4a Use the relevant form controls to get user's input.


4b Design web pages using multiple Forms for the given problem.
4c Apply the given validation rules on form.
4d Set/modify/ delete cookies using cookies attributes.
4e Manage the given session using session variables.
Topics and Sub-topics
4.1 Creating a webpage using GUI Components, Browser Role-GET and POST methods,
Server Role
4.2 Form controls: text box, text area, radio button, check box, list, buttons
4.3 Working with multiple forms: - A web page having many forms - A form having multiple
submit buttons.
4.4 Web page validation.
4.5 Cookies-Use of cookies, Attributes of cookies, create cookies, modify cookies value, and
delete cookies.
4.6 Session Use of session, Start session, get session variables, destroy session.
4.7 Sending E-mail

4.0 INTRODUCTION

In today's web development landscape, PHP has become a standard due to its simplicity,
performance, reliability, flexibility, and speed. One of PHP's most powerful features is its
ability to handle HTML forms efficiently.

Forms play a crucial role in web applications as they enable user interaction and data
submission to the server for processing. They serve as a bridge between users and the web
server, allowing seamless communication. Figure 4.1 illustrates the form handling process.
An HTML form consists of a <form> tag that encloses various Graphical User Interface (GUI)
elements, such as text input fields, checkboxes, radio buttons, dropdown lists, and buttons. One
of the key advantages of using PHP for form handling is its ability to automatically recognize
and process form elements, making data collection and management more efficient.

The <form> tag is used to define a form, while individual GUI elements are specified using
form input elements, such as <input>, <select>, <textarea>, and <button>. These elements
allow users to enter data, which can then be sent to a PHP script for processing.

4.1 CREATING A WEBPAGE USING GUI COMPONENTS


A document that contains blank fields for users to fill in or select data is known as a form.
Generally, the data entered in a form is stored in a database. We can create and use forms in
PHP to collect user input. To retrieve form data, PHP provides superglobals $_GET and
$_POST. The form request can be either a GET or POST request:

 GET Method: Use $_GET to retrieve data from a GET request.


 POST Method: Use $_POST to retrieve data from a POST request.

4.1.1 Browser Role: GET and POST Methods

There are two primary HTTP methods that a client can use to send form data to a server: GET
and POST. The method is specified using the method attribute in the <form> tag.
1. GET Method

 The GET method sends the encoded user information as a part of the URL.
 Example URL: http://www.test.com/index.htm?name1=value1&name2=value2
 The GET method is limited to sending up to 1024 characters.
 Never use GET for passwords or sensitive information.
 GET cannot send binary data (such as images or files).
 Data sent via GET can be accessed using the QUERY_STRING environment variable.
 PHP provides the $_GET associative array to retrieve GET parameters.
Example: Using GET Method (test.php)
<?php
if(isset($_GET["s1"])) {
echo "Welcome " . $_GET['name'] . "<br />";
echo "You are " . $_GET['age'] . " years old.";
}
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
Name: <input type="text" name="name" /><br>
Age: <input type="text" name="age" /><br>
<input type="submit" name="s1" value="Ok"/>
</form>
</body>
</html>
 After submitting the form, the URL will look like:
 The isset() function checks if the "Ok" button was pressed.

2. POST Method

 The POST method transfers data via HTTP headers instead of the URL.
 No restrictions on data size.
 Can send ASCII as well as binary data.
 Data is accessed using $_POST.
 More secure than GET, especially when using HTTPS.

Example: Using POST Method (test.php)


<?php
if(isset($_POST["s1"])) {
echo "Welcome " . $_POST['name'] . "<br />";
echo "You are " . $_POST['age'] . " years old.";
}
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Name: <input type="text" name="name" /><br>
Age: <input type="text" name="age" /><br>
<input type="submit" name="s1" value="Ok"/>
</form>
</body>
</html>

 The output is the same as in the GET example, but the URL does not change after
submission.
GET vs. POST Methods

Feature GET POST

Visibility Visible in URL Hidden in HTTP Headers

Data Limit ~2000 characters No limit

Security Less secure More secure

Caching Can be cached Cannot be cached

Used for Queries, bookmarks Form submissions, secure data

When to Use GET?

 For non-sensitive data.


 If bookmarking the URL is beneficial.

When to Use POST?

 For sensitive information (e.g., passwords, personal data).


 When sending large amounts of data.
 When sending binary files.

4.1.2 Server Role

PHP is a server-side scripting language used to create dynamic web pages. PHP scripts
execute on the server, consuming server resources, and only the output is sent to the client.

Example: Server-Side Scripting with PHP


<html>
<head>
<title>Welcome to Our Web Site</title>
</head>
<body>
<h1>
<?php
if (date('G') < 12) {
echo "Good Morning!";
} else {
echo "Welcome!";
}
?>
</h1>
<p>Rest of the content goes here...</p>
</body>
</html>

 If the current time is before 12 PM, the page displays "Good Morning!".
 Otherwise, it displays "Welcome!”

4.2 FORM CONTROLS


There are different types of form controls that we can use to collect data using a form, namely
Textbox, Checkbox, Radio button, and so on.

4.2.1 Textbox
A text input field allows the user to enter a single line of text. A text box (input box), text field
(input field), or text entry box is a graphical control element intended to enable the user to input
text information to be used by the program.

Example: welcome.html
<html>
<body>
<form action="welcome.php" method="get">
<input type="text" name="user" />
<input type="submit" value="SUBMIT" />
</form>
</body>
</html>
welcome.php
<?php
echo "Welcome <b>" . $_GET['user'] . "</b><br/>";
?>
Output:

4.2.2 Textarea
A textarea field allows the user to enter multiple lines of text. Unlike most other controls, an
initial value is placed between the <textarea> tags rather than in a value attribute.

Example: textarea.html
<html>
<body>
<form action="textarea1.php" method="get">
<textarea name="address" rows="5" cols="40"></textarea>
<input type="submit" value="SUBMIT" />
</form>
</body>
</html>

textarea1.php
<?php
echo "Your address is: <br/><b>" . $_GET['address'] . "</b>";
?>
Output:
4.2.3 Radio Button
Radio buttons allow users to make a single choice from multiple options. All radio
buttons in a group share the same name attribute.

Example: radiobutton.html
<html>
<body>
<form action="radiobutton1.php" method="post">
<b>Please select your favorite color</b><br>
<input type="radio" name="color" value="Red"> Red <br>
<input type="radio" name="color" value="White"> White <br>
<input type="radio" name="color" value="Yellow"> Yellow <br>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>

radiobutton1.php
<?php
$color = $_POST['color'];
if (!empty($color)) {
echo $color . " is a nice color";
}
?>
Output:

4.2.4 Checkbox
Checkboxes allow users to select multiple options. The value attribute should contain
the value sent to the server when the checkbox is selected.

Example: checkbox.html
<html>
<head>
<title>Multiple Checkboxes</title>
</head>
<body>
<form action="checkbox.php" method="post">
<h4>Select your interested programming language:</h4>
<input type="checkbox" name="check_list[]" value="C/C++"> C/C++
<input type="checkbox" name="check_list[]" value="Java"> Java
<input type="checkbox" name="check_list[]" value="PHP"> PHP
<input type="checkbox" name="check_list[]" value="Perl"> Perl
<input type="checkbox" name="check_list[]" value="Python"> Python <br><br>
<input type="submit" name="submit" value="SUBMIT"/>
</form>
</body>
</html>

checkbox.php
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list'])) {
$checked_count = count($_POST['check_list']);
echo "You have selected the following " . $checked_count . " option(s): <br/>";
foreach ($_POST['check_list'] as $selected) {
echo "<p>" . $selected . "</p>";
}
} else {
echo "<b>Please Select At Least One Option.</b>";
}
}
?>
Output:
4.2.5 List
Lists allow users to select one or multiple items. A multi-select list allows users to
select multiple items by holding the Ctrl (Windows) or Command (Mac) key.

Example: listbox.html
<html>
<body>
<form action="listbox.php" method="post">
<p>
<select name="Transport[]" multiple="multiple">
<option>BUS</option>
<option>CAR</option>
<option>RAILWAY</option>
<option>AIRPLANE</option>
</select>
</p>
<p><input type="submit" value="SUBMIT" /></p>
</form>
</body>
</html>

listbox.php
<?php
if (isset($_POST['Transport'])) {
echo "<p>You have selected:</p><ul>";
foreach ($_POST['Transport'] as $value) {
echo "<li>" . $value . "</li>";
}
echo "</ul>";
}
?>
Output:
4.2.6 Buttons
Buttons are interactive components that enable users to perform actions. The <button>
element is used to create an HTML button.

Example: button_demo.html
<html>
<head><title>Button Demo</title></head>
<body>
<h4>How to call a PHP function on the click of a button?</h4>
<form method="post">
<input type="submit" name="button1" value="Button1" />
<input type="submit" name="button2" value="Button2" />
</form>
</body>
</html>

button_demo.php
<?php
if (isset($_POST['button1'])) {
echo "<h4>This is <u>Button1</u> that is selected</h4>";
} elseif (isset($_POST['button2'])) {
echo "<h4>This is <u>Button2</u> that is selected</h4>";
}
?>
Output:

4.3 WORKING WITH MULTIPLE FORMS


Processing form data in PHP is significantly simpler than most other Web programming
language. This simplicity and ease of use makes it possible to do some fairly complex things
with forma including handling multiple forms and multiple submit buttons in the same form.

4.3.1 Web Page Having Multiple Forms


To enhance efficiency and improve user experience, it is now possible to implement multiple
forms within a single web page. This approach helps reduce unnecessary page reloads,
minimizes wait times, and provides a smoother interaction flow. By using technologies like
AJAX, JavaScript, or modern front-end frameworks, forms can be submitted
asynchronously without requiring a full-page refresh.

This example demonstrates how to handle multiple forms on a single page in PHP.

<html>
<body>
<form name="mailinglist" method="post">
<fieldset>
<legend>Form 1:</legend>
<h4>Email: <input type="text" name="email" /></h4>
<input type="submit" name="mailing-submit" value="Add to mailing list" />
</fieldset>
</form>

<form name="contactus" method="post">


<fieldset>
<legend>Form 2:</legend>
<h4>Email: <input type="text" name="email" /></h4>
<h4>Subject: <input type="text" name="subject" /></h4>
<h4>Write message here:<textarea name="message"></textarea></h4>
<input type="submit" name="contact-submit" value="Send Email" />
</fieldset>
</form>

<?php
if (!empty($_POST["mailing-submit"])) {
echo "<h4>Form 1 is Calling</h4>";
}

if (!empty($_POST["contact-submit"])) {
echo "<h4>Form 2 is Calling</h4>";
}
?>
</body>
</html>

Output:
4.3.2 Form Having Multiple Submit Buttons
In an HTML form, you can have multiple submit buttons, and PHP can handle them by
checking which button was pressed. This is useful when you need to perform different actions
based on user input.

This example demonstrates how PHP handles multiple submit buttons in a single form.

:
<html>
<head><title>Button Demo</title></head>
<body>

<h4>Form Having Multiple Submit Buttons</h4>

<form method="post">
<input type="submit" name="btn_submit" value="Button 1" />
<input type="submit" name="btn_submit" value="Button 2" />
<input type="submit" name="btn_submit" value="Button 3" />
</form>

<?php
if (isset($_POST['btn_submit'])) {
switch ($_POST['btn_submit']) {
case "Button 1":
echo "<h4>You pressed Button 1</h4>";
break;
case "Button 2":
echo "<h4>You pressed Button 2</h4>";
break;
case "Button 3":
echo "<h4>You pressed Button 3</h4>";
break;
}
}
?>

</body>
</html>

Output:
4.4 Web Page Validation in PHP
Validation ensures that the input submitted by the user is correct and secure. There are two
types of validation in PHP:

1. Client-Side Validation:
o Performed on the user's web browser before data is sent to the server.
o Uses JavaScript, HTML5 attributes, or frameworks like jQuery for quick
feedback.
2. Server-Side Validation:
o Performed on the server after data is submitted.
o Uses PHP to validate and sanitize data, ensuring security and correctness.

Common Validation Rules for Form Fields

Sr. No Field Validation Rules


1 Name Must contain only letters and white spaces.
2 Email Must be a valid email format (e.g., [email protected]).
3 Website Must be a valid URL format (e.g., https://example.com).
4 Radio At least one option must be selected.
5 Checkbox At least one checkbox must be checked.
6 Dropdown At least one option must be selected from the list.

Example: For form validation.


<!DOCTYPE html>
<html>
<head>
<style>
.error { color: #FF0000; }
</style>
</head>
<body>

<?php
// Define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

// Function to sanitize input


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

// Check if form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Name validation
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 white space allowed";
}
}

// Email validation
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";
}
}

// Website validation
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
if (!filter_var($website, FILTER_VALIDATE_URL)) {
$websiteErr = "Invalid URL format";
}
}

// Comment (Optional)
if (!empty($_POST["comment"])) {
$comment = test_input($_POST["comment"]);
}

// Gender validation
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>

<h2>Somwanshi Sir Classes Registration Form</h2>


<p><span class="error">* Required field</span></p>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);


?>">
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" name="name" value="<?php echo $name; ?>">
<span class="error">* <?php echo $nameErr; ?></span>
</td>
</tr>
<tr>
<td>E-mail:</td>
<td>
<input type="text" name="email" value="<?php echo $email; ?>">
<span class="error">* <?php echo $emailErr; ?></span>
</td>
</tr>
<tr>
<td>Website:</td>
<td>
<input type="text" name="website" value="<?php echo $website; ?>">
<span class="error"><?php echo $websiteErr; ?></span>
</td>
</tr>
<tr>
<td>Comments:</td>
<td>
<textarea name="comment" rows="5" cols="40"><?php echo $comment;
?></textarea>
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type="radio" name="gender" value="female" <?php if ($gender == "female")
echo "checked"; ?>> Female
<input type="radio" name="gender" value="male" <?php if ($gender == "male")
echo "checked"; ?>> Male
<span class="error">* <?php echo $genderErr; ?></span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Submit">
</td>
</tr>
</table>
</form>

<?php
// Display input values after submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && empty($nameErr) &&
empty($emailErr) && empty($genderErr) && empty($websiteErr)) {
echo "<h4>Your given values are:</h4>";
echo "Name: $name <br>";
echo "Email: $email <br>";
echo "Website: $website <br>";
echo "Comment: $comment <br>";
echo "Gender: $gender <br>";
}
?>

</body>
</html>

Output:

4.5 COOKIES

A cookie is a small piece of data in the form of a name-value pair that is sent by a web server
and stored by the browser on the client machine. This information helps the server customize
web pages based on the user's past interactions.

A server can send one or more cookies to a browser in the response headers. The browser then
sends back these cookies with subsequent requests. Cookies store various types of information,
such as user identification codes, preferences, and session data.
PHP cookies are stored as text files in the client browser and are used to recognize users. They
are also known as web cookies, HTTP cookies, or browser cookies.

Cookies are created on the server side and saved in the client browser. When the client makes
a request, the cookie is sent along with the request to the server, allowing the server to retrieve
stored information.

4.5.1 Types of Cookies

1. Session Cookies
o Also called transient cookies.
o Erased when the web browser is closed.
o Stored in temporary memory and not retained after the session ends.
o Do not collect information from the computer.
o Used for temporary storage and expire when the session ends.
2. Persistent Cookies
o Also called permanent or stored cookies.
o Stored on the hard drive until they expire or are manually deleted.
o Used to collect user information like browsing behavior and preferences.
o Set with an expiration date to determine their lifespan.

4.5.2 Use of Cookies

Cookies help in identifying users and maintaining session data. Since HTTP is a stateless
protocol, cookies allow tracking user sessions using small files stored on the user's computer.

Common uses of cookies:

 Personalizing the user experience.


 Tracking visited pages.
 Storing user preferences.

To check if a cookie exists, the isset() function is used:


isset($_COOKIE['nameOfCookie']);
If the specified cookie exists, the function returns true; otherwise, it returns false.
4.5.3 Attributes of Cookies
The syntax for setting a cookie:
setcookie(name, value, expire, path, domain, secure, httponly);

Name: Name of the cookie, accessed using $_COOKIE.


Value: The value assigned to the cookie.
Expiry: UNIX timestamp indicating when the cookie expires.
Path: Defines the directories where the cookie is valid.
Domain: Specifies the domain where the cookie is valid.
Secure: Ensures cookies are sent only over HTTPS when set to true.
HttpOnly: Prevents access to cookies via JavaScript for security.

4.5.4 Creating Cookies

Example of creating a cookie:


<?php
$cookie_name = "Teacher";
$cookie_value = "Ravi";
setcookie($cookie_name, $cookie_value, time() + (86400 * 1), "/"); // Expires in 1 day
?>
<html>
<body>
<?php
if (!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Output:
4.5.5 Modifying Cookie Values

To modify a cookie, use setcookie() again with a new value.

<?php
$cookie_name = "Teacher";
$cookie_value = "Prashant";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>

Output:

4.5.6 Deleting Cookies

To delete a cookie, set its expiration time in the past:

<?php
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

Output:

Cookie 'user' is deleted.

Advantages of Cookies

1. Easy Implementation: Cookies are simple to use and supported by all browsers.
2. Reduced Server Load: Stored on the client-side, reducing the server's resource
consumption.
3. Domain-Specific: Cookies are restricted to specific domains, enhancing privacy.
4. Fast Access: Cookies speed up web interactions by remembering user data.
Disadvantages of Cookies

1. Security Risks: Cookies are stored as plain text and can be modified by users.
2. Limited Size: Each cookie is limited to 4KB, with a maximum of 20 cookies per
domain.
3. Can Be Disabled: Users can disable cookies in their browser settings.
4. Users Can Delete Cookies: This can prevent applications from functioning as
intended.

4.6 SESSION

A session is a way to store information (in variables) to be used across multiple pages. Sessions
allow us to store data on the web server associated with a session ID. Once a session is created,
PHP sends a cookie containing the session ID to the web browser.

In subsequent requests, the web browser sends the session ID cookie back to the web server so
that PHP can retrieve the data based on the session ID and make it available in our script.

An alternative way to make data accessible across multiple pages of an entire website is PHP
sessions. A session creates a file in a temporary directory on the server where registered session
variables and their values are stored. This data remains available to all pages during that visit.

The location of the temporary file is determined by a setting in the php.ini file called
session.save_path.

4.6.1 Use of Session

In general, a session refers to a communication frame between two mediums. A PHP session
stores data on a server rather than on the user's computer.

 Session Identifiers (SID): A unique number assigned to identify every user in a


session-based environment.
 Purpose of SID: It links the user to their information on the server (e.g., posts, emails,
etc.).
 Session Variables: Stored globally on the server and accessible across multiple pages.

When using an application, we open it, make changes, and close it. The application recognizes
our actions. However, on the internet, the web server does not maintain state due to the stateless
nature of HTTP.

Session variables solve this problem by storing user information across multiple pages (e.g.,
username, favorite color). A session lasts until the user closes the browser, holding information
for a single user and making it accessible across all pages within the application.

Why should a session be maintained?

 When a client continuously interacts with a server, the server cannot identify the client’s
requests because HTTP is stateless.
 Session tracking is needed to maintain a conversational state.
4.6.2 Start Session

A session is started with the session_start() function. It first checks if a session is already started;
if none is found, it starts a new session.

Session variables are set using the PHP global variable $_SESSION[]. These variables are
accessible throughout the session lifetime.

Example: Start a session in demo_session1.php.

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";

echo "Session variables are set.";


?>
</body>
</html>

Output:

Session variables are set.

Use the isset() function to check if a session variable is already set.

4.6.3 Get Session Variables

To retrieve session variables set in demo_session1.php, create another page demo_session2.php.

Example: Retrieve session variables.

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Retrieve session variables
echo "Favorite color is " . $_SESSION["favcolor"] . "<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>

Output:
Favorite color is green.
Favorite animal is cat.

4.6.4 Destroy Session

To remove all global session variables and destroy the session, use session_unset() and
session_destroy().

Example: Destroy session.

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Remove all session variables
session_unset();
// Destroy the session
session_destroy();
?>
</body>
</html>

4.6.5 Difference between Session and Cookie

Sr.
Cookie Session
No.
1 Stored in browser as text file. Stored on the server.
2 Client-side resource. Server-side resource.
Stores a limited amount of data
3 Stores an unlimited amount of data.
(4KB).
Cannot hold multiple variables
4 Can hold multiple variables.
efficiently.
5 Easily accessible, less secure. Not easily accessible, more secure.
6 Can expire at a set time. Destroyed using session_destroy().
setcookie() must appear before <html> session_start() must be the first thing in the
7
tag. document.
8 Linked to the user’s computer. Linked to the server.
4.7 SENDING E-MAIL IN PHP

Sending an email using PHP usually involves more complex information. To send an email,
we must configure the php.ini file with the details of how the system handles email
transmission.

Configuring php.ini

Open the php.ini file and locate the section titled [mail function]. Set the SMTP server and
sender email settings:

[mail function]
SMTP = smtp.my.server.net
sendmail_from = [email protected]

For Linux systems, the sendmail_path directive should be set to the location of the sendmail
application:

sendmail_path = /usr/sbin/sendmail -t -i

Using the mail() Function in PHP

PHP uses the mail() function to send emails. This function requires three mandatory
parameters:

1. Recipient's email address


2. Subject of the email
3. Message body

Additionally, there are two optional parameters for including headers and additional flags.

Syntax:
bool mail(string $to, string $subject, string $message [, string $headers [, string $parameters
]])
Parameter Descriptions:
Parameter Description

$to Required. Specifies the receiver's email address.

$subject Required. Specifies the subject of the email (no newline characters allowed).

Required. Defines the message body. Each line should be separated with \n,
$message
and lines should not exceed 70 characters.

Optional. Specifies additional headers like From, Cc, and Bcc, separated by
$headers
\r\n.

Optional. Additional flags used as command-line options for the program


$parameters
sending mail.
Return Values:
 Returns true if the mail is successfully sent.
 Returns false if it fails.

Example: Sending an Email in PHP

<?php
function sanitize_my_email($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}

$to_email = "[email protected]";
$subject = "Testing PHP Mail";
$message = "This mail is sent using the PHP mail function.";
$headers = "From: [email protected]";

// Validate email address


$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
echo "Invalid email address.";
} else {
// Send email
mail($to_email, $subject, $message, $headers);
echo "Email has been sent successfully.";
}
?>
Expected Output:
If the email is valid and successfully sent, it will output:
Email has been sent successfully.
Otherwise, it will output:
Invalid email address.

To configure XAMPP to send mail from localhost using PHP, follow these steps:

Step 1: Configure sendmail.ini

1. Navigate to C:\xampp\sendmail\
2. Open sendmail.ini using Notepad or any text editor.
3. Find and modify the following settings:

smtp_server=smtp.gmail.com
smtp_port=587
smtp_ssl=auto
[email protected]
auth_password=your-email-password
o Replace [email protected] with your Gmail address.
o Replace your-email-password with the actual app password (not your Gmail
password). You may need to generate an App Password in your Google
Account for security.

Step 2: Configure php.ini

1. Navigate to C:\xampp\php\
2. Open php.ini using Notepad or any text editor.
3. Locate the [mail function] section and update it as follows:

[mail function]
SMTP=smtp.gmail.com
smtp_port=587
[email protected]
sendmail_path="C:\xampp\sendmail\sendmail.exe -t"

Step 3: Restart Apache

 Go to the XAMPP Control Panel and restart Apache to apply the changes.

Step 4: Test the Mail Sending Function

Create a test PHP script (mail_test.php) and place it in C:\xampp\htdocs\:

<?php
$to = "[email protected]";
$subject = "Test Mail from Localhost";
$message = "This is a test email sent from XAMPP.";
$headers = "From: [email protected]";

if(mail($to, $subject, $message, $headers)) {


echo "Mail sent successfully.";
} else {
echo "Failed to send mail.";
}
?>

Run http://localhost/mail_test.php in your browser and check if the email is sent.

Troubleshooting:

 If you face authentication issues, enable Less Secure Apps or generate an App
Password in your Google Account.
 Check if your firewall or antivirus is blocking outgoing emails.
 Ensure that your internet connection is working properly.
Practice Questions:
1. What is a form, and how can you create it in HTML?
2. Define form control and list its types.
3. What is a cookie? How can you create it in PHP?
4. What is a session in PHP?
5. Explain the role of a server in web applications.
6. When should you use the GET and POST methods in form submission?
7. Describe how PHP maintains state using sessions and cookies.
8. Explain form validation with an example.
9. Write a PHP script to process a form that collects user input and displays it.
10. Demonstrate how to check whether a session variable is set.
11. How can you retrieve and delete cookie values in PHP?
12. Create an example demonstrating how to send an email using PHP.
13. Compare and contrast GET and POST methods in terms of security and data
handling.
14. Analyze different form controls and their uses in web forms.
15. Why is it important to validate user input before processing a form?
16. Evaluate the advantages and disadvantages of using cookies versus sessions
for state management.
17. Discuss the security risks involved in using cookies and how to mitigate them.
18. Why is form validation important for web security?
19. Develop a web page that includes multiple forms for different types of user
input.
20. Design a user authentication system using PHP sessions and cookies.
21. Implement a contact form that validates input and sends an email upon
submission.

You might also like