我正在使用CodeIgniter自定义表单,在此表单中,我在表单提交后使用了CSRF令牌我希望在表单提交后检查控制器,如果CSRF令牌有效,是否有人可以帮我解决这个问题?< / p>
PHP表单代码
<form role="form" data-parsley-validate="" novalidate="" class="mb-lg" action="?c=
<?php echo isset($controller) ? $controller : "welcome"; ?>&m=login" method="post">
<div class="form-group has-feedback">
<input name="email" id="exampleInputEmail1" type="email" placeholder="Enter email" autocomplete="off" required class="form-control">
<span class="fa fa-envelope form-control-feedback text-muted"></span>
</div>
<div class="form-group has-feedback">
<input name="password" id="exampleInputPassword1" type="password" placeholder="Password" required class="form-control">
<span class="fa fa-lock form-control-feedback text-muted"></span>
</div>
<div class="clearfix">
<div class="pull-right">
<a href="?c=<?php echo isset($controller) ? $controller : "welcome"; ?>&m=resetpassword" class="text-muted">Forgot your password?</a>
</div>
</div>
<?php
$csrf = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash()
);
?>
<input type="hidden" name="<?php echo $csrf['name'];?>" value="<?php echo $csrf['hash'];?>" />
<button type="submit" class="btn btn-block btn-primary mt-lg">Login</button>
</form>
答案 0 :(得分:2)
CodeIgniter会自动为您执行此操作。如果它无效,则会show_error
show_error('The action you have requested is not allowed.', 403);
相关功能可以在/system/core/security
课程中找到,功能:csrf_verify()
和csrf_show_error()
(如果无效)。
如果您现在已经理解,如果您在配置中启用了csrf并且您没有相应的csrf隐藏字段或使用form_open
(为您添加字段),那么当您发布请求时将失败并显示上述消息。对于AJAX请求也是如此 - 为ajax请求自动执行此操作,只要有ajax请求,您就可以将其添加到页面顶部:
<script type="text/javascript">
token["<?php echo $this->security->get_csrf_token_name(); ?>"] = "<?php echo $this->security->get_csrf_hash(); ?>";
jQuery.ajaxSetup({data: token, type: "POST"});
</script>