Making a "remember login" function I'm trying to make a safe "remember me / auto login" function on my site and as I'm just a hobby programmer I would like someone professional to take a look at my code this far. This site will probably never see the light of day I'm just doing this because I find it fun and learning, but I still like to do it correct. I have read this.

Login.php

$query = $db-&gt;prepare('SELECT id, username, password FROM users WHERE username = ? OR email = ?');
$query-&gt;execute(array($_POST['username'], $_POST['username']));
$row = $query-&gt;fetch();

if ($row and password_verify($_POST['password'], $row['password'])) {

    // Remember?
    if (isset($_POST['remember'])) {

        $selector = base64_encode(random_bytes(9));
        $authenticator = random_bytes(33);

        setcookie('remember', $selector.':'.base64_encode($authenticator), time() + 864000);

        $query = $db-&gt;prepare('INSERT INTO auth_tokens (selector, token, userid, expires) VALUES (?, ?, ?, ?)');
        $query-&gt;execute(array(   $selector, hash('sha256', $authenticator), $row['id'], date('Y-m-d\TH:i:s', time() + 864000)  ));  
    }

    $_SESSION['userid'] = $row['id'];
    $_SESSION['username'] = $row['username'];

    exit(header('Location: /'));
}


This is my logout:

session_destroy();

if (!empty($_COOKIE['remember'])) {
    setcookie('remember', '', time() - 1000);
    $db-&gt;exec('DELETE FROM auth_tokens WHERE userid = '.$_SESSION['userid']);
}

exit(header('Location: '.SITE_URL));


And this is my code in index.php to check if the user has the cookie and log them in:

if (empty($_SESSION['userid']) &amp;&amp; !empty($_COOKIE['remember'])) {

    list($selector, $authenticator) = explode(':', $_COOKIE['remember']);

    $query = $db-&gt;prepare('SELECT * FROM auth_tokens WHERE selector = ?');
    $query-&gt;execute(array($selector));
    $row = $query-&gt;fetch();

    if (hash_equals($row['token'], hash('sha256', base64_decode($authenticator)))) {
        $_SESSION['userid'] = $row['userid'];
    }
}


One thing I need to do is check if the cookie has expired and log them out, but other than that what do you think? Am I missing something?
You are doing good. You are referencing a good example. 
The flow will be as below: 


Once the user logs in and have checked "remember me", set the cookie with a unique token for user.
Next time when the user comes back, check the cookie with the token value in DB.
If it matches, allow the user to login.
If the token is missing redirect to login.


Ref: 
http://jaspan.com/improved_persistent_login_cookie_best_practice