php没有设置无限的cookie

Ok, so now I have this code in my login form handler .php file:

<?php
    $username = "root";
    $password = "root";
    $hostname = "localhost";
    $db = "agendadb";
    $db = new mysqli($hostname, $username, $password, $db);
  $res = $db->query("SELECT userId FROM tblUsers WHERE username='".$_POST['username']."' AND password='".md5($_POST['password'])."'");
  if($res){
    if($row =  $res->fetch_assoc()){
      setcookie('userId', strval($row['userId']), 2147483647);
      $_COOKIE['userId']= $row['userId'];
      echo 1;
    }else{
      echo -2;
    }
  }else{
    echo -1;
  }
?>

Somewhy, the cookie userId is not being set, and I can't figure out why. The script is working because it echoes the result correctly, but the cookie is not being set and no errors are thrown.

In the begining of my index page I have the following code to check if the cookie has been set

<?php
echo '<script>';

if(!isset($_COOKIE['userId'])){
  echo 'console.log(" isset");';
}
if(empty($_COOKIE['userId'])){
  echo 'console.log(" empty");';
}
if($_COOKIE['userId']==""){
  echo 'console.log(" ==");';
}
echo '</script>';
?>

and after loging in my console in index.php always shows isset empty ==

Also, I tried using ob_start(); and ob_end_flush(); in the login handler .php file, but did not work either.

Any help would be appreciated.

Here are a few reasons why your cookie but not be being set.

Not accessible by the domain

Is it being set on the same directory as this script (are both your files in the exact same directory)? If not, then you need to specify the fourth parameter of the cookie to make it available to the whole domain, as well as fixing your parameters.

setcookie('userId', strval($row['userId']), time() + 2147483647, "/");

Stale cookie or wrong sub-domain

If your website is querying both www and non-www versions, then you may be getting different cookies because they are being treated as different sub-domains. You can change your htaccess to fix this, or you can check by going into your development console and typing document.cookie and comparing the two pages

Cookies aren't sent until second request or cache-related

Cookies are also not set on the first request on the script, as they only created once the request is finished. You should refresh the page again to make sure that's not happening. Your browser could also be caching and not getting the new cookie, it'd be best for you to clear all your cookies related to your test-site first before proceeding to fix your problem.

And also, an "infinite" cookie isn't possible.