0

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.
                }
            })
4
  • where do you set the session? Have you called session_start() for this script? Commented Feb 14, 2020 at 10:43
  • 1
    @delboy1978uk, yes. I have updated my question Commented Feb 14, 2020 at 10:46
  • 1
    do you also session_start in the script where you say $response['message'] = $_SESSION['csrf_token'];? Commented Feb 14, 2020 at 10:48
  • 1
    @delboy1978uk, there. It was as I thought, something simple and stupid! That works now, cheers. If you post as answer I will mark as accepted answer Commented Feb 14, 2020 at 10:50

1 Answer 1

2

You just need to make sure the session has started on each script.

session_start();
$response['message'] = $_SESSION['csrf_token'];
$response['message'] = $_POST['token'];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.