'PHP, Cookie theft
I store a basket cookie Id which is really uniq, a long random 20 characters string like that: "7irMz2cvpnXpSCkNkBAT"
It's stored on browser not directly in a single Cookie but in a Json global cookie containing multiple values.
I can see Baskets from an admin part and I have sometimes a Basket from let's say a client from New-Zealand falling into the Basket of a someone in India who created an account!
It's all the time the same user stealing the basket Cookie from someone else and putting in it 20 articles which had not been put originally by the client.
I don't know if it's a bot from India or a real person doing that!
How to prevent cookie theft?
I cannot associate a cookie to an IP, people with smartphones for example change sometimes of IP address.
To recover / create / update the cookie I do like that:
// Recovering the Cookies from the Datas Json Object
if(isset($_COOKIE['Datas'])) {
$cookie = json_decode($_COOKIE['Datas']);
if(is_object($cookie)) {
$expiry = $cookie->expiry;
$diff=$expiry-time();
$cookieDatasExpiresDays = floor($diff/(60*60*24));
foreach($cookie->Data as $key => $value) {
$_COOKIE[$key] = $value;
}
} else {
setcookie('Datas', '', -1, '/');
}
}
/**
* Cookie for basket used for non connected users
*/
if((!isset($_COOKIE['Basket']) || $_COOKIE['Basket'] == NULL) &&
!check_bot()) { //We check also if Cookies are enabled
$updateCookie = 'Basket';
$_COOKIE['Basket'] = get_stringSuffle(20, TRUE);
}
if(isset($_COOKIE['Basket'])) {
$cookiesInfos['Basket'] = $_COOKIE['Basket'];
}
...
if($updateCookie != '' && !check_bot()) { //We check also if Cookies are enabled
// Updating Cookie if needed
$cookiesArray = [];
$cookiesArray['Data'] = [];
foreach($cookiesInfos as $key => $val) {
$cookiesArray['Data'][$key] = $val;
}
setcookie('Datas', '', -1, '/');
setcookie('Datas', json_encode($cookiesArray), $expiry, '/');
}
EDIT
As advised by @nice_dev I added the secure options to my call on setcookie:
setcookie('Datas', json_encode($cookiesArray), $expiry, '/', $_SERVER['HTTP_HOST'], TRUE, TRUE);
Note: That's perfect, this modification on the server didn't made me loose any of my Cookie.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
