This is probably really simple but it isn’t obvious to me right now why this isn’t working.
I am setting a session variable on the index.php file, putting the value into a hidden field within a form and then submitting the form via jQuery and ajax. All the other form data is there and the hidden input value is there. But if I just try to echo the actual session variable out I get nothing eg:
$response['message'] = $_SESSION['csrf_token']; // no output $response['message'] = $_POST['token']; // outputs the session variable value stored in the hidden field
On index.php
<?php session_start(); $_SESSION['csrf_token'] = uniqid('', true); ?> <input type="hidden" name="token" value="<?php echo $_SESSION['csrf_token']; ?>">
jQuery:
var form = $('#testForm').serialize(); $.ajax({ url: 'test', type: 'POST', dataType: 'json', data: form, beforeSend: function() { // loading spinner etc. } })
Advertisement
Answer
You just need to make sure the session has started on each script.
session_start(); $response['message'] = $_SESSION['csrf_token']; $response['message'] = $_POST['token'];