Data Sanitization
Data Sanitization and Security
Security is a primary pillar of this project. To prevent common vulnerabilities such as Cross-Site Scripting (XSS), SQL Injection, and Cross-Site Request Forgery (CSRF), all user-supplied data must be validated, sanitized, and escaped using standard WordPress functions.
Input Validation
Validation ensures that the data being submitted matches the expected format before any processing occurs. Always validate data as early as possible.
Common Validation Functions:
is_email(): Checks if a string is a valid email address.term_exists(): Checks if a given taxonomy term exists.username_exists(): Checks if a username is registered.
// Example: Validating a simple input
if ( isset( $_POST['user_age'] ) && is_numeric( $_POST['user_age'] ) ) {
$age = (int) $_POST['user_age'];
} else {
// Handle error: age is not valid
}
Data Sanitization
Sanitization cleanses data by stripping out unwanted characters or tags before it is saved to the database. This project adheres to the "Sanitize Early" principle.
Usage Examples:
sanitize_text_field(): Strips tags, removes line breaks, and tabs. Use for standard text inputs.sanitize_email(): Strips invalid characters from email addresses.absint(): Converts a value to a non-negative integer.sanitize_textarea_field(): Preserves line breaks but strips tags.
// Sanitizing a custom settings field
$processed_data = array(
'user_bio' => sanitize_textarea_field( $_POST['bio'] ),
'user_email' => sanitize_email( $_POST['email'] ),
'post_id' => absint( $_POST['post_id'] ),
);
Output Escaping
To prevent XSS, all data must be escaped at the point of output ("Escape Late"). Never trust data retrieved from the database or external APIs without escaping it first.
Usage Examples:
esc_html(): Use when a string is rendered within HTML nodes.esc_attr(): Use when data is placed inside an HTML attribute (e.g.,valueortitle).esc_url(): Use for all URLs, including those insrcandhrefattributes.wp_kses(): Use when you need to allow specific HTML tags (useful for text editors/formatted content).
<!-- Example: Escaping in a template file -->
<div class="user-profile">
<a href="<?php echo esc_url( $profile_url ); ?>">
<?php echo esc_html( $username ); ?>
</a>
<input type="text" value="<?php echo esc_attr( $saved_value ); ?>" />
</div>
Security Tokens (Nonces)
Non-persistent security tokens (Nonces) are used to protect against CSRF attacks. Every action that modifies data or changes state must include a nonce check.
1. Create a Nonce: Include a nonce field in your forms or append it to your URLs.
// In a form
wp_nonce_field( 'update_user_settings', 'user_settings_nonce' );
// In a URL
$url = wp_nonce_url( $base_url, 'delete_post_' . $post_id );
2. Verify a Nonce: Check the nonce before processing the request on the server side.
if ( ! isset( $_POST['user_settings_nonce'] ) || ! wp_verify_nonce( $_POST['user_settings_nonce'], 'update_user_settings' ) ) {
wp_die( 'Security check failed' );
}
// Proceed with data processing...
Database Safety
When interacting with the database directly (outside of WP_Query or standard API functions), use the $wpdb->prepare() method to prevent SQL injection.
global $wpdb;
$user_id = 12;
// Use placeholders (%s for string, %d for integer, %f for float)
$user_data = $wpdb->get_row( $wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}users WHERE ID = %d",
$user_id
) );