I have some PHP session test code - to ensure the logged in user is valid.
I'll just explain some of the functions: is_logged_in just checks to see if some session variables are set and test_duplicate connects to the database to check if there is a row with a column equaling the value.
function check_account(){
if(is_logged_in()){
// Destroy session if the user doesn't exist.
if(test_duplicate("username", $_SESSION["user"])){
session_destroy();
}
}
if($_SESSION["valid_day"] != date("Ymd")){
// Destroy session if the key has expired
session_destroy();
}
}
function test_duplicate($field, $value){
$mysqli = database_connect();
$statement = $mysqli->prepare("SELECT * FROM users WHERE " . $field . " = ?");
$statement->bind_param("s", $value);
$statement->execute();
$statement->store_result();
$rows = $statement->num_rows;
if($rows > 0){
return FALSE;
}
return TRUE;
}
function database_connect(){
if(!isset($dbconnection)){
$config = get_configuration();
// Create connection
$mysqli = new mysqli($config["hostname"], $config["username"], $config["password"], $config["database"]);
if($mysqli->connect_error){
die("<h1>Error 1 :: Critical backend failure</h1>");
}
if(!check_tables($mysqli)){
die("<h1>Error 2 :: Critical backend failure</h1>");
}
$dbconnection = $mysqli;
return $mysqli;
}else{
return $dbconnection;
}
}
The problems:
test_duplicate function takes about 3-4 seconds to completeMy current solutions (I don't think these are particularly good):
I would suggest:
test_duplicate function.select *, return a single integer value. Better still instead of hadling it as a row returning query, hadle it as a scalar query that returns a single value.Update
Here's a query that returns 1 if there is a row with a specified value in username; or 0 if no matching row exists:
select
ifnull(
(
select
1 as user_exists
from
dual
where
exists(
select * from users where username = 'test2'
)
), 0) as result
from dual