Introduction
Data sanitization and safe output are important parts of PHP security. They help developers handle user input safely and prevent problems such as unwanted characters, HTML injection, and Cross-Site Scripting (XSS). In this chapter, you will practise sanitizing names, emails, URLs, numbers, and displaying user-submitted data safely using practical PHP examples. Data Sanitization and Safe Output in PHP Practice Questions with Solutions to help you to understand the concepts.
Question 1: Remove Unnecessary Spaces Using trim()
Problem Statement
A student enters their name with extra spaces. Create a PHP program that removes spaces from the beginning and end of the name.
PHP Solution
<?php
$name = " Rahul Sharma ";
$cleanName = trim($name);
echo "Original Name: [" . $name . "]<br>";
echo "Clean Name: [" . $cleanName . "]";
?>
Sample Output
Original Name: [ Rahul Sharma ]
Clean Name: [Rahul Sharma]
Explanation
trim()removes whitespace from the beginning and end of a string.- It does not remove spaces between words.
- It is useful for cleaning names and other text inputs.
Concepts Covered
- Data sanitization
trim()- Removing unnecessary spaces
Question 2: Remove HTML Tags Using strip_tags()
Problem Statement
A user submits text containing HTML tags. Create a PHP program that removes HTML tags before displaying the text.
PHP Solution
<?php
$message = "<h2>Welcome to PHP</h2>";
$cleanMessage = strip_tags($message);
echo $cleanMessage;
?>
Sample Output
Welcome to PHP
Explanation
strip_tags()removes HTML and PHP tags from a string.- The remaining text is displayed without the HTML formatting.
- It can help when an application accepts plain text instead of HTML.
Important: strip_tags() is not a replacement for output escaping. Always use htmlspecialchars() when displaying untrusted text in HTML.
Concepts Covered
strip_tags()- Removing HTML tags
- Text sanitization
Question 3: Display User Input Safely Using htmlspecialchars()
Problem Statement
A user enters text containing HTML characters. Create a PHP program that displays the text safely without allowing the browser to interpret it as HTML.
PHP Solution
<?php
$message = "<h2>Hello PHP</h2>";
$safeMessage = htmlspecialchars(
$message,
ENT_QUOTES,
"UTF-8"
);
echo $safeMessage;
?>
Sample Output
&lt;h2&gt;Hello PHP&lt;/h2&gt;
The browser displays the original text:
<h2>Hello PHP</h2>
It does not create an actual heading.
Explanation
htmlspecialchars()converts special HTML characters into HTML entities.<becomes<.>becomes>.ENT_QUOTESalso converts single and double quotes.UTF-8specifies the character encoding.
This is one of the most important functions for preventing HTML-based XSS when displaying untrusted text inside HTML.
Concepts Covered
- Safe output
htmlspecialchars()- HTML entities
- XSS prevention
Question 4: Sanitize an Email Address Using filter_var()
Problem Statement
A user enters an email address with unnecessary spaces. Create a PHP program that cleans the input and checks whether it is a valid email address.
PHP Solution
<?php
$email = " rahul@gmail.com ";
$cleanEmail = trim($email);
if (filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email: " . htmlspecialchars($cleanEmail);
} else {
echo "Invalid Email Address.";
}
?>
Sample Output
Valid Email: rahul@gmail.com
Explanation
trim()removes unnecessary surrounding spaces.filter_var()checks the email format.FILTER_VALIDATE_EMAILvalidates the email address.htmlspecialchars()safely displays the result.
Remember: FILTER_VALIDATE_EMAIL validates an email’s format. It does not prove that the email address actually exists.
Concepts Covered
- Email sanitization
trim()filter_var()- Email validation
Question 5: Sanitize a URL Using filter_var()
Problem Statement
A user submits a website URL. Create a PHP program that removes unwanted characters and checks whether the URL is valid.
PHP Solution
<?php
$website = "https://www.example.com";
$cleanWebsite = filter_var(
$website,
FILTER_SANITIZE_URL
);
if (filter_var($cleanWebsite, FILTER_VALIDATE_URL)) {
echo "Valid Website: " . htmlspecialchars($cleanWebsite);
} else {
echo "Invalid Website URL.";
}
?>
Sample Output
Valid Website: https://www.example.com
Explanation
FILTER_SANITIZE_URLremoves characters that are not permitted by its sanitization filter.FILTER_VALIDATE_URLchecks whether the cleaned value has a valid URL format.htmlspecialchars()safely displays the URL in HTML.
Important: A syntactically valid URL is not automatically safe to visit or use. Applications should also check permitted schemes and destinations when handling links.
Concepts Covered
- URL sanitization
FILTER_SANITIZE_URL- URL validation
- Safe output
Question 6: Remove HTML and Special Characters from a Text Input
Problem Statement
A user submits a comment containing HTML tags and unwanted characters. Create a PHP program that removes HTML tags and trims unnecessary spaces.
PHP Solution
<?php
$comment = " <b>PHP is easy!</b> ";
$cleanComment = trim(strip_tags($comment));
echo "Clean Comment: " . htmlspecialchars(
$cleanComment,
ENT_QUOTES,
"UTF-8"
);
?>
Sample Output
Clean Comment: PHP is easy!
Explanation
strip_tags()removes HTML tags.trim()removes unnecessary spaces from both ends.htmlspecialchars()safely displays the cleaned text.- These functions perform different tasks and can be used together.
Concepts Covered
- Text cleaning
strip_tags()trim()htmlspecialchars()
Question 7: Sanitize and Validate an Integer
Problem Statement
A student enters their age as text. Create a PHP program that removes unnecessary surrounding whitespace and checks whether the value is a valid integer.
PHP Solution
<?php
$age = " 25 ";
$cleanAge = trim($age);
$validAge = filter_var(
$cleanAge,
FILTER_VALIDATE_INT
);
if ($validAge !== false) {
echo "Valid Age: " . $validAge;
} else {
echo "Please enter a valid integer.";
}
?>
Sample Output
Valid Age: 25
Explanation
trim()removes surrounding whitespace.FILTER_VALIDATE_INTchecks whether the value is a valid integer.!== falseis important because zero is a valid integer and should not be mistaken for a validation failure.
Concepts Covered
- Integer sanitization
- Integer validation
filter_var()- Strict comparison
Question 8: Safely Display Multiple Student Records
Problem Statement
A PHP program stores multiple student names in an array. Display all student names safely, including names containing special HTML characters.
PHP Solution
<?php
$students = [
"Rahul Sharma",
"Amit Kumar",
"<script>alert('Test')</script>"
];
foreach ($students as $student) {
echo htmlspecialchars(
$student,
ENT_QUOTES,
"UTF-8"
) . "<br>";
}
?>
Sample Output
Rahul Sharma
Amit Kumar
<script>alert('Test')</script>
The third line appears as text in the browser. The script does not execute.
Explanation
- The
$studentsarray stores multiple student names. foreach()processes each name.htmlspecialchars()escapes special HTML characters before displaying each value.- This prevents untrusted text from being interpreted as executable HTML or JavaScript.
Concepts Covered
- Array output
foreach()- Safe HTML output
- XSS prevention
Question 9: Sanitize Form Data Before Displaying It
Problem Statement
An employee submits their name, email, and message. Create a PHP program that cleans the submitted values and displays them safely.
PHP Solution
<?php
$name = " Amit Sharma ";
$email = " amit@gmail.com ";
$message = " I want to learn PHP. ";
// Clean submitted values
$cleanName = trim($name);
$cleanEmail = trim($email);
$cleanMessage = trim($message);
// Validate email
if (!filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email address.";
} else {
echo "<h3>Employee Details</h3>";
echo "Name: " .
htmlspecialchars($cleanName, ENT_QUOTES, "UTF-8") .
"<br>";
echo "Email: " .
htmlspecialchars($cleanEmail, ENT_QUOTES, "UTF-8") .
"<br>";
echo "Message: " .
htmlspecialchars($cleanMessage, ENT_QUOTES, "UTF-8");
}
?>
Sample Output
Employee Details
Name: Amit Sharma
Email: amit@gmail.com
Message: I want to learn PHP.
Explanation
trim()cleans the submitted text.filter_var()checks the email format.htmlspecialchars()safely displays all three values.- Each value is handled according to its purpose: cleaning, validation, or output escaping.
Concepts Covered
- Multiple input sanitization
- Email validation
- Safe output
- Employee data handling
Question 10: Build a Complete Safe Student Data Display System
Problem Statement
Create a PHP program that accepts student details through sample variables, cleans the input, validates the email and age, and displays the information safely.
PHP Solution
<?php
// Sample submitted data
$name = " Rahul Sharma ";
$email = " rahul@gmail.com ";
$age = " 20 ";
$course = "<b>PHP Development</b>";
// Clean input
$cleanName = trim($name);
$cleanEmail = trim($email);
$cleanAge = trim($age);
$cleanCourse = trim(strip_tags($course));
// Validate data
$errors = [];
if ($cleanName === "") {
$errors[] = "Student name is required.";
}
if (!filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email address.";
}
$validAge = filter_var($cleanAge, FILTER_VALIDATE_INT);
if ($validAge === false || $validAge < 1 || $validAge > 100) {
$errors[] = "Enter a valid age between 1 and 100.";
}
if ($cleanCourse === "") {
$errors[] = "Course name is required.";
}
// Display result
if (empty($errors)) {
echo "<h3>Student Registration Details</h3>";
echo "Name: " .
htmlspecialchars($cleanName, ENT_QUOTES, "UTF-8") .
"<br>";
echo "Email: " .
htmlspecialchars($cleanEmail, ENT_QUOTES, "UTF-8") .
"<br>";
echo "Age: " . $validAge . "<br>";
echo "Course: " .
htmlspecialchars($cleanCourse, ENT_QUOTES, "UTF-8");
} else {
echo "<h3>Validation Errors</h3>";
foreach ($errors as $error) {
echo htmlspecialchars($error, ENT_QUOTES, "UTF-8") . "<br>";
}
}
?>
Sample Output
Student Registration Details
Name: Rahul Sharma
Email: rahul@gmail.com
Age: 20
Course: PHP Development
Explanation
- The program receives sample student information.
trim()removes unnecessary surrounding spaces.strip_tags()removes HTML tags from the course name.filter_var()validates the email and age.- The
$errorsarray stores validation messages. htmlspecialchars()safely displays student details and error messages.- Registration details appear only when all validations pass.
Concepts Covered
- Data sanitization
- Input validation
- Safe output
- Error handling
- Array processing
- XSS prevention
Key Takeaways
- Sanitization cleans or transforms input data.
- Validation checks whether data meets required rules.
trim()removes surrounding whitespace.strip_tags()removes HTML and PHP tags.htmlspecialchars()safely displays untrusted text in HTML.filter_var()provides sanitization and validation filters.FILTER_VALIDATE_EMAILchecks email format.FILTER_VALIDATE_INTchecks integer values.FILTER_SANITIZE_URLcleans URL input.- Never assume that user-submitted data is safe.
Frequently Asked Questions (FAQs)
1. What is data sanitization in PHP?
Data sanitization is the process of cleaning or transforming input data before using it in an application.
2. What is the difference between sanitization and validation?
Sanitization modifies or cleans data, while validation checks whether data follows the required rules.
3. What is htmlspecialchars() in PHP?
htmlspecialchars() converts special HTML characters into HTML entities so that untrusted text is displayed as text instead of being interpreted as HTML.
4. What is the purpose of strip_tags()?
strip_tags() removes HTML and PHP tags from a string. It is useful when an application should accept plain text instead of HTML.
5. What is the difference between trim() and strip_tags()?
trim() removes whitespace from the beginning and end of a string, while strip_tags() removes HTML and PHP tags.
6. What is XSS in PHP?
Cross-Site Scripting (XSS) is a security vulnerability in which malicious scripts are injected into a webpage and executed in another user’s browser.
7. Does htmlspecialchars() prevent all types of security attacks?
No. It is designed for escaping text in HTML contexts. Other contexts, such as JavaScript, CSS, URLs, SQL, and HTML attributes, require appropriate context-specific protections.
8. Does sanitization replace input validation?
No. Sanitization and validation solve different problems. Applications should use both where appropriate.
9. Should we sanitize data before storing it in a database?
Data should be validated and normalized according to the application’s requirements. Use prepared statements with PDO or MySQLi to prevent SQL injection instead of trying to sanitize SQL input manually.
10. Why should we use UTF-8 with htmlspecialchars()?
UTF-8 supports a wide range of characters and provides consistent character encoding when escaping text for HTML output.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
