CodeIgniter CSRF Valid for Only One Time Ajax Request
The behavior you are observingâwhere a CodeIgniter application successfully processes an image upload via AJAX on the first attempt but fails on subsequent onesâis a classic symptom of how Cross-Site Request Forgery (CSRF) tokens work. It is not that your code has a bug; rather, it is interacting with the security mechanism exactly as designed. The solution lies in understanding the lifecycle of the CSRF token and ensuring your JavaScript handles its rotation correctly.
When config['csrf_protection'] is set to TRUE (the default), CodeIgniter generates a unique hash for every request session. This hash, often called a "token," is stored in the user's session alongside a name (defaulting to csrf_hash). On your initial page load, CodeIgniter likely echoes this token into your view via <meta> tags or JavaScript variables, allowing you to read it before making your AJAX call.
The problem arises because of how the data is sent and received between your frontend and backend. In your jQuery snippet, you are manually retrieving the token name and hash from the server-side controller context ($this->security->get_csrf_token_name() and get_csrf_hash()) within the JavaScript string. While this might work for a single request if the page reloads or if the token is explicitly provided in the view metadata, relying on server-side echo statements inside the AJAX payload string often leads to scope issues or stale data if the variable isn't properly passed to the client.
More critically, CSRF tokens are designed to be stateless and often single-use for specific actions depending on the configuration. Even when config['csrf_token_regenerate'] is not explicitly set to true (which forces a new token on every request), CodeIgniter validates the submitted hash against the one stored in the session. If your logic inadvertently consumes the token or if the validation process marks it as used, the next request will fail because the stored hash no longer matches the one being sent, or the system expects a fresh token.
To resolve this and allow multiple uploads via AJAX while keeping csrf_protection enabled, you must shift how you pass the token to the client. Instead of trying to echo the server variable directly into the AJAX string (which creates a dynamic string that might not execute correctly in all environments), you should access the token from the HTML head or a dedicated script block where CodeIgniter has already rendered it.
Here is the corrected approach using jQuery:
// Get the CSRF token and name from the meta tags or a global variable set by CI
var token = $('meta[name="csrf-token"]').attr('content'); // Or use a JS variable provided in view
var tokenName = $('meta[name="csrf-token-name"]').attr('content') || 'csrf_hash';
$("#avatar").change(function(){
var link = $("#avatar").val();
$.ajax({
url : '<?php echo base_url("main/test"); ?>',
type: 'POST',
data: {
tokenName: tokenName,
token: token,
'id': "hello",
'link': link
},
success : function(data)
{
console.log("Upload successful:", data);
// Handle the response (e.g., update image src)
},
error: function(xhr, status, error) {
console.error("CSRF Error or Upload Failed", error);
}
});
});
In your view file, ensure CodeIgniter renders these values. You can do this in the controller by echoing them into a <meta> block or initializing a JavaScript object:
<script>
window.CSRF_TOKEN_NAME = '<?php echo $this->security->get_csrf_token_name(); ?>';
window.CSRF_TOKEN_HASH = '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
Your controller logic remains largely unchanged, as it simply validates the incoming hash against the session. The key takeaway is that you are not disabling security by using AJAX; you are just managing the token lifecycle correctly. By decoupling the token retrieval from the AJAX string construction and instead reading pre-rendered values from your view or global variables, you ensure that every request sends a valid, current hash. This allows the upload library to process multiple files without triggering false positives in the security check.
If you find yourself needing to bypass this entirely for local development or specific internal tools, setting csrf_protection to FALSE works but removes a vital layer of defense against automated attacks. Keeping it enabled and fixing the token handling is the robust engineering choice that maintains security without sacrificing functionality.