palmi
palmi

Reputation: 73

Cookie Not Being Set in PHP

There is a problem in setting the cookie in PHP. This is the code that I am using to set a cookie if a checkbox is checked.

<?php 
    if(isset($_POST['remember'])){
    setcookie("loggedemail",$email,"time()+3600","/");
    setcookie("loggedpassword",$password,"time()+3600","/");
    echo $_COOKIE['loggedemail'];
    echo $_COOKIE['loggedpassword'];
}
?>

Here 'remember' is the id of the checkbox that I am using to set the cookies. The issues here are

Also, I am not able to delete the session cookie when a person logs out of the session. session_destroy(); does not seem to be doing the trick because Chrome still shows the cookie to be set active.

How do I solve these problems?

Upvotes: 0

Views: 831

Answers (4)

Mihai Stancu
Mihai Stancu

Reputation: 16107

The value of $_COOKIE is set by reading cookies received from the browser.

In order to receive a cookie from the browser it must be: set in PHP -> the browser should load -> the user should navigate to the next page (or submit a form).

So basically if you use setcookie you can't read $_COOKIE yet until the next refresh. That's why the echos weren't showing anything. They were showing NULL - to confirm this use var_dump and you'll see the output.

Upvotes: 1

walther
walther

Reputation: 13600

If you do it like this:

setCookie("cookieName", "value", time() + 3600);

It has to work (if you didn't alter any browser settings). However, the variable isn't available till the next load of the page. You should be able to see it in Chrome dev tools though. If not, make 100% sure you're not outputting ANYTHING before you set the cookie.

Concerning your second problem, session_destroy() destroys a session, but it doesn't invalidate cookies already sent to the client. You need to manually invalidate them by setting their expiration time.

Upvotes: 1

Geek Num 88
Geek Num 88

Reputation: 5312

session_destroy() does not unset the cookie with the session id in it, it only trashes the session data.

You say the checkbox has the id attribute of 'remember' - does it have a name attribute? if not that is why everything is not working id's are not posted to the form action per HTML definition.

Upvotes: 0

GBD
GBD

Reputation: 15981

You are passing time as string. here is problem so change your php code as below

setcookie("loggedemail",$email,time()+3600,"/");
setcookie("loggedpassword",$password,time()+3600,"/");

Cookie are not part of session so you can't use session_destroy().

If you want to delete cookie, then you have to set time as past time as below

setcookie("loggedemail", "", time()-3600);

Upvotes: 0

Related Questions