如何销毁 PHP 中的特定会话变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28602173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:58:06  来源:igfitidea点击:

How do I destroy a specific session variable in PHP?

phpsession

提问by Benedict Payot

I'm currently working on a shopping cart system. It requires a user login to access the cart. So I've wrote some codes to disable access of the cart page if the user is not logged in. However, whenever I try to empty the cart, I get logged out. I just want to destroy the cart session and not the user session. Here's my code:

我目前正在研究购物车系统。它需要用户登录才能访问购物车。因此,如果用户未登录,我编写了一些代码来禁用对购物车页面的访问。但是,每当我尝试清空购物车时,我都会退出。我只想销毁购物车会话而不是用户会话。这是我的代码:

For the cart page:

对于购物车页面:

<?php
  session_start();
  if(isset($_SESSION['userID'])){

  }
  elseif(!isset($_SESSION['userID'])){
      echo 
      "<script>
        alert('You must be logged in.');
        window.location.href='index.php#login'
      </script>";
    }
?>

  <?php
    include ('../import/layout.php');
  ?>

  <body>

    <div class="site-wrapper" id="index">

      <div class="site-wrapper-inner">

        <div class="cover-container">

          <?php
            include ('../import/nav-two.php');
          ?>

          <!-- <div class="inner cover">

          </div>

          <div class="mastfoot">
            <div class="inner">
              <p>&copy; 2015 Aroma Chicken House Restaurant, All Rights Reserved.
                 <a class="menu-item pull-right" href="#index">Back to Top</a>
              </p>
            </div>
          </div> -->

        </div>

        <div id="cart">
          <div class="container">
            <?php
              include ('../cart/index.php');
            ?>
          </div>
        </div>


      </div>

    </div>


  </body>

For the cart update:

对于购物车更新:

<?php
session_start();
include_once("config/config.php");

//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
    $return_url = base64_decode($_GET["return_url"]); //return url
    session_destroy();
    header('Location:'.$return_url);
}

//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
    $product_code   = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
    $product_qty    = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
    $return_url     = base64_decode($_POST["return_url"]); //return url

    //MySqli query - get details of item from db using product code
    $results = $mysqli->query("SELECT product_name,price FROM products WHERE product_code='$product_code' LIMIT 1");
    $obj = $results->fetch_object();

    if ($results) { //we have the product info 

        //prepare array for the session variable
        $new_product = array(array('name'=>$obj->product_name, 'code'=>$product_code, 'qty'=>$product_qty, 'price'=>$obj->price));

        if(isset($_SESSION["products"])) //if we have the session
        {
            $found = false; //set found item to false

            foreach ($_SESSION["products"] as $cart_itm) //loop through session array
            {
                if($cart_itm["code"] == $product_code){ //the item exist in array

                    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$product_qty, 'price'=>$cart_itm["price"]);
                    $found = true;
                }else{
                    //item doesn't exist in the list, just retrive old info and prepare array for session var
                    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
                }
            }

            if($found == false) //we didn't find item in array
            {
                //add new user item in array
                $_SESSION["products"] = array_merge($product, $new_product);
            }else{
                //found user item in array list, and increased the quantity
                $_SESSION["products"] = $product;
            }

        }else{
            //create a new session var if does not exist
            $_SESSION["products"] = $new_product;
        }

    }

    //redirect back to original page
    header('Location:'.$return_url);
}

//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
    $product_code   = $_GET["removep"]; //get the product code to remove
    $return_url     = base64_decode($_GET["return_url"]); //get return url


    foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
    {
        if($cart_itm["code"]!=$product_code){ //item does,t exist in the list
            $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
        }

        //create a new product list for cart
        $_SESSION["products"] = $product;
    }

    //redirect back to original page
    header('Location:'.$return_url);
}
?>

回答by Markus Müller

What about

关于什么

unset($_SESSION["products"])

instead of the

而不是

session_destroy()

There is only one session per user. So there is no way to destroy a "specific" session. What you can do is delete the contents of your session responsible for the display of the cart (as shown above).

每个用户只有一个会话。所以没有办法销毁“特定”会话。您可以做的是删除负责显示购物车的会话内容(如上所示)。

回答by Naved Munshi

you can use

您可以使用

  unset($_SESSION["products"]);

回答by Venkata Krishna

Use,

用,

unset($_SESSION["products"]);

session_destroy()will destroy all the sessions, while the above line would destroy a specific session variable.

session_destroy()将销毁所有会话,而上面的行将销毁特定的会话变量。

回答by Salketer

What you want is not to destroy the session, as you want to keep the user logged in. The best way to do that is by removing or overwriting your cart's variables as needed. You can either unset($_SESSION['products']);remove the variable completely, or $_SESSION['products'] = array();reset it to an empty cart.

您想要的不是破坏会话,因为您想让用户保持登录状态。最好的方法是根据需要删除或覆盖购物车的变量。您可以unset($_SESSION['products']);完全删除变量,也可以将其$_SESSION['products'] = array();重置为空购物车。

At some point (if you save the cart in database later) you might want to use the same code as you do when removing an item from the cart for all the items present in it...

在某些时候(如果您稍后将购物车保存在数据库中),您可能希望使用与从购物车中删除项目中存在的所有项目时相同的代码......

回答by Tanjima Tani

Use unset()for all the session variables specific to either site 1 or 2.

使用unset()的所有会话变量具体到站点1或2。

unset($_SESSION['var1']);
//or
unset($_SESSION['var2']);

回答by navjot singh

use the unset() instead of session_destroy(). where unset point the particular variable, were session_destroy destroy all the session variables.

使用 unset() 而不是 session_destroy()。在未设置特定变量的地方, session_destroy 会破坏所有会话变量。

unset($_SESSION["products"])

回答by navjot singh

unset()func is useful in this case.

unset()func 在这种情况下很有用。

session_destroy()func will destroy

session_destroy()func 会破坏

回答by Hacker

session_destroy()is destroy all session variable and unset(session variable)destroy a particular session variable.

session_destroy()是销毁所有会话变量并unset(session variable)销毁特定会话变量。

回答by learner

Specific session's value can be set to "null" and then check that session's value using empty() function where it is needed Or specific session's value can be set to some value let say 0 and then check session's value with set value for performing some operations.

可以将特定会话的值设置为“null”,然后在需要时使用 empty() 函数检查该会话的值,或者可以将特定会话的值设置为某个值,例如 0,然后使用设置值检查会话的值以执行某些操作.