CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New

Codeigniter CSRF Token Example


CodeIgniter, a popular PHP framework, provides built-in support for Cross-Site Request Forgery (CSRF) protection to secure your web applications from CSRF attacks. CSRF protection in CodeIgniter involves generating and validating CSRF tokens. Here's how you can work with CSRF tokens in CodeIgniter:

Step 1: Enabling CSRF Protection:

By default, CSRF protection is enabled in CodeIgniter. You can find the CSRF configuration in the application/config/config.php file. Make sure the csrf_protection configuration is set to true:

Go to your config.php file

And Change the CSRF configuration like this.

$config['csrf_protection'] = TRUE;

Step 2:

Then in your HTML form in view file

<input type="hidden" class="txt_csrfname" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>">

Add the below Input box

Example:

<form id="form-validation-simple" name="form-validation-simple" method="POST">
<input type="hidden" class="txt_csrfname" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>">
    <div class="row">
        <div class="col-md-6">
                <div class="form-group">
                <label class="form-label"> Topic Name  <span class="required">*</span> </label>
                <input
                    name="Name" id="Name" value="<?php echo $values->Name;?>" placeholder="Required, at least 4 characters" minlength="4" required
                    type="text"
                    class="form-control"
                    data-validation="[NOTEMPTY]"/>
                </div>
        </div>
    </div>

3. Validating CSRF Tokens:

CodeIgniter automatically validates CSRF tokens when you submit a form. If a CSRF token mismatch occurs, it will show an error message by default. You can customize the error message in the application/language folder.