Session set after redirect not saved on form submit

293 Views Asked by At

I'm using sessions to send variables over forms to securely delete records on a backend. Everything works just fine:

  1. I create the list of records, along with delete buttons as forms.
  2. While creating the delete buttons I set a session including the token and the id of the item to delete.
  3. When I click the delete button (which submits the form) the action is called in the php file that handles the action. I read the token, compare it to the one sent in the form, retrieve from the session the id of the item to be deleted, delete the item.
  4. Redirect the user to the previous page.

However, after the redirect, this does not work unless I refresh the page before deleting. Even though the session is created again after the redirection (I already checked this works fine), when I submit a delete form again, the session does not persist to the file that handles the form.

Does anyone have any idea of what might be happening?

How I set the session:

$token = SessionManager::setTokenForForm('delete-' . $row->id, $values);

echo '<form method="post" action="' . FrontendConstants::$BASE_URL . FrontendConstants::$DELETE_RECORD_URL . '">';
echo '  <input type="hidden" name="token" value="' . $token . '"/>';
echo '    <input type="hidden" name="redirect_url" value="' . $fullRedirectUrl . '"/>';
echo '    <input type="hidden" name="id" value="' . $row->id . '"/>';
echo '    <input type="submit" class="btn btn-default" value="Delete"/>';
echo ' </form>';

The function setTokenForForm:

public static function setTokenForForm($form, $values = null) {
        $token = uniqid();
        if (!isset($_SESSION)) {
            session_start();
        }

        $session = array();

        $session['token'] = $token;

        if ($values != null) {
            $session['values'] = $values;
        } else {
            $session['values'] = array();
        }

        $_SESSION[$form] = $session;

        return $token;
 }

On delete.php, which is the file being called by the form, after consulting the session and deleting the item, I redirect to the previous page:

header('Location: ' . $redirect_url);
0

There are 0 best solutions below