How to sanitize user input?

What is the correct way sanitizing form data before submitting to the database? I have the following text input:

<form method="post" action="options.php">
    <?php wp_nonce_field('update-options'); ?>

<input style="width:100%" type="text" name="data[title]" id="title" value="<?php $title = get_option('data_test'); echo $title['title']; ?>" /></p>

    <input type="hidden" name="action" value="update"/>
    <input type="hidden" name="page_options" value="lu_ban_data"/>
    <input style="float:left;margin-top: 10px; margin-bottom: 10px; vertical-align: middle; clear: both;" class="button-primary" type="submit" value="<?php _e('save changes') ?>" />
</form>

I tried doing echo sanitize_text_field($title['title']);, but it only sanitizes the data upon requesting it from the db, the data inside the db still contains unwanted characters. This is why I want to sanitize before submitting it.

Related posts

1 comment

  1. I am not sure if this helpful or not. As s_ha_dum said, you should post how you are processing the submitted data and sending to db.

    But for starters, you might look at escaping the outputted data in the form:

    <input style="width:100%" type="text" name="data[title]" id="title" value="<?php $title = get_option('data_test'); echo esc_attr($title['title']); ?>" /></p>
    

    Use esc_attr() and esc_html() for data that you are adding to the page that has been submitted by the user or you are unsure of its origins.

    esc_attr() is for content outputted into an html tag attribute, and esc_html() is for content outputted directly into the page or between tags. There are also esc_attr_e(), esc_attr__(), esc_html_e, and esc_html__() versions if you need translation.

    Finally, within the escaping series is esc_sql() for user submitted data that you are going to send to your database.

    EDIT:

    As @Milo pointed out in the comments, there isn’t much use for esc_sql() here, because those escape functions are getting applied already to update_option() through the sanitize_option() function and prepared when placed in the database. So you can skip that. If you are writing your own MySQL calls to store data, you should look at $wpdb->prepare to escape them.

    For adding meta_data and options to the database through built in functions, you are already covered.

Comments are closed.