title: PHP authentication with multiple domains and subdomains
body: <p>I have one main domain: <code>main.com</code>, subdomains: <code>test1.main.com</code>, <code>test2.main.com</code> and other domains <code>one.com</code>, <code>two.com</code>.</p>
  
  <p>Now it's done like these:</p>
  
  <pre><code>ini_set("session.cookie_domain", ".main.com");
  
  $domain = 'main.com';
  </code></pre>
  
  <p>login.php</p>
  
  <pre><code>$user = $db-&gt;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;
  }
  </code></pre>
  
  <p>added on each page:</p>
  
  <pre><code>if(!isset($_SESSION['user_id']))
  {
    if(isset($_COOKIE['email']) &amp;&amp; isset($_COOKIE['password']))
    {
      $email = $_COOKIE['email'];
      $password = $_COOKIE['password'];
  
      $user = $db-&gt;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-&gt;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'];
    }
  }
  </code></pre>
  
  <p>logout.php</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>But it works only on domain <code>main.com</code> and its subdomains <code>test1.main.com</code>, <code>test2.main.com</code>.</p>
  
  <p>I need to somehow save the session and on other domains <code>one.com</code>, <code>two.com</code>.</p>
  
  <p>How best to do safe authentication, if there are solutions, i really confused, please tell with example.</p>