Recently wrote a system, no security filter input, want to use CI input class, analyzed the next, there are three files are required system/core under the
utf8.php,security.php,input.php
Can be integrated into a file, but more trouble, or three files it, so easy.
Use it like this:
Instantiating a secure input class
$UNI = new UTF8 ();
$SEC = new security ();
$input = new input ();
Then there is the form of $username = $input->post (' username ').
Of course, in the inside to modify some configuration variables, such as $cookiepath, $cookieprefix, $cookiedomain, $cookiesecure and so on;
But there is a key configuration, $this->_enable_csrf= FALSE; This variable corresponds to var$_enable_csrf = false; The default is False, if you set it to true,
This will add a _csrf_token_name key-value pair after the URL, because this will be checked in the code below.
The request must also have a _csrf_cookie_name cookie value.
Reference:
There is a csrf (cross Site Request forgery) protection feature in CI 2.0
If this function is opened
Post form to server will spit error 500
An Error was encountered
The action has requested is not allowed.
Will not perform
To add a token value to the value of the form sent
To use the forms function properly
The following lines can be found in the application/config/config.php
1 2 3 4 |
$config [ 'csrf_protection' ] = TRUE;
$config [ 'csrf_token_name' ] = 'csrf_test_name' ;
$config [ 'csrf_cookie_name' ] = 'csrf_cookie_name' ;
$config [ 'csrf_expire' ] = 7200;
|
Originally $config[' Csrf_protection ') the preset is false to true to open the
It will help you to save a value in a cookie after you open it.
The name of the cookie can be set in the config.php above
After that, the delivery form will be communicated with this token.
The following is an example of the Ajax function of jquery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$( function (){
$( '#btn' ).click( function (){
$.ajax({
type: 'POST'
,url: '/ajax' //ajax接收的server端
,data:$( '#form' ).serialize()+ '&csrf_test_name=' + getCookie( 'csrf_test_name' )
,success: function (data){
alert(data.msg);
}
,dataType: 'json'
});
});
});
function getCookie(name){
var arr = document.cookie.match( new RegExp( "(^| )" +name+ "=([^;]*)(;|$)" ));
if (arr != null ) return unescape(arr[2]); return null ;
}
|
GetCookie () is the value of using JS to remove the cookie
This is found on the Internet, and can be taken directly.
And Csrf_test_name is the number of parameters that can be set in the config.php.
Grab this cookie and send out the form together
You can use it normally.
Have any comments welcome message ~
Referer:http://ericlbarnes.com/blog/post/codeigniter_csrf_protection_with_ajax
The above describes the use of CodeIgniter input classes, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.