0
0
Wordpressframework~5 mins

Data sanitization in Wordpress

Choose your learning style9 modes available
Introduction

Data sanitization helps keep your website safe by cleaning user input. It removes harmful or unwanted parts before saving or using the data.

When accepting user input from forms like comments or contact pages.
Before saving data to the database to avoid security risks.
When displaying user input on the website to prevent harmful code from running.
When processing data from external sources to ensure it is safe.
Before sending data to other systems or APIs to avoid errors or attacks.
Syntax
Wordpress
<?php
$clean_data = sanitize_text_field( $dirty_data );
?>

sanitize_text_field() is a common WordPress function to clean simple text input.

There are many other sanitization functions for different data types, like emails, URLs, or HTML.

Examples
Sanitize a simple text field from a form submission.
Wordpress
<?php
$clean_name = sanitize_text_field( $_POST['name'] );
?>
Sanitize an email address to ensure it is valid and safe.
Wordpress
<?php
$clean_email = sanitize_email( $_POST['email'] );
?>
Sanitize a URL before saving it to the database.
Wordpress
<?php
$clean_url = esc_url_raw( $_POST['website'] );
?>
Allow safe HTML tags in user content while removing harmful code.
Wordpress
<?php
$clean_html = wp_kses_post( $_POST['content'] );
?>
Sample Program

This code cleans user input from a form before using it. It shows the cleaned data safely.

Wordpress
<?php
// Example: Sanitizing user input from a form
if ( isset( $_POST['submit'] ) ) {
    $name = sanitize_text_field( $_POST['name'] ?? '' );
    $email = sanitize_email( $_POST['email'] ?? '' );
    $website = esc_url_raw( $_POST['website'] ?? '' );

    echo "Name: " . $name . "\n";
    echo "Email: " . $email . "\n";
    echo "Website: " . $website . "\n";
}
?>
OutputSuccess
Important Notes

Always sanitize data as soon as you get it, before saving or displaying.

Use the right sanitization function for the type of data you expect.

Sanitization helps prevent security issues like cross-site scripting (XSS).

Summary

Data sanitization cleans user input to keep your site safe.

WordPress offers many functions like sanitize_text_field() and sanitize_email().

Use sanitization every time you handle user or external data.