1

In PHP 5.5 you had the function

mysql_real_escape_string()

and I always did

htmlspecialchars(mysql_real_escape_string($_POST['...]));

to secure against SQL-Injection.

With PHP 7 mysql_real_escape_string() is gone. An alternative is

mysqli_real_escape_string()

but that function needs a link to the mysqli object. When using WordPress to perform a query like this:

$query_args = array( 's' => $_POST['search'] ); $query = new WP_Query( $query_args );

I can't provide a mysqli object. So Do I have to leave all the security stuff to WordPress? Is it enough to do:

$query_args = array( 's' => htmlspecialchars( $_POST['search'] ) ); $query = new WP_Query( $query_args );

?

5
  • your code didn't add any security, no point in trying to maintain it. Sep 21, 2016 at 8:41
  • What do you mean?
    – SVARTBERG
    Sep 21, 2016 at 8:42
  • Wordpress API does proper escaping, all you have done is to "break" the actual data that needed to be acted upon Sep 21, 2016 at 8:43
  • So if I understand correctly, the answer to my question is that I can do: $query_args = array( 's' => $_POST['search'] ); $query = new WP_Query( $query_args );
    – SVARTBERG
    Sep 21, 2016 at 9:01
  • yes, wp_query will do whatever is the needed sanitization to access the DB. To display you might need to do some escaping Sep 21, 2016 at 10:39

1 Answer 1

1

Maybe you could try this, to sanitize the whole $_POST array

$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

Or to sanitize just a field, you could use the native WP function

$sanitized = sanitize_text_field ( $_POST['key'] );
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.