Store a hash in a cookie to identify the user's account to keep logged in after close browser I made a option to user choose to stay logged in even after he closes the browser. It's really simple to implement, but i'm not sure about the hash i used to identify the user that is stored in a cookie. 

To generate the hash i used bin2hex(random_bytes(59/2)) this function generate a string like this one:

118f9bc738e28b5079cf04bc3c88b2754f8ae04c9f1e1127d020389c49


To make sure that it's unique for each user, before register new accounts i check all hashes that i already have in my database.

I only use this hash to identify the user using the cookie, is it safe? The lenght of the hash is good enough to a Brute force attack be impossible, right?

What do you guys think about my code?

register.php

$hash = bin2hex(random_bytes(59/2));


login.php

##
## Get data from database using $_POST variable from &lt;form&gt;
##
if(!empty($_POST['stay_loggedIn'])){
  setcookie('stay_loggedIn', $fetch_data['hash'], strtotime('+14 days'), '/');
}


index.php

if(!empty($_COOKIE['stay_loggedIn']) &amp;&amp; empty($_SESSION['logged_cookie'])){

    ## Set this session variable to run this code only one time
    $_SESSION['logged_cookie'] = 1;

    $hash = $_COOKIE['stay_loggedIn'];
    $logeIn = $conn-&gt;prepare("SELECT * FROM users WHERE `hash` = :hash");
    $logeIn-&gt;bindValue(':hash', $hash, PDO::PARAM_STR);
    $logeIn-&gt;execute();
    $user_data = $logeIn-&gt;fetch(PDO::FETCH_ASSOC);
    ##
    ## Set session variables
    ##
}


logout.php

$params = session_get_cookie_params();
setcookie('stay_loggedIn', '', time() - 3600, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
I think this is a bad approach on two fronts (the second one is more important):


Having to check a randomly generated 'hash' against the database, to see if it has been used before, is inefficient. First of all, this is not a hash, it's a random string. A hash is created from something sensible, to verify it later. Can I assume you already have an unique identifier for each user in your database? You could store that in the cookie, it tells you which user it is. User id's don't need to be a secret. However, you don't want someone to change it and see information from another to user. To prevent this, you could add a small random string to the cookie, and in your database, to verify that they are who they say they are. Such a string is called a 'token'. An user is only valid if the user id and the token in the cookie match with the id and token in the database. Your queries will now probably be quicker because you can use the user id to look up the token.
Staying 'logged in' after closing the browser is done by not erasing the session cookie when the browser closes. It's as simple as that. See: https://www.php.net/manual/en/function.session-set-cookie-params.php (see 'lifetime', it defaults to 0).