-->

codeigniter csrf error on form submission

2020-07-24 16:18发布

问题:

I have a form using codeigniter brackets

echo form_open('signup');

echo form_close();

and when i submit it i get the following error

An Error Was Encountered

The action you have requested is not allowed.

NOT always but often...

even when the hidden inputfield exist inside the form:

<div style="display:none">
<input type="hidden" value="token name is here" name="csrf_token_name">
</div>

this also happens on a similar form(signin)

EDIT: html generated via form

<form accept-charset="utf-8" method="post" action="http://www.example.com/signup">
<div style="display:none">
<input type="hidden" value="93565fb5855d31af3d46bd655b11a4a6" name="csrf_token_name">
</div>
<input id="username" type="text" placeholder="Username" maxlength="20" value="" name="username">
<input id="email" type="text" placeholder="Email" value="" name="email">
<input id="password" type="password" placeholder="Password" value="" name="password">
<input id="submit" type="submit" value="Sign up" name="submit">
</form>

回答1:

you are doing it wrong.

try this

    <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />

the value must be what codeigniter calculates for the csrf token.

or use form helper and codeigniter will add this hidden field automatically.



回答2:

In my case I just increased 'csrf_expire' variable - the number in seconds the token should expire.

From $config['csrf_expire'] = 7200; To $config['csrf_expire'] = 28800;



回答3:

change $config['csrf_regenerate'] = TRUE;

to

$config['csrf_regenerate'] = FALSE; in config file



回答4:

If you just want to get rid of the errors altogether...
The easiest solution to get around them would be to:

  1. Open your /config/config.php file

  2. Find the line below:
    $config['csrf_protection'] = TRUE;

  3. Replace it with...
    $config['csrf_protection'] = FALSE;

  4. Save changes.


CAUTION: Turning off the CSRF protection means you are left open to CSRF attacks.