简体   繁体   中英

Can't retrieve cookies in PHP

I have the following code, in a successful login function:

setcookie('username', $username, time()+60*60*24*365);
setcookie('password', $clean_pw, time()+60*60*24*365);

Where $username and $clean_pw are the plain text login information.

In a test page, I try this:

foreach ($_COOKIE as $key=>$val)
{
    echo $key.' is '.$val."<br>\n";
}

And get as result:

PHPSESSID is 823fc1084766daba506cffc3654e1e23
_gat is 1
_ga is GA1.2.1524905679.1454061204

Why can't I find my login cookies?

edit: also, the cookies are in my browser cookies list. It looks like they aren't in the $_COOKIE

First of all, never EVER set usernames or passwords into cookies. It's a very bad practise as cookies can read by anything. A cookie should be used for something like a "remember me" check, and use a session (that still doesn't contain username or password) to verify the users identity.

With that out of the way, to answer your question, You wont see a cookie that's just been set until you go to the next page (or refresh).

Also, you might also want to consider using the dateTime() class for use in date setting and to set up path and domain for the cookie aswell, like so:

setcookie(name,value,expire,path,domain,secure,httponly);

A $_COOKIE needs to be created using setcookie() :

setcookie(name, value, expire, path, domain, secure, httponly);

More information on $_COOKIE at http://www.w3schools.com/php/php_cookies.asp .


You can use a PHP Session instead to make it more secure.

Firstly, set the $_SESSION :

session_start();
$_SESSION['logged_in'] = true;
header("Location: login.php");

To find out if users are logged in, you can check for the session, if not set, then redirect users back to the Login Page.

<?php

 session_start();
 if(!$_SESSION['logged_in']){
 session_destroy();
 header("Location: login.php");
}

?>

To logout, destroy the Session.

<?php

session_start();
$_SESSION['logged_in'] = 0;
session_destroy();
header("Location: login.php");

?>

Just a tip, you should encrypt the users' usernames and passwords.

Also, never store passwords in cookies or sessions, as there's no use in the first place. It's a better and more secure way to just store true when user is logged in.

Hope this helps!

Try to set cookie with 'path'.

setcookie(name,value,expire,path,domain,secure,httponly);

like

setcookie('username', $username, time()+60*60*24*365, '/');
setcookie('password', $clean_pw, time()+60*60*24*365, '/');

which will specify to all file path on that domain.

you can use session instead of cookies, it may help u

$_SESSION["name"] = "andy";
$_SESSION["pass"] = "00000";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM