Cyber Security /Web Security Fundamentals / Lesson
Cyber Security

Input Validation

Learn how secure web applications validate, normalize and safely process user-supplied data while preventing injection, cross-site scripting, unsafe file handling and other input-related security problems.

🎯

Learning Objectives

["Understand why user input must be treated as untrusted data.","Understand the difference between validation, sanitization and escaping.","Apply allowlist validation principles.","Understand type, length, range and format validation.","Understand server-side validation.","Understand normalization and canonicalization.","Understand context-specific output encoding.","Understand SQL injection prevention using prepared statements.","Understand cross-site scripting prevention.","Understand secure file-upload validation.","Understand URL, email, IP and JSON validation.","Understand business-rule validation.","Understand mass-assignment risks.","Understand Unicode and canonicalization concerns.","Apply safe input-validation practices in PHP and WordPress."]

📖

Lesson Content

Introduction to Input Validation

Input validation is the process of checking data before an application
accepts, stores, processes or displays it.

Web applications receive information from many sources, including:

  • HTML forms.
  • URL parameters.
  • Cookies.
  • HTTP headers.
  • JSON APIs.
  • Uploaded files.
  • Mobile applications.
  • Other servers and external services.
  • Database records.

A fundamental cybersecurity principle is:

Never automatically trust data simply because it came from a browser,
another application or a previously used source.

Input validation helps an application determine whether received data is
acceptable for the intended operation.

1. Why Input Validation Matters

Applications frequently make decisions based on user-supplied information.
If that information is not handled safely, attackers may be able to cause
unexpected behavior.

Poor input handling can contribute to vulnerabilities such as:

  • SQL injection.
  • Cross-site scripting.
  • Command injection.
  • Path traversal.
  • Unsafe file uploads.
  • Authentication problems.
  • Broken business logic.
  • Data corruption.

2. Trusted and Untrusted Input

A common mistake is assuming that input is safe because it came from the
application’s own interface.

For example, a developer might create a form containing:

<input type="number" name="age">

The browser may display a number field, but an attacker can send a custom
HTTP request that does not follow the expected interface.

Therefore, server-side validation is essential.

3. Client-Side Validation

Client-side validation happens in the browser.

Examples include:

  • HTML input types.
  • JavaScript validation.
  • Required fields.
  • Minimum and maximum values.

Client-side validation is useful for user experience because it can provide
immediate feedback.

However, it is not a sufficient security control.

4. Server-Side Validation

Server-side validation occurs after data reaches the application server.

This is the authoritative validation layer for security-sensitive operations.

For example:

<?php

$age = filter_input(
	INPUT_POST,
	'age',
	FILTER_VALIDATE_INT
);

if ( false === $age || null === $age ) {

	echo 'Invalid age.';

} else {

	echo 'Valid age.';
}

The server should reject data that does not satisfy the application’s
requirements.

5. Allowlist Validation

Allowlist validation defines what is acceptable rather than attempting to
list every possible malicious value.

For example, if an application expects a course status, it could permit:

draft
published
archived

Values outside that defined set should be rejected.

This is generally easier to reason about than attempting to identify every
possible invalid value.

6. Denylist Validation

Denylist validation attempts to identify values that should not be accepted.

For example, a developer might attempt to block a small set of suspicious
characters or words.

Denylisting can be useful as an additional defensive layer, but it should
not normally be the primary security mechanism because attackers may find
alternative representations.

7. Type Validation

The application should verify that data has the expected type.

Examples:

  • An age should be an integer.
  • A price should be a valid numeric value.
  • A Boolean option should contain an expected Boolean representation.
  • An email address should have an appropriate email structure.
  • An IP address should be a valid IP address.

8. Length Validation

Applications should define reasonable limits for text input.

For example, a username might have a maximum length such as 50 characters,
depending on the application’s requirements.

Length limits can help:

  • Prevent malformed data.
  • Reduce accidental database errors.
  • Reduce unnecessary resource consumption.
  • Make application behavior predictable.

9. Range Validation

Numeric values should be checked against meaningful boundaries.

For example, if a training course accepts a rating from 1 to 5:

1
2
3
4
5

A value such as 900 should not be accepted simply because it is technically
a valid integer.

10. Format Validation

Some fields require a specific format.

Examples include:

  • Email addresses.
  • Phone numbers.
  • Dates.
  • IP addresses.
  • UUIDs.
  • Postcodes.
  • Course identifiers.

Format validation should match the actual business requirement rather than
being unnecessarily restrictive.

11. Validation vs Sanitization vs Escaping

These concepts are related but are not interchangeable.

