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

时间:2018-06-13 22:29:25

标签: php session

我已将此购物车页面编码,但我对如何从另一个页面中的会话访问产品ID一无所知?有人请帮帮我!我是初学者,所以如果你也请给我示例代码,它会帮助我很多。

<?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')
        );
    }
}
?>

1 个答案:

答案 0 :(得分:0)

使用您在其他页面上使用的相同代码来获取product_ids

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