I now want to compare this value passed into the server action with the session variable itself, so the server action knows the call has come from the user interface.
So then in my PHP file I have declared a SESSION variable called csrf_token… however it has a value of null.
How can I access the value of the csrf_token session variable in my Server Action?
Thanks @TomD… I’m not a PHP guru, but I would assume that something else starts that, and if it wasn’t running then I’d not be able to echo the value of $_SESSION.csrf_token on the front end?
The session variables created on the page via PHP code ($_SESSION['var1']) are dfferent to the session variables created in the Server Connect API so you need to post the value. Your method via a hidden form field is as good a way as any.
But for anti-CSRF, I need to compare the value posted on the form with the actual value set in the PHP session variable… so how can I access the value I have set for $_SESSION['csrf_token'] directly via PHP in a server action?
Great - I’m glad you sorted it out. I often find it useful to inspect the contents of sessions - particularly if they contain multiple values which you might be adding to or removing. To do this, get the session name using the browser developer tools:
An alternative I use which removes the need for custom code is.
Create an API action which creates the token AND sets the session value.
Call the server action from the page and use the returned token (which is also saved in a session var) from rhe API action. Use the token in a hidden input or better value text input with d-none to hide it.
The token can then be checked on form submission by comparing the submitted value with the session variable value.
The technique is illustrated in my video series under sections on honeypots.