TechniquePurpose
ValidationDetermines whether input meets expected requirements.
SanitizationCleans or transforms data according to a specific purpose.
EscapingEncodes data for a particular output context.

A common security mistake is assuming that sanitization automatically makes
data safe for every context.

12. Output Encoding

Input validation does not replace output encoding.

Suppose an application accepts a person’s display name and later inserts it
into HTML.

The application should escape the value for HTML output.

<?php

$name = 'Student Example';

echo esc_html( $name );

The correct escaping method depends on where the data is being used.

13. Context-Specific Escaping

Different output contexts require different handling.

  • HTML text.
  • HTML attributes.
  • URLs.
  • JavaScript.
  • CSS.
  • SQL queries.

For example, WordPress provides functions such as:

esc_html()
esc_attr()
esc_url()
esc_js()

Developers should select the function appropriate to the output context.

14. SQL Injection Prevention

SQL injection occurs when untrusted data is incorrectly incorporated into a
database query.

The safest general approach is to use parameterized or prepared queries
provided by the database library.

In WordPress, developers can use $wpdb->prepare().

<?php

global $wpdb;

$user_id = 25;

$user = $wpdb->get_row(
	$wpdb->prepare(
		"SELECT *
		FROM {$wpdb->users}
		WHERE ID = %d",
		$user_id
	)
);

The value is supplied separately from the SQL statement.

15. Never Build SQL by String Concatenation

Developers should avoid constructing SQL queries by directly concatenating
untrusted input.

Conceptually unsafe code looks like:

$query = "SELECT * FROM users WHERE id = " . $user_input;

The correct implementation depends on the database API, but parameterized
queries should be preferred.

16. Cross-Site Scripting

Cross-site scripting, commonly called XSS, can occur when untrusted data is
included in web content without appropriate output handling.

Three broad categories often discussed are:

  • Stored XSS.
  • Reflected XSS.
  • DOM-based XSS.

Defensive measures include:

  • Validate input where appropriate.
  • Escape output according to context.
  • Use secure templating practices.
  • Apply an appropriate Content Security Policy where practical.

17. Input Validation Does Not Replace Escaping

Consider a display name field.

A developer may validate that the value is not empty and is below a maximum
length.

That does not automatically make it safe for every output context.

If the value is displayed in HTML, appropriate HTML escaping should still
be applied.

18. File Upload Validation

File uploads require special attention because an uploaded file may contain
unexpected content.

Applications should consider:

  • Allowed file types.
  • File size limits.
  • File extension.
  • Actual file type.
  • Storage location.
  • Generated filenames.
  • Executable-file restrictions.
  • Authentication and authorization.
  • Malware scanning where appropriate.

An extension alone should not be treated as proof that a file is safe.

19. File Names

Applications should avoid trusting uploaded filenames.

A safer design can generate its own internal filename rather than using the
original filename as the storage identity.

This can reduce problems involving unexpected characters, path manipulation
and filename collisions.

20. Path Traversal

Path traversal refers to attempts to access files outside the intended
directory or resource boundary.

Applications should not assume that a filename supplied by a user refers to
a safe location.

Defensive approaches include:

  • Allowlisting expected resource identifiers.
  • Using safe application-managed identifiers.
  • Restricting storage directories.
  • Canonicalizing paths where appropriate.
  • Checking that the final resolved path remains within the permitted directory.

21. URL Validation

URLs received by an application should be validated according to their
intended use.

For example, if an application accepts a website URL, it may need to verify:

  • Valid URL syntax.
  • Allowed protocols.
  • Allowed domains where appropriate.
  • Expected port restrictions.

URL validation is especially important when the application will later make
server-side requests to a supplied URL.

22. Email Validation

PHP provides a basic email validation filter:

<?php

$email = 'student@example.com';

if ( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {

	echo 'Valid email format.';

} else {

	echo 'Invalid email format.';
}

Validation confirms the format. It does not prove that the mailbox exists or
that the person controls it.

23. IP Address Validation

PHP can also validate IP addresses.

<?php

$ip = '192.168.1.20';

if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) {

	echo 'Valid IP address.';

} else {

	echo 'Invalid IP address.';
}

24. JSON Validation

Modern APIs frequently receive JSON.

The application should verify:

  • Valid JSON syntax.
  • Expected data types.
  • Required fields.
  • Allowed values.
  • Maximum sizes.
  • Business rules.

Valid JSON does not automatically mean valid application data.

25. Business-Rule Validation

Technical validation alone is not enough.

Applications must also validate whether the requested operation makes sense
according to business rules.

For example:

Course capacity = 30
Current enrollment = 30

