1
votes

i got this SQL query where post_title taken from $_GET

$sql = "SELECT ID FROM posts WHERE posts.post_title = '5-design-web-colourful'";

What is the best way to sanitize this and make it more safe ?

EDIT : (as requested) I'm trying to create a plugin that work to hide a particular category (named private) and all of its post for every non-logged guest. i have hook into 'pre_get_posts' and 'posts_selection' able to control how to show particular posts and category for admin, the member who wrote them, other member, and guest.

The category must be non exist. so it can not be shown on cat archive page in front end.

I know it's not relatedto the question cause what iask just how to sanitize name / title of a post. nothing more.

2
So you want to make sure that an identifier isn't tampered with. Is the column name $wpdb->posts.post_title the only "issue" or can $wpdb->posts be a problem, too? - VolkerK
VolkerK: I read the question to mean that '5-desain-web-colourful' (i.e. value of post_title field) was taken from $_GET. Can you please clarify, justjoe? - Anonymoose
@all : sorry, this is wordpress query. i will edit those sql first - justjoe
Now, in this version of the query, you don't have to sanitize anything. It's a static query with no variable parts. You might want to explain what you're trying to achieve. And now it becomes more and more likely the question is a duplicate. - VolkerK
I'm not bored but (no offence) maybe a bit annoyed... because there is something to the question. It could be a good question but right now imho it's a mess. It started as a mysql question (having only identifiers as variables), you got the generic mysql_escape_lalala answers (potentially wrong at this point), turns out you really want variable sql parameters, ok real_escape_string might be it. Suddenly it becomes a wordpress question (-> real_escape_string not good), WP_QUERY gets involved. Now it's wpdb (probably both, WP_QUERY and wpdb) ....c'mon, it's a bit all over the place. - VolkerK

2 Answers

3
votes

Use mysql_real_escape_string, assuming you use MySQL.

3
votes

While this doesn't directly answer your question, the better approach is to use bind parameters. This protects you from all attack vectors of this category.

http://php.net/manual/en/pdo.prepared-statements.php

http://www.php.net/manual/en/pdostatement.bindparam.php

For your example:

$sth = $dbh->prepare("select id from $wpdb->posts where $wpdb->posts.post_title = ?");
$sth->bindParam(1, $str);
$sth->execute();

CAUTION: This assumes that $wpdb is safe!