当前位置: 动力学知识库 > 问答 > 编程问答 >

session - PHP Cookies not being loaded when coming from a clicked link

问题描述:

I'm working on a website that is keeping a user session token in $_SESSION. When I type the URL directly, I can load the cookies just fine, but when I click on a page that loads the cookie through PHP, it can't find the cookie. Is there any way to get around this?

Here's the code for saving the cookie

setcookie("tpl_token", $token, time()+365*24*60*60, "/");

And for retrieving

if(isset($_COOKIE['tpl_token'])){

$token = $_COOKIE['tpl_token'];

} else {

echo "Cookie not set";

}

It is returning that cookie is not set.

网友答案:

In order to create a session in PHP, use the session_start() function. PHP handles sessions internally for you, so you do not have to do any dirty work.

Example:

session_name("tpl_token");
session_start(); //sends session cookie with name "tpl_token"

//create session variable.
$_SESSION["logged_in"] = true;

if(isset($_SESSION["logged_in"])){
//stuff to do if user is logged in already
} else {
//stuff to do if user is not logged in.
}

//Destroy Session/Logout;
session_unset();
session_destroy();

If you are try create session cookies, there is no need for the $_COOKIE[] function

分享给朋友:
您可能感兴趣的文章:
随机阅读: