【问题标题】:Require cookie to view website, or be redirected to different page (PHP)需要 cookie 才能查看网站,或被重定向到不同的页面 (PHP)
【发布时间】:2014-08-20 22:31:31
【问题描述】:

简单的请求;我需要我网站的访问者拥有特定的 cookie 才能查看该网站。当用户访问 my.site.com/anydirectory/anypage.php 时,他们需要被重定向到 my.site.com/index.php 向他们发出警告并选择走开继续。如果他们继续,则会设置一个 cookie,并将他们带到最初请求的页面(并最终可以访问整个站点,至少 90 天)。如果他们选择 Walk Away,则设置不同的 cookie 并将他们重定向到 my.site.com/bummer.php,并将继续被定向到 bummer.php 页面,直到 90 天结束,或者他们删除 cookie,以先到者为准。

这就是我所拥有的;

我把它放在我所有页面的顶部...

<?php if (!isset($_COOKIE['youwerewarned'])) {
header("Location: /index.php?url=http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]")
}
?>

...然后我把它放在我的 index.php 页面的顶部...

<?php

// change to your domain name.
$domain = "my.site.com";

// Get the requested page, add it to our domain so we can create an enter link
if (isset($_GET['request'])) {
$request ="<a href='http://$domain" . $_GET['request'] . "'>";
}

// The exit link
{
$leave ="<a href='http://my.site.com/bummer.php'>";
}

// Set a cookie so we are not redirected back here again. You can set how long the cookie is good.
if (!isset($_COOKIE['youwerewarned'])) {
setcookie('youwerewarned','true',time()+6048... . $domain);
}

?>

...然后我把它放在index.php页面的适当位置...

<?php echo $leave ?>WALK AWAY</a>&nbsp;&nbsp;&nbsp;<?php echo $request ?>CONTINUE</a>

...我错过了什么?

【问题讨论】:

  • 这不起作用如何?你检查过cookies是否真的被设置了吗?也许您遇到了过早的标头发送问题。
  • “我错过了什么?” - 标题的分号。开启error reporting,将向Parse error: syntax error, unexpected '}'in... IF 发出信号,这是您的实际工作代码,而不仅仅是复制/粘贴错误。

标签: php redirect cookies


【解决方案1】:

据我所知,您缺少一个结束/结束分号:

header("Location: /index.php?url=http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]")

做:

header("Location: /index.php?url=http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");

然后有这一行,我不知道这 => ... . 是否是您实际代码的一部分。

setcookie('youwerewarned','true',time()+6048... . $domain);

应该读作

setcookie("youwerewarned", "true", time()+6048, "/", $domain);

开启error reporting,会发出信号

解析错误:语法错误,意外 '}',期待 ',' 或 ';'在...(文件路径)第 X 行

为缺少的分号。

【讨论】:

  • 谢谢,我想知道,除了错误之外,一切都应该在哪里?
  • @RickSmalls 不客气,瑞克。我相信是的,我测试了代码,它运行良好。 var_dump($_COOKIE); 确实显示为 cookie 的名称。
  • 它正在工作,有点。 &lt;?php echo $leave ?&gt;WALK AWAY&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;?php echo $request ?&gt;CONTINUE&lt;/a&gt; 链接无效。 Continue 根本不起作用,当您单击 Walk Away 时,它应该设置一个完全不同的 cookie。当它重定向到索引时,无论点击什么,它都会设置 cookie。点击 Walk Away 链接时,有没有办法设置不同的 cookie?
  • @RickSmalls 我注意到index.php?url$_GET['request'] 这两个应该相互关联/连接吗?我需要知道request 的来源以及您正在使用的url GET 方法。如果您有更多代码要给我看,请告诉我以及您是如何使用它的。
  • @RickSmalls 至于设置不同的cookie名称;是的,我会说你可以将它设置在bummer.php 中作为else{...}if 条件if (!isset($_COOKIE['youwerewarned'])) 一起使用,这样你就可以做if (!isset($_COOKIE['youwerewarned'])){...}else{ setcookie("different_name", "true", time()+6048, "/", $domain); 类型的事情。 bummer.php 里面有什么?
猜你喜欢
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 2018-11-15
相关资源
最近更新 更多