A request to enroll another student may be syntactically valid but still
violate the application’s business rules.

26. Mass Assignment

Mass assignment occurs when an application automatically accepts too many
fields from user input and maps them directly into an internal object or
database record.

For example, a profile update form may legitimately accept:

display_name
phone
bio

But the application should not automatically allow a user to submit
sensitive fields such as:

role
account_status
is_admin

unless the user has explicit permission to modify them.

Allowlisting accepted fields is a strong defensive approach.

27. Canonicalization

Canonicalization means converting data into a standard representation before
making security decisions.

This matters because the same logical value may sometimes have multiple
representations.

Security-sensitive validation should be performed on the representation
that will actually be used by the application.

28. Unicode Considerations

Modern applications handle international text and Unicode.

Developers should consider:

  • Unicode normalization.
  • Case sensitivity.
  • Character length.
  • Confusable characters.
  • Encoding consistency.

This is particularly important for usernames, domains, identifiers and
security-sensitive comparisons.

29. Input Validation and APIs

API endpoints should validate every request according to the API contract.

For example, a course-creation endpoint might require:

{
	"title": "Web Development",
	"duration_months": 6,
	"published": false
}

The server should verify the type, structure, allowed fields and business
rules before processing the request.

30. Input Validation and Authentication

Authentication endpoints also require input validation.

Examples include:

  • Username format.
  • Email format.
  • Password length.
  • Verification-code format.
  • Reset-token structure.

Validation does not replace secure password hashing, MFA or rate limiting.
It is one layer of the overall security design.

31. WordPress Input Validation

WordPress developers should use appropriate sanitization, validation and
escaping functions depending on the purpose of the data.

Common functions include:

  • sanitize_text_field()
  • sanitize_email()
  • sanitize_key()
  • absint()
  • esc_html()
  • esc_attr()
  • esc_url()

These functions do not mean the same thing and should not be used
interchangeably.

32. WordPress Database Validation

When values are used in database queries, developers should use appropriate
database APIs and prepared statements.

<?php

global $wpdb;

$course_id = absint( $_POST['course_id'] ?? 0 );

$course = $wpdb->get_row(
	$wpdb->prepare(
		"SELECT *
		FROM {$wpdb->prefix}dwallnet_courses
		WHERE id = %d",
		$course_id
	)
);

The value is converted to an integer and then supplied through the prepared
query.

33. Secure Form Processing

A secure form-processing flow can include:

  1. Verify the request context.
  2. Verify the user’s authorization.
  3. Retrieve submitted data.
  4. Validate the data.
  5. Normalize it where appropriate.
  6. Perform business-rule checks.
  7. Store it safely.
  8. Escape it when displayed later.

This layered approach is much stronger than relying on one security function.

34. Example: Allowlist Validation

<?php

$allowed_statuses = array(
	'draft',
	'published',
	'archived',
);

$status = isset( $_POST['status'] )
	? sanitize_key( wp_unslash( $_POST['status'] ) )
	: '';

if ( ! in_array( $status, $allowed_statuses, true ) ) {

	echo 'Invalid status.';

} else {

	echo 'Accepted status: ' . esc_html( $status );
}

35. Example: Numeric Validation

<?php

$course_id = filter_input(
	INPUT_POST,
	'course_id',
	FILTER_VALIDATE_INT
);

if (
	false === $course_id
	|| null === $course_id
	|| $course_id <= 0
) {

	echo 'Invalid course ID.';

} else {

	echo 'Valid course ID: ' . (int) $course_id;
}

36. Example: String Length Validation

<?php

$title = isset( $_POST['title'] )
	? trim( wp_unslash( $_POST['title'] ) )
	: '';

if ( '' === $title ) {

	echo 'Title is required.';

} elseif ( mb_strlen( $title ) > 100 ) {

	echo 'Title is too long.';

} else {

	echo 'Title accepted.';
}

37. Validation of Uploaded Files

When accepting uploads, the application should define an explicit policy.

For example, a training platform might permit only:

  • PDF documents.
  • JPEG images.
  • PNG images.

It should also enforce:

  • Maximum file size.
  • Allowed MIME types.
  • Safe storage.
  • Authentication and authorization.
  • Appropriate filename handling.

38. Input Validation and Security Headers

Input validation is one part of web security and should work alongside other
controls.

Additional defenses can include:

  • Content Security Policy.
  • Secure cookies.
  • CSRF protection.
  • HTTPS.
  • Access control.
  • Authentication.
  • Security logging.

