How Do I Pass a PHP Session Variable From Front End to Back End?

I’m trying to create an anti-CSRF token that can be read on the front and back end of my PHP based app.

I’ve created the token in a PHP Session variable with the following code at the top of the index.php file:

<?php 
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

I can access this on the front end and pass it to the back-end via a hidden input…

<input id="i_user_setting_csrf" name="csrf_token" type="hidden" class="form-control fs_75 c_right6" value="<?php echo $_SESSION['csrf_token']; ?>">

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?

Best wishes,
Antony.

Perhaps you’ve forgotten to include:
session_start();
… unless it’s called earlier in the page.

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.

Thanks @sitestreet!

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?

You were right @TomD… this code works!

<?php 
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

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:

… then find the location of the file and open it in a text editor:

image

Very useful for debugging - as long as you have access to the relevant temp folder.

2 Likes

An alternative I use which removes the need for custom code is.

  1. Create an API action which creates the token AND sets the session value.

  2. 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.

  3. 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.

4 Likes