【问题标题】:cookie is working fine in root directory but not working sub directorycookie 在根目录中工作正常,但在子目录中不工作
【发布时间】:2019-01-27 09:31:08
【问题描述】:

我希望当访问者访问我的网站时,它会检查该网站 cookie 之前是否保存在他的浏览器中。如果之前没有保存,则将保存新的cookie。然后,如果他将访问主页,他将被重定向到保存在他的浏览器 cookie 中的页面。为此,我在任何页面中使用此代码:

$exlink =  "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

if(!isset($_COOKIE['saveexperice'])){
    setcookie('saveexperice', $exlink, time()+60*60*24*30, '/');
}

并在主页中使用此代码:

if($_COOKIE['saveexperice']){
    $exlinkr = $_COOKIE['saveexperice'];
     header('Location: ' . $exlinkr);   
}

一切正常。但问题是它只适用于根目录。不工作任何子目录,例如 domain.com/subfolder。 访问者访问时会在此处制作cookie,但如果他访问主页,则不会重定向子文件夹。如果我访问根目录的任何页面,例如 domian.com/about.php,cookie 将被保存并返回我的主页,它会将我重定向到我保存的 cookie 页面,即 domain.com/about.php。 我希望它需要在子文件夹页面中工作。 我该怎么做?

【问题讨论】:

  • 因为您只是在设置 cookie if 它还没有根据您的代码设置。 if(!isset($_COOKIE['saveexperice'])) {
  • 是的,我用过,只有在没有设置 cookie 的情况下才需要设置 cookie,现在 cookie 没有问题,现在问题是我不能从 sub 使用 cookie 主域(根目录)目录。
  • 现在我有解决方案github.com/hmbashar/…

标签: php cookies


【解决方案1】:

各位,我有解决这个问题的方法,有需要的可以查看github链接

设置cookie并使用cookie重定向之前的访问链接

您可以在访问者/客户端浏览器上设置 cookie,然后当访问者离线并再次返回您的网站时,访问者/客户端会在他尝试访问者主页时自动重定向上次访问链接。他/她无法访问主页自动重定向最新链接。清除/删除cookie后,他/她可以再次访问主页。

设置 Cookie 首先,您需要将浏览链接设置为 cookie。只需使用以下代码。

$exlink =  "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
setcookie('saveexperice', $exlink, time()+(60*60*24*30), '/'); // set cookie for 30 days

注意:你必须需要 php 文件。像 .php,如果你的文件是 .html,.css 则 php 不起作用(例如新用户)。并且必须将该代码用于上述所有代码的标题中。例子见截图http://prntscr.com/i7y64e

现在我们已将浏览器上的上次访问链接设置为 cookie

现在我们将从 cookie 中获取该 url。

if(isset($_COOKIE['last_visited_url'])){
    $redirect_url = $_COOKIE['last_visited_url'];       
}

现在我们有了那个 url,你可以将 header() 重定向到那个 url

header('Location: '. $redirect_url);

完整的代码

if(isset($_COOKIE['last_visited_url'])){
    $redirect_url = $_COOKIE['last_visited_url']; // get link from cookie
    header('Location: '. $redirect_url); // redirect cookie link
}

注意:你必须需要 php 文件。像 .php,如果你的文件是 .html,.css 则 php 不起作用(例如新用户)。并且必须将该代码用于上述所有代码的标题中。例子见截图http://prntscr.com/i7y8km

只需为另一个页面设置 cookie 并放置重定向代码 访问会重定向哪个链接?喜欢主页。

Cookie 清除/删除 现在您可以使用该代码删除/清除您的 cookie

$cookieurl =  $_SERVER['REQUEST_URI'];

setcookie('last_visited_url', $current_location, time()-60*60*24*30, '/'); // remove cookie time

header('location: https://link.com'); // inpur link which link redirect after clear cookie

更改 Cookie 链接

$current_location = $_SERVER['REQUEST_URI'];

if(isset($_COOKIE['last_visited_url'])){
 $cookie_location = $_COOKIE['last_visited_url']; 


 if($current_location != $cookie_location){ 

    setcookie('last_visited_url', $current_location, time()+60*60*24*30, '/'); 
 } 
} else {
 setcookie('last_visited_url', $current_location, time()+60*60*24*30, '/'); 
} 

Check Here on github

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多