39. Common Input-Handling Mistakes

  • Trusting client-side validation.
  • Using denylisting as the only security mechanism.
  • Failing to validate data types.
  • Failing to enforce length limits.
  • Building SQL queries through string concatenation.
  • Using the same sanitization method for every output context.
  • Trusting file extensions.
  • Allowing users to modify security-sensitive fields.
  • Failing to apply authorization before processing input.
  • Assuming valid JSON means valid application data.
  • Failing to apply business-rule validation.

40. Defense in Depth

Input validation should be treated as one layer of a broader security model.

A secure application may combine:

Authentication
      ↓
Authorization
      ↓
Input Validation
      ↓
Business Rules
      ↓
Safe Database Access
      ↓
Output Encoding
      ↓
Logging and Monitoring

No individual layer should be expected to solve every security problem.

41. Practical Cybersecurity Lab

Create a small local registration form containing:

  • Name.
  • Email.
  • Age.
  • Course status.
  • Profile description.

Implement server-side validation for:

  1. Required fields.
  2. Email format.
  3. Age range.
  4. Maximum description length.
  5. Allowlisted course status.
  6. Safe HTML output.

Then store the validated data in a local development database using
parameterized queries.

Perform the exercise only on systems and accounts you own or have explicit
permission to test.

42. Security Review Scenario

Imagine a Dwallnet LMS form that accepts a course ID from the browser.

The application should not assume that:

course_id = 15

is valid simply because the value came from the course page.

The server should:

  1. Validate that the value is a valid integer.
  2. Confirm that the course exists.
  3. Check whether the current user is authorized to interact with it.
  4. Apply any relevant business rules.
  5. Use a prepared database query.

43. Input Validation Checklist

  • Is the input source identified?
  • Is the data considered untrusted?
  • Is validation performed on the server?
  • Is the data type correct?
  • Is the length acceptable?
  • Is the value within an allowed range?
  • Is the format correct?
  • Are allowed values explicitly defined?
  • Are business rules enforced?
  • Are security-sensitive fields protected?
  • Are database queries parameterized?
  • Is output escaped for its actual context?
  • Are uploaded files handled safely?
  • Are authorization checks performed?

44. Key Takeaways

  • All external input should be treated as untrusted.
  • Server-side validation is essential.
  • Allowlisting is often safer than trying to block every bad value.
  • Validation, sanitization and escaping serve different purposes.
  • Output must be encoded according to its context.
  • Prepared statements help prevent SQL injection.
  • File uploads require multiple layers of validation.
  • Business-rule validation is as important as technical validation.
  • Security-sensitive fields should not be accepted through uncontrolled mass assignment.
  • Canonicalization can help ensure security decisions are made on the correct representation.
  • Input validation works together with authentication and authorization.
  • WordPress developers should use the appropriate validation, sanitization and escaping functions.

45. Review Questions

  1. What is input validation?
  2. Why should client-side validation not be trusted as the primary security control?
  3. What is allowlist validation?
  4. What is denylist validation?
  5. What is the difference between validation and sanitization?
  6. What is output escaping?
  7. Why are prepared statements important?
  8. What is cross-site scripting?
  9. Why do file uploads require special validation?
  10. What is path traversal?
  11. What is mass assignment?
  12. Why is server-side validation necessary?
  13. What is business-rule validation?
  14. Why does context-specific escaping matter?
  15. How does WordPress help developers safely process output?

Conclusion

Input validation is a fundamental part of secure web development. A
professional application should never assume that information supplied by a
browser, API client or external system is trustworthy.

Developers should validate data on the server, apply business rules,
parameterize database queries, handle uploads carefully and escape output
according to its context.

The next lesson will examine Secure Passwords and how
applications should securely create, store and verify password credentials.

💻

Code Example

<?php

$allowed_statuses = array(
	'draft',
	'published',
	'archived',
);

$status = isset( $_POST['status'] )
	? sanitize_key( wp_unslash( $_POST['status'] ) )
	: '';

if ( ! in_array( $status, $allowed_statuses, true ) ) {

	echo 'Invalid status.';

} else {

	echo 'Accepted status: ' . esc_html( $status );
}
⭐

Key Takeaways

["All external input should be treated as untrusted.","Server-side validation is essential.","Allowlisting is often safer than trying to block every bad value.","Validation, sanitization and escaping serve different purposes.","Output must be encoded according to its context.","Prepared statements help prevent SQL injection.","File uploads require multiple layers of validation.","Business-rule validation is important.","Security-sensitive fields should not be accepted through uncontrolled mass assignment.","Canonicalization can help ensure security decisions use the correct representation.","Input validation works together with authentication and authorization.","WordPress developers should use appropriate validation, sanitization and escaping functions."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress