简体   繁体   English

如何在另一个页面中访问PHP会话变量?

[英]How to access php session variable in another page?

I have this shopping cart page coded, but i am clueless about how to acces the product id from session in another page? 我已经将此购物车页面编码,但是我不知道如何从另一个页面的会话访问产品ID? Anyone please help me! 有人请帮助我! I'm beginner so if you please give me example code too it'd help me a lot. 我是新手,所以如果您也给我示例代码,那将对我有很大帮助。

<?php
    session_start();
    $product_ids = array();
//session_destroy();

//check if Add to Cart button has been submitted
if(filter_input(INPUT_POST, 'add_to_cart')){
    if(isset($_SESSION['shopping_cart'])){

        //keep track of how mnay products are in the shopping cart
        $count = count($_SESSION['shopping_cart']);

        //create sequantial array for matching array keys to products id's
        $product_ids = array_column($_SESSION['shopping_cart'], 'id');

        if (!in_array(filter_input(INPUT_GET, 'id'), $product_ids)){
        $_SESSION['shopping_cart'][$count] = array
            (
                'id' => filter_input(INPUT_GET, 'id'),
                'name' => filter_input(INPUT_POST, 'name'),
                'price' => filter_input(INPUT_POST, 'price'),
                'quantity' => filter_input(INPUT_POST, 'quantity')
            );   
        }    
    }
    else { //if shopping cart doesn't exist, create first product with array key 0
        //create array using submitted form data, start from key 0 and fill it with values
        $_SESSION['shopping_cart'][0] = array
        (
            'id' => filter_input(INPUT_GET, 'id'),
            'name' => filter_input(INPUT_POST, 'name'),
            'price' => filter_input(INPUT_POST, 'price'),
            'quantity' => filter_input(INPUT_POST, 'quantity')
        );
    }
}
?>

Use the same code you have here on the other page to get the product_ids 使用另一页上的相同代码获取product_id

//other page
session_start();
$product_ids = array_column($_SESSION['shopping_cart'], 'id');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM