Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP serialized data stored in mysql db error

Tags:

php

mysql

mariadb

I have a Database based session storage solution. Works great! I however have an issue with it storing a particular type of data.

I have an application which uses CSRF tokens. When a form is created, it will create a token for that form. The token is a hashed (sha256) value of different types of values. One copy goes to the form and another copy is stored in the sessions. Upon submitting the form, it compares the tokens to ensure that they match.

Below is an example of the destruct function which updates the db with the new data

UPDATE session_manager SET variables= :variables  WHERE 1=1  AND id = :id
array(2) {
  [":variables"]=>
      string(152) "a:1:{s:4:"CSRF";a:1:{s:8:"register";a:2:{s:5:"token";s:64:"e749603241dec1911ef3a40d98b2f5185d389434060483297394b504cc904ede";s:4:"time";i:1443456816;}}}"
  [":id"]=>
      string(2) "49"
}

Update statement is fine and works fine. This is the issue I have, the data is updated however the 'token' value that you can see in the data above is not the same value in the db which is below (This is a binary download of the data):

a:1:{s:4:"CSRF";a:1:{s:8:"register";a:2:{s:5:"token";s:64:"b48fc79fc2f51eff765c05476895238a42d9d45b2c1aeb7c6e4582d0381b7f4f";s:4:"time";i:1443456817;}}}

It would appear that mysql is changing the value and I cannot for the life of me figure out the issue. Solutions I've tried include:

  • serialize
  • json_encode
  • base64

Changing charsets of the db and what not. Tried different field types in the db for example TEXT, Longtext and BLOB. Which does not seem to work for me :(

Here is the sql for the db

CREATE TABLE session_manager(
    id BIGINT(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
    session_id VARCHAR(200),
    user_agent TINYTEXT NOT NULL,
    variables BLOB NOT NULL,
    initial_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
    regenerate_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL
);

Any reasons that pop to mind?

like image 778
Tim Avatar asked Sep 28 '15 16:09

Tim


1 Answers

Have you looked at time index of your array? It seems like it changed as well. This makes me think the method for saving the session is executed (at least) twice. The second time the session is updated and overwrites the old value.

Run this code in with a debugger attached, or print/log a stack trace every time your function is called. This should give you a pretty good idea when the value is updated again.

PS: Is the update query called again on the next request, before you can retrieve the value?

like image 116
M. Dekker Avatar answered Sep 17 '22 23:09

M. Dekker