I’ve developed some PHP/MySQL code to add some functionality to a Wordpress install; the data for this feature is stored in tables within the WP database itself.
I’m now trying to protect the site from SQL injection attacks (by first disabling magic quotes and then using mysqli_real_escape_string) but I’m having some issues disabling magic quotes.
Adding this bit of code (from Sitepoint’s PHP Live course) into the Wordpress header or page results in the page not loading at all.
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
I’m guessing it’s a result of some incompatibility with Wordpress and a different approach may be better suited to deal with SQL injection attempts.
I’ve also had a read through the Wordpress documentation for the wpdb class which is what I’m using to INSERT/UPDATE/DELETE/SELECT data.
If I understand correctly, for INSERT and UPDATE, there is no need for SQL escaping.
(array) Data to insert (in column => value pairs). Both $data columns and $data values should be “raw” (neither should be SQL escaped).
Again, if I understand the Wordpress documentation correctly, SQL escaping needs to be done for DELETE and SELECT queries.
Wordpress seems to offer two/three ways of doing this
<?php $sql = $wpdb->prepare( 'query' [, value_parameter, value_parameter ... ] ); ?>
$wpdb->escape( $text )
Escapes a single string for use in a SQL query. Glorified addslashes().
like_escape( $string )
Sanitizes $string for use in a LIKE expression of a SQL query. Will still need to be SQL escaped (with one of the above functions).
I would appreciate it if someone who’s experienced with these Wordpress functions could confirm whether my understanding is correct and help me understand which of those functions would be best suited for dealing with SQL injection attempts.