Capture set cookie

Asked

Viewed 196 times

0

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

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

In PHP, it calls the method Login and does the same. After logging in, before returning to Javascript, I initiate several cookies, but after logging into any other page, I can’t 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 the $_COOKIE['user_id'] just to check if the cookies are working and what returns 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');
?>

2 answers

1

It was left to define the path or route where the cookie can 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), "/");

-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'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.