MilkCore

Sanitize
in package

Data Sanitization Class

This class handles data sanitization for output to prevent security vulnerabilities. Data is sanitized only when displayed, not when stored in the database.

FUNDAMENTAL RULE: Never sanitize data when saving to the database, only when displaying it! In the database, we store the original data and use prepared statements for security.

The sanitization functions protect against:

  • XSS (Cross-Site Scripting): Prevents injection and execution of malicious JavaScript
  • Code Injection: Prevents insertion of PHP or other language code
  • HTML Injection: Prevents insertion of malicious HTML tags
Tags
example
// Example: Display a user-entered message safely
echo "Message: ";
echo Sanitize::html($message); // Converts characters like < > " ' to HTML entities

// DANGEROUS (NEVER DO THIS):
echo $message; // Could execute malicious JavaScript!
see
ObjectToForm

For generating forms from object definitions

Table of Contents

Methods

html()  : string
Sanitizes HTML content while preserving safe HTML tags
input()  : string
Sanitizes input data based on its type

Methods

html()

Sanitizes HTML content while preserving safe HTML tags

public static html(string $html) : string

Use this method when you need to display HTML content but want to remove potentially harmful elements like JavaScript. This method removes script tags, event handlers, and JavaScript URIs while preserving safe HTML formatting.

Parameters
$html : string

The HTML input to sanitize

Tags
example
// Sanitize HTML content
$content = '<p>This is <strong>bold</strong> text.</p><script>alert("XSS");</script>';
$safe_html = Sanitize::html($content);
// Result: '<p>This is <strong>bold</strong> text.</p>'

// Dangerous attributes are also removed
$link = '<a href="javascript:alert(\'XSS\');">Click me</a>';
$safe_link = Sanitize::html($link);
// Result: '<a>Click me</a>'
Return values
string

The sanitized HTML output with harmful elements removed

input()

Sanitizes input data based on its type

public static input(mixed $input[, string $type = 'string' ]) : string

This method sanitizes input data according to the specified type and escapes special characters to prevent XSS attacks. It's the primary method used by the helper functions in functions.php.

Parameters
$input : mixed

The input data to sanitize

$type : string = 'string'

The type of data ('string', 'email', 'url', 'int', 'float', 'html')

Tags
example
// Sanitize a string
$safe_text = Sanitize::input($user_input);

// Sanitize an email address
$safe_email = Sanitize::input($email, 'email');

// Sanitize a URL
$safe_url = Sanitize::input($url, 'url');

// Sanitize an integer
$safe_id = Sanitize::input($id, 'int');
Return values
string

The sanitized output


        
On this page

Search results