Search code examples
phpjsonwordpresssanitization

Saving string to database in WordPress


I am saving options to my database. The JSON string is returned from ajax call, and I am sanitizing it like

$my_settings = wp_json_encode( sanitize_text_field( wp_unslash( $_POST['data'] ) ) );

When I save it with update_option this gets saved in the database as

"{ \"0\": { \"settings\": { \"default\": \"0\", \"header_main_title\": \"\",...

Now if I only do this

$my_settings = sanitize_text_field( wp_unslash( $_POST['data'] ) );

The entry in the database will be

{ "0": { "settings": { "default": "0", "header_main_title": "",...

The second version can still be decoded using json_decode, since this is a JSON string after all, and doesn't have the slashed double quotes.

The thing that's bothering me is:

  • Is this safe?
  • Will the magic quotes have any impact on this?
  • Should I use first or second way?

Solution

  • Option value is always saving safe due to wpdb update method, not sanitize_option. You can save any data you want. Take a look into update_option code:

    $update_args = array(
             'option_value' => $serialized_value,
    );
    $result = $wpdb->update( $wpdb->options, $update_args ...
    

    Update method uses prepare, so it is always safe:

    return $this->query( $this->prepare( $sql, $values ) );