dtv8189
dtv8189
2011-12-22 17:46

使用JQuery和CodeIgniter将注释安全地添加到数据库中?

已采纳

So I have a comments script I've written in Codeigniter that uses PHP and Jquery.

Basically, a user writes a comment and then hits submit. I then use AJAX to call a server side script to check, validate and insert the comment.

At the JQuery end I am escaping using the encodeURIComponent

$.ajax({
    url : 'http://domain.com/ajax/post_comment',
    type : 'post',
    data : encodeURIComponent( $(this).val() ),
    success : function(data){
                //more code here
            }
});

At the PHP end, as I say I'm using CodeIgniter, so I am escaping the comments using the Binding provided by CodeIgniter like below

$sql = "INSERT INTO video_comments VALUES(NULL, ?);
$this->db->query($sql,array($comment));

This works pretty well and can escape and insert

!"£$%^&*()_+=-}{~@:?></.,#;][¬`|

Now the problem is that, it cannot insert '(single quote) or \(backslash)? I guess because it's not escaping them properly?

One clue might be that it does allow me to insert \' which I guess escapes the single quote? But I would have thought CodeIgniters binding would take care of that at least?

Any ideas?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dqzg62440 dqzg62440 10年前

    First, don't use encodeURIComponent. That's not the intended use of it at all. Edit: Here's a link discussing what that call is actually for: When are you supposed to use escape instead of encodeURI / encodeURIComponent?

    Second, I don't see where you are escaping in the PHP code. CodeIgniter has built in escape functions, like escape_str:

    $sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";
    

    More info here: http://codeigniter.com/user_guide/database/queries.html

    点赞 评论 复制链接分享
  • dqyitt2954 dqyitt2954 10年前

    Update: according to the discussion below query bindings makes the query safe by itself so there is no need to use escape functions separately.

    IMHO, the best and secure way is to use CodeIgniter Active Record Class for your queries, if you are not too much (again too much) worried about performance. IMO, there is just slight performance improvement if you disable Active Record but there are lots of benefits if you enable and use.

    http://codeigniter.com/user_guide/database/active_record.html

    点赞 评论 复制链接分享

相关推荐