get_posts() SQL Injection
سؤال
I'm working on a custom search page and I usually use wpdb->prepare when crafting custom queries. But this time I went with get_posts to create the below query. But I'm wondering if I have to worry about SQL Injection with it. Should I? Or does get_posts() have that security built in?
If not, how do I clean the incoming variables?
$SEARCH_QUERY = @$_GET['s2'];
$args2 = array(
'orderby' => 'date',
'order' => 'DESC',
's' => $SEARCH_QUERY
);
$arrSearchResults = get_posts($args2);
echo "<pre>";
print_r($arrSearchResults);
echo "</pre>";
المحلول
If not, how do I clean the incoming variables?
In most cases you don't, get_posts
calls WP_Query
internally, and WP_Query
performs some sanitization, namely via wpdb->prepare
.
However, for what you're trying to do, this is the wrong approach. Just use a standard search.php
template with a standard post loop, and use input
fields that have the same names as the parameters for WP_Query
. WP will automatically filter as a result of them being added to the URL. There is no need for a custom page template with a custom query and custom URL parameters. It's just unnecessary complexity, and double the database queries ( don't forget the broken pagination, dealing with 404's, etc )