Thursday, April 15, 2010

Secure PHP Session

I have been working on this class for a day or so, and would like to post it up to see if anyone can find fault with it. It uses mysql to store session information. Right now the information is unencrypted, that feature will be added eventually. Let me know what you think (haha if anyone ever even comes across this blog...)

- replace the connectDb() class with whatever it is you use to connect to the database.


class session();
{
public $sessionKey;
public $value;

function __construct()
{
session_start();
$time = time();
$expTime = $time - 1200;
$db = new connectDb(); //connect to da database.
$killOldData = "DELETE * FROM sessionData WHERE time < '$expTime'";
mysql_query($killOldData);
$this->changeKey();
}

private function changeKey()
{
$oldKey = $_SESSION['key'];
$newKey = $this->generateNewKey();
$checkQuery = "SELECT * FROM sessionData WHERE lock = '$newKey'";
while(!$dup)
{
//this might be slow. gonna see how it works out.
$check = mysql_query($check);

if(mysql_num_rows($check) > 0)
{
$newKey = $this->generateNewKey();
}
else
{
$_SESSION['key'] = $newKey;
$changeKey = "UPDATE sessionData SET lock = '$newKey' WHERE lock = '$oldKey'";
mysql_query($changeKey);
mysql_query("UPDATE sessionData SET time = '$time' WHERE lock = '$newKey'");
$dup = true;
}
}
}

function retreiveData()
{
$time = time();
$key = $_SESSION['key']
$getSessionData = mysql_query("SELECT * FROM sessionData WHERE lock = '$key' AND key = '$this->sessionKey'");
mysql_query("UPDATE sessionData SET time = '$time' WHERE lock = '$key'");
while($sessionData = mysql_fetch_assoc($getSessionData))
{
$data = $sessionData['value'];
}
}

function updateData()
{
$time = time();
$key = $_SESSION['key'];
$query = "UPDATE sessionData SET ".$this->sessionKey." = '".$this->value."' WHERE lock = '$key'";
mysql_query("UPDATE sessionData SET time = '$time' WHERE lock = '$key'");
mysql_query($query);
unset($this->value);
}

function addData()
{
$time = time();
$key = $_SESSION['key'];
$time = time();
$query = "INSERT INTO sessionData (lock, key, value, time) VALUES ('$key', '$this->sessionKey', '$this->value', '$time')";
mysql_query($query);
unset($this->value);
}

private function generateNewKey()
{
return sha1(uniqid(mt_rand(), true));
}
}