CSRF/csrf in ci4
- Enable CSRF:
Go to app/Config/Filters.php
Search for public array $methods and replace with:12345public array $methods = ['post' => ['csrf']];
- Use (Just paste under <from>) :
<input type=”hidden” name=”<?= csrf_token() ?>” value=”<?= csrf_hash() ?>” />
=============================================
CSRF in AJAX CI4
Add this in <form> or without form, it will get it by id
1 | <input type="hidden" id="csrf_token" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>"> |
AJAX Script for Handling
Retrieve the CSRF token from the <input>
field and include it in the AJAX request. After receiving the response, update the token dynamically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | $(document).ready(function () { $('#statusSelect').on('change', function () { let selectedValue = $(this).val(); // Get the selected value // Get CSRF token from the hidden input field let csrfName = $('#csrf_token').attr('name'); // CSRF token name let csrfHash = $('#csrf_token').val(); // CSRF token value // Prepare AJAX request $.ajax({ url: '/your-endpoint', // Replace with your endpoint method: 'POST', data: { [csrfName]: csrfHash, // CSRF token selected: selectedValue // Selected option value }, success: function (response) { // Update CSRF token for subsequent requests $('#csrf_token').val(response.csrfToken); // Handle success response alert('Status updated successfully!'); console.log(response.message); }, error: function (xhr, status, error) { // Handle errors alert('An error occurred.'); console.error(error); } }); }); }); |
Controller to Handle the Request
The controller processes the request and returns a response with an updated CSRF token.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public function updateStatus() { if ($this->request->getMethod() === 'post') { // Get the selected value $selectedValue = $this->request->getPost('selected'); // Perform your logic here (e.g., update the database) // ... // Return success response with the updated CSRF token return $this->response->setJSON([ 'status' => 'success', 'message' => 'Status updated successfully', 'csrfToken' => csrf_hash() // Updated CSRF token ]); } // Handle invalid request return $this->response->setJSON([ 'status' => 'error', 'message' => 'Invalid request', 'csrfToken' => csrf_hash() // Updated CSRF token ]); } |