Maintain Session after closing browser using PHP

Asked

Viewed 467 times

1

I’m making a cart using session, has how to increase the time of session?

below is the class I created for my shopping cart.

class carrinhocompra{
public function __construct(){
    if(!isset($_SESSION['carrinho'])){
        $_SESSION['carrinho'] = array();
    }
}

public function adicionar($id, $qtd=1, $form_id=NULL){
    if(is_null($form_id)){
        $indice = sprintf("%s:%s", (int)$id, 0);

    } else {
        $indice = sprintf("%s:%s", (int)$id, (int)$form_id);
    }

    if(!isset($_SESSION['carrinho'][$indice])){
        $_SESSION['carrinho'][$indice] = (int)$qtd;
    }


}

public function aterarQtd($indice, $qtd){
    if(isset($_SESSION['carrinho'][$indice])){
        if($qtd > 0){
            $_SESSION['carrinho'][$indice] = (int)$qtd;
        }
    }
}

public function excluirProd($indice){
   unset($_SESSION['carrinho'][$indice]);
}

}

  • If the answer helped you or solved your problem, take a vote and mark it as the correct answer, otherwise give more details about what you tried and the results. Always vote and choose the right answers is good practice and helps other users.

1 answer

2


For this, you need to use cookies:

setcookie('carrinho', $_SESSION['carrinho'], time() + 60 * 60 * 24);
//Esse cookie expira em um dia, você pode alterar o valor de acordo com a sua necessidade

And at the time of showing the cart, you check whether the cookie exists:

$carrinho = $_COOKIE['carrinho'];
  • or I edited and put like this the class to my cart is just change where is $_Session to $_cookie or I have to do more thing?

  • session and cookie are two different things and go to work together, you check if there is something in the cookie and read it to fill in the cart information, any changes in the cart you need to update the cookie. You keep using sessions as before for other features.

Browser other questions tagged

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