wpdb->insert and stripslashes against sql injection

I’ve been reading the codex at this page: http://codex.wordpress.org/Function_Reference/stripslashes_deep

The code i wrote before reading that page is this:

Read More
$data   = array(
    'col1' => $v['float'],
    'col2' => stripslashes($v['string'])
);
$format = array( '%f', '%s' );
$wpdb->insert( 'table', $data, $format );

Basically i manually pass stripslashed values in the $data array. Now, is this code correct and secure or shall i perform a $_REQUEST = array_map( 'stripslashes_deep', $_REQUEST );? Is there any important difference or is it the same?

Related posts

Leave a Reply

1 comment

  1. If you check out the source for the $wpdb->insert( $table, $data, $format) method you will find this comment:

    Data to insert (in column => value pairs). Both $data columns and
    $data values should be “raw” (neither should be SQL escaped).

    so you shouldn’t need to do the SQL escape yourself on the data.

    As far as I understand the process, the data inserted into the $wpdb->insert() method, goes through:

    • the $wpdb->prepare() method,
    • which uses $wpdb->escape_by_ref(),
    • which uses $wpdb->_real_escape(), for non floating values: ! is_float( $string ),
    • that uses the PHP wrapper mysql_real_escape_string() or mysqli_real_escape_string() for WP 3.9+ with PHP 5.5+.

    From the PHP docs on the mysql_real_escape_string() function:

    Escapes special characters in the unescaped_string, taking into
    account the current character set of the connection so that it is safe
    to place it in a mysql_query(). If binary data is to be inserted, this
    function must be used.
    mysql_real_escape_string() calls MySQL’s library function mysql_real_escape_string, which prepends backslashes to the following
    characters: x00, n, r, , ‘, ” and x1a.
    This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

    But as stated in the Codex page you refer to, in older versions of PHP the addslashes can be automatically applied to the $_POST, $_GET and $_REQUEST globals. The Magic Quotes feature is deprecated in PHP 5.3 and removed in 5.4.