I have one main domain: main.com
, subdomains: test1.main.com
, test2.main.com
and other domains one.com
, two.com
.
Now it's done like these:
ini_set("session.cookie_domain", ".main.com");
$domain = 'main.com';
login.php
$user = $db->query("SELECT id, login FROM users WHERE email=? AND password=?",
array($email, $password), "rowassoc");
if($user)
{
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['login'];
$time = 100000;
setcookie('email', $email, time() + $time, "/", "." . $domain);
setcookie('password', $password, time() + $time, "/", "." . $domain);
header('Location: http://' . $user['login'] . "." . $domain);
exit;
}
added on each page:
if(!isset($_SESSION['user_id']))
{
if(isset($_COOKIE['email']) && isset($_COOKIE['password']))
{
$email = $_COOKIE['email'];
$password = $_COOKIE['password'];
$user = $db->query("SELECT id, login FROM users WHERE email=? AND password=?",
array($email, $password), "rowassoc");
if($user)
{
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['login'];
}
}
}
else
{
$user = $db->query("SELECT id, login FROM users WHERE id=?",
array($_SESSION['user_id']), "rowassoc");
if(!$user)
{
setcookie('email', '', time() , "/", "." . $domain);
setcookie('password', '', time() , "/", "." . $domain);
unset($_SESSION['user_id']);
session_destroy();
setcookie("PHPSESSID","",time(), "/", "." . $domain);
}
else
{
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['login'];
}
}
logout.php
if(isset($_SESSION['user_id']))
{
setcookie('email', '', time() , "/", "." . $domain);
setcookie('password', '', time() , "/", "." . $domain);
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
session_destroy();
setcookie("PHPSESSID","",time(), "/", "." . $domain);
header('Location: /main');
exit;
}
But it works only on domain main.com
and its subdomains test1.main.com
, test2.main.com
.
I need to somehow save the session and on other domains one.com
, two.com
.
How best to do safe authentication, if there are solutions, i really confused, please tell with example.
See Question&Answers more detail:
os