There are two ways to include the CSRF token in the CodeIgniter application.
Using CodeIgniter form helper class, CSRF tokens can be added automatically or in a custom form for which custom hidden input name and its value are to be given.
Using form helper class
:
[php]
<?php echo form_open(base_url( 'user/login' ), array( 'id' => 'login', 'class' => 'login' ));?>
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" value="Submit" />
<?php echo form_close();?>
[/php]
Output:
[php]
<form action="http://localhost/codeigniter/index.php" method="post" accept-charset="utf-8"><div style="display:none">
<input type="hidden" name="csrf_test_name" value="0729bc908947526aa2e7951fb9066701" />
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" value="Submit" />
[/php]
Using Custom Form
:
[php]
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
[/php]
Suppose, AJAX is being used in the application and token is not passed with POST data then, CodeIgniter will through a error
500 (Internal Server Error)
which states that the forms in the application should use CSRF tokens and then should be pass with POST data.
[html]
<!-- Add CSRF Token as Variable into HEAD -->
<script type="text/javascript">
var csrf_token = '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<!-- Call AJAX code and used CSRF Token -->
<script type="text/javascript">
$.post('POST URL', { data: 'value', 'csrf_test_name': csrf_value }, function( response ) {
// response
}, 'json' );
</script>
[/html]