Capture cookie set

0

I'm developing a system and my idea is to use cookies to save the data (at least login).

I have the login page (login.php), and a JavaScript sending the AJAX data from the login page to PHP (data.php).

In PHP, it calls the Login method and does the same. After logging in, before returning to JavaScript, I initialize a number of cookies, but after login, on any other page, I can not access them. Below is the code:

data.php

$login = $Admin->login($admin["txtMail"], $admin["txtPassword"]);
if(!$login){
    echo json_encode([
        "success"       => false,
        "description"   => "incorrect data"
    ]);
}else{
    $Admin->setId($admin['txtMail']);
    setcookie('user_mail', $admin['txtMail'], (time() + (30 * 24 * 3600)));
    setcookie('user_id', $Admin->getId(), (time() + (30 * 24 * 3600)));
    setcookie('is_logged', true, (time() + (30 * 24 * 3600)));
    echo json_encode([
        "success" => true
    ]);
}

Now on the login page, I call $_COOKIE['user_id'] just to check if cookies are working and what returns me is this:

  

Notice: Undefined index: user_id in C: \ xampp \ htdocs \ Project_app \ admin \ login.php on line 7

Code below:

<?php
    ob_start();
    session_start();
    if(isset($_COOKIE['is_logged']) && $_COOKIE['is_logged']){
        header("Location:   index.php");
    }
    echo $_COOKIE['user_id'];
    require_once('sealed/controllers/controller.php');
?>
    
asked by anonymous 28.12.2018 / 17:33

2 answers

1

It was missing defining the path or route where the cookie could be used within the domain. By default, the cookie can be used in the directory where it was created and in its subdirectories. If we indicate "/" the cookie will be valid within the entire domain.

setcookie('user_id', $Admin->getId(), time() + (30 * 24 * 3600), "/");
    
28.12.2018 / 19:46
-1

Try to remove the parentheses before time() .

Your code:

setcookie('user_mail', $admin['txtMail'], (time() + (30 * 24 * 3600)));

PHP 7 Documentation:

setcookie("CookieTeste", $value, time()+3600);

Your new code would look something like:

setcookie("user_mail", $admin['txtMail'], time() + (30 * 24 * 3600));
echo $_COOKIE['user_id'];
    
28.12.2018 / 19:28