In my login script I calculate a value with md5
and then store that in a database. The id for that row is stored in a cookie on the clients computer. However, the value of the cookie is 1 lower then the actual value. What's causing this?
$cookie = md5($_SERVER['REMOTE_ADDR']+$member['username']+$salt)
$tkn = "INSERT INTO cookies (token) VALUES ('$cookie')";
$tknqry = mysql_query($tkn) or die(mysql_error());
$cookievalue = mysql_insert_id();
setcookie("token", $cookievalue, time()+2678400);
Just a guess based off of what you have said in your question. If you use the setcookie()
function it does NOT update the $_COOKIE
array until a new request is made.
//cookie has a value of 1 already
setcookie('token',2);
var_dump($_COOKIE['token'] == 1); //true
var_dump($_COOKIE['token'] == 2); //false
If you were to refresh the page then the value of $_COOKIE['token']
would equal 2. In your case you probably only want to generate a new one if one isn't set so just check to see if $_COOKIE['token']
is already set:
if(!isset($_COOKIE['token'])) {
$cookie = md5($_SERVER['REMOTE_ADDR']+$member['username']+$salt)
$tkn = "INSERT INTO cookies (token) VALUES ('$cookie')";
$tknqry = mysql_query($tkn) or die(mysql_error());
$cookievalue = mysql_insert_id();
setcookie("token", $cookievalue, time()+2678400);
//for debug
echo "cookie set to: $cookievalue";
} else {
//for debug
echo "cookie already set to: {$_COOKIE['token']}";
}
FYI I would not use mysql_
functions as they are deprecated.
From the PHP manual:
http://www.php.net/manual/en/function.mysql-insert-id.php
Caution
mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation.
Maybe this helps a little bit ?