TY CO PHP Unit 04
TY CO PHP Unit 04
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.
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.
The output is the same as in the GET example, but the URL does not change after
submission.
GET vs. POST Methods
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.
If the current time is before 12 PM, the page displays "Good Morning!".
Otherwise, it displays "Welcome!”
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:
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>
<?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>
<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.
<?php
// Define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
// 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"]);
}
}
?>
<?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.
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.
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.
Output:
4.5.5 Modifying Cookie Values
<?php
$cookie_name = "Teacher";
$cookie_value = "Prashant";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
Output:
<?php
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Output:
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.
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.
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.
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.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
Output:
<?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.
To remove all global session variables and destroy the session, use session_unset() and
session_destroy().
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Remove all session variables
session_unset();
// Destroy the session
session_destroy();
?>
</body>
</html>
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
PHP uses the mail() function to send emails. This function requires three mandatory
parameters:
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
$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.
<?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]";
To configure XAMPP to send mail from localhost using PHP, follow these steps:
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.
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"
Go to the XAMPP Control Panel and restart Apache to apply the changes.
<?php
$to = "[email protected]";
$subject = "Test Mail from Localhost";
$message = "This is a test email sent from XAMPP.";
$headers = "From: [email protected]";
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.