我知道如何在CodeIgniter的表单中启用CSRF,但是我不确定如何在CodeIgniter经典链接中实现此功能(例如,在管理区域中添加/删除私人消息,帖子等)
现在我正在使用这样的东西:
视图
<?php echo anchor('account/delete_private_message/'.$obj->pmID, 'delete mesage', array('onclick' => 'return confirm(\'Do you really want to delete this private message?\');', 'class' => 'delete-message-button')); ?>
控制器
function delete_private_message($pmID = '')
{
$deleted_pm = $this->account_model->delete_pm($pmID);
if($deleted_pm)
{
$this->session->set_flashdata('status', 'PM was deleted successfully');
}
else
{
$this->session->set_flashdata('status', 'Error');
}
redirect('account/private_messages');
}
模型
function delete_pm($pmID)
{
$return = 0;
if(!empty($pmID))
{
$this->db->where('pmID', $pmID);
$result = $this->db->delete('private_messages');
}
return $result;
}
如果用户单击弹出窗口中的“确定”,则消息将被删除.
问题是如何将令牌添加到链接和用户会话并进行验证等.我不知道如何实现此功能以使其正常工作.
编辑:我只是想我必须在链接的末尾添加生成的令牌,如:
account/delete_private_message/1239/dfdf6e7re67a6e87r6e87r69876bn3
值dfdf6e7re67a6e87r6e87r69876bn3也在当前用户的会话中,并在控制器中进行验证.但是,我不知道该怎么做.因此,感谢您的帮助.
解决方法:
您是正确的-只需将CSRF令牌作为链接的一部分传递即可.下面的示例应该有所帮助(但我尚未对其进行测试)
function delete_private_message($pmID = '', $token = null)
{
// Check supplied token is valid
if ( ! ($this->_check_token($token)))
{
// Not valid
$this->session->set_flashdata('status', 'Error');
redirect('account/private_messages');
}
if($this->account_model->delete_pm($pmID))
{
$this->session->set_flashdata('status', 'PM was deleted successfully');
}
else
{
$this->session->set_flashdata('status', 'Error');
}
redirect('account/private_messages');
}
function _check_token ($token)
{
return ($token === $_COOKIE[$this->csrf_cookie_name]);
}
ps.您的模型代码有错误
$return = 0;
应该
$result = 0;