这段代码容易受到SQL注入攻击吗?


Is this code vulnerable to SQL injection attacks?

这个代码容易受到SQL注入攻击吗?

$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_author_email, comment_date_gmt, comment_approved, comment_type, comment_author_url, SUBSTRING(comment_content,1,70) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 5";

假设$wpdb对象从外部是不可触摸的(这在Wordpress中通常是正确的),我想说您使用这个特定的查询是安全的。

您只需要担心从外部源接收的任何参数的传入。

Wordpress提供了几种方法来处理查询中的用户输入。看到http://codex.wordpress.org/Data_Validation数据库

这取决于我看不到的一些事情-或者我没有足够的知识从你发布的代码中知道。要容易受到SQL注入的攻击,您必须在数据库中输入未转义的字符串。(编辑:通常是一个未转义的,但用户可定义的字符串)。

我在你的代码中看不到任何地方转义了字符串。PHP为此提供了一个函数:$string = mysql_real_escape_string($string);然后在数据库查询中使用该字符串应该是安全的。

例如,不要使用:
$name = $_GET['name'];
mysql_query("INSERT INTO table_name VALUES ('$name')");

而不是使用:

$name = mysql_real_escape_string($_GET['name']);
mysql_query("INSERT INTO table_name VALUES ('$name')");

你"应该"受到SQL注入的保护,只要在"mysql_real_escape_string"函数中没有漏洞。