一起使用Session和Cookies记住我

In my login page I am using Session and Cookies both, session for usual login and cookies when remember me is checked. My code for creating session or setting cookies is:

if(isset($_POST['login'])){ 
$username = $_POST['user_login'];
$password = $_POST['password_login'];
$stmt = $db->prepare("SELECT * FROM userss WHERE username = :username AND password = :password");
$stmt->execute(array(':username'=>$username,':password'=>$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_db = $row['username'];
$pass_db = $row['password'];
if($username == $user_db && $password == $pass_db) {  
    $_SESSION['username']=$username;
    if ($_POST['rememberme']!=NULL) {
        setcookie('username', $username,time()+31556926);
    }
    header("Location:main.php");
}

and then on any page to create a user fuction I am calling session or cookie like this:

if(isset($_COOKIE['username'])||isset($_SESSION['username'])) {
    $username = $_COOKIE['username'];
    $username = $_SESSION['username'];
}

Now my problem is:

  1. Even when remember me is checked session is used and not cookies I tested it by exiting my browser. I can't figure out where code has gone wrong.
  2. In the second code if(isset($_COOKIE['username'])||isset($_SESSION['username'])) { is correct but I am not sure how to define username for both different situations also $username = $_COOKIE['username']; is giving me undefined index username. May be my way of setting cookies has gone wrong.

Replace here

if (isset($_POST['rememberme'])) {
setcookie('username', $username,time()+31556926);
}

And in user functions

if(isset($_SESSION['username']) {
      $username = $_SESSION['username'];
    }
 else if(isset($_COOKIE['username']){
      $username = $_COOKIE['username'];
    }
 else
    {
     //invalid ---
    }