如何重定向如果Cookie不等于可值


How To Redirect If Cookie Does Not Equal Vairable

如果cookie不等于有效值,我很难重定向用户。如果它等于vaible,那么它应该继续脚本。这是我重定向的代码:

if(empty($_GET)) {
    //No variables are specified in the URL.
    //Do stuff accordingly
    echo "No variables specified in URL...";
} else {
    //Variables are present. Do stuff:
    $id = htmlspecialchars($_GET["id"]);
    echo 'url query is ' . $id;
}
if(isset($_COOKIE['logged_in']) == $id)
{
    header("Location: test.php");
}
if(isset($_COOKIE['logged_in']) != $id)
{
    //continues the script

请注意,if语句($id)中的vaible是来自url查询的vaibre;例如,如果url是"random.com/test.php?id=17",cookie等于18,则脚本应该重定向。但是,如果url是"random.com/test.php?id=17",并且cookie等于17,那么请保持在同一页面上。如果听起来很完整,我很抱歉。

它不起这个代码的作用:无论vaible等于什么,它都不会重定向。感谢

你在找这样的东西吗。如果是这样,它应该适用于您的情况:

<?php
if(empty($_GET)) {
    //No variables are specified in the URL.
    //Do stuff accordingly
    echo "No variables specified in URL...";
} else {
    //Variables are present. Do stuff:
    $id = htmlspecialchars($_GET["id"]);
    echo 'url query is ' . $id;
}
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in']==$id)
{
    header("Location: test.php");
}
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in']!=$id)
{
    //continues the script
}
?>

只有在发送到客户端后,才会应用标头。如果你想立即重定向,你可以把exit(0)放在header(…)后面。在这种情况下,你将停止执行脚本,并将当前的header发送到浏览器,浏览器将重定向你。

if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in']==$id) {
    header("Location: test.php");
    exit(0);
}
//continues the script

问题是您正在将isset的""(结果)与GET参数$id:的进行比较

if(isset($_COOKIE['logged_in']) == $id)

这意味着"确定是否设置了$_COOKIE['logged_in'],并将该确定与$id进行比较"。PHP将评估返回truefalseisset(如文档中所述),并将该truefalse与表达式的另一侧(==)进行比较,即$id,这在给定的示例中永远不会匹配。如果您查询"random.com/test.php?id=true"(或false),这可能会满足您的需求。

您的这行不是,意思是"确定是否设置了$_COOKIE['logged_in'],并将$_COOKIE['logged_in']值与$id值进行比较",我相信这就是您想要的。在这种情况下,您要做的是首先检查$_COOKIE['logged_in']是否设置为,然后检查$_COOKIE['logged_in']是否与$id匹配,如下所示:

if (isset($_COOKIE['logged_in']) && $_COOKIE['logged_in'] == $id)

如果这没有意义,这里有一个非常明确的版本,它可能更清楚地说明实际发生了什么:

if ((isset($_COOKIE['logged_in']) == true) && ($_COOKIE['logged_in'] == $id))

希望能有所帮助。

您应该添加另一个条件。

 if(empty($_GET)) {
    //No variables are specified in the URL.
    //Do stuff accordingly
    echo "No variables specified in URL...";
} else {
    //Variables are present. Do stuff:
    $id = htmlspecialchars($_GET["id"]);
    echo 'url query is ' . $id;
}
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in'] == $id)
{
    header("Location: test.php");
}
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in'] != $id)
{
    //continues the script

或者使用这个脚本

if(isset($_COOKIE['logged_in']))
{
   if($_COOKIE['logged_in']==$id){
       header("Location: test.php");
   }
   else{
       //another condition to equal is not equal so directly we can use else
       //continues the script
   }
} else {
echo "Cookie not valid or available";
// redirect user 
}