我正在为我的网站添加私人消息.在我的表单中的“收件人”文本字段中,我想在有人开始键入时建议有效的用户名.在阅读了教程并研究了一些脚本后,我制作了以下代码,用于建议我的数据库表中名为users的用户名.它有效,但我不确定它是多么正确和安全.
$(function() {
$( "#username" ).autocomplete({ //the recipient text field with id #username
source: function( request, response ) {
$.ajax({
url: "http://localhost/mysite/index.PHP/my_controller/search_username",
dataType: "json",
data: request,
success: function(data){
if(data.response == 'true') {
response(data.message);
}
}
});
},
minLength: 1,
select: function( event, ui ) {
//Do something extra on select... Perhaps add user id to hidden input
},
});
});
控制器(为简单起见,我没有使用模型,虽然我计划)
function search_username()
{
$username = trim($this->input->get('term')); //get term parameter sent via text field. Not sure how secure get() is
$this->db->select('id, username');
$this->db->from('users');
$this->db->like('username', $username);
$this->db->limit('5');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$data['response'] = 'true'; //If username exists set true
$data['message'] = array();
foreach ($query->result() as $row)
{
$data['message'][] = array(
'label' => $row->username,
'value' => $row->username,
'user_id' => $row->id
);
}
}
else
{
$data['response'] = 'false'; //Set false if user not valid
}
echo json_encode($data);
}
解决方法:
我建议制作一个编辑…
我会通过将第二个参数TRUE传递给get()来启用XSS保护
$username = trim($this->input->get('term', TRUE));