Security
The Security Class contains methods that help protect your site against Cross-Site Request Forgery attacks.
Loading the Library
If your only interest in loading the library is to handle CSRF protection, then you will never need to load it, as it runs as a filter and has no manual interaction.
If you find a case where you do need direct access though, you may load it through the Services file:
<?php
$security = service('security');
Cross-Site Request Forgery (CSRF)
Warning
The CSRF Protection is only available for POST/PUT/PATCH/DELETE requests. Requests for other methods are not protected.
Prerequisite
When you use the CodeIgniter’s CSRF protection, you still need to code as the following. Otherwise, the CSRF protection may be bypassed.
When Auto-Routing is Disabled
Do one of the following:
Do not use
$routes->add(), and use HTTP verbs in routes.Check the request method in the controller method before processing.
E.g.:
if (! $this->request->is('post')) {
return $this->response->setStatusCode(405)->setBody('Method Not Allowed');
}
Note
The $this->request->is() method can be used since v4.3.0.
In previous versions, you need to use
if (strtolower($this->request->getMethod()) !== 'post').
When Auto-Routing is Enabled
Check the request method in the controller method before processing.
E.g.:
if (! $this->request->is('post')) {
return $this->response->setStatusCode(405)->setBody('Method Not Allowed');
}