douxi5940 2015-08-30 15:13
浏览 55
已采纳

在SESSION变量中无法将新id与id匹配

Using PHP, my objective is to prevent the addition of a duplicate ID into a SESSION cart. The ID is passed from a form. The error message works for the first item only. Other items already in the cart bypass the conditional statement and are added to the array, although the first item at any point gets caught by it. Various trial and error remedies have failed.

Any assistance is appreciated. Let me know if this challenge is not described clearly. Thank you in advance.

Here's the code:

// If user clicks add button
if(isset($_POST['action']) && $_POST['action'] === 'Add'){ 

// If cart has content, check if new content already in cart
if(!empty($_SESSION['cart'])){

    foreach($_SESSION['cart'] as $id){
        if($_POST['id'] === $id){
            $errMsg = 'Item ' . $_POST['id'] . ' already in cart.';
            include 'error.html.php';
            exit();                                              
        }else{
           // Add new content to cart
           $_SESSION['cart'][] = $_POST['id'];
           header('Location: .');
           exit();
        }
    }          
}
  • 写回答

2条回答 默认 最新

  • dougong9987 2015-08-30 18:19
    关注

    try this code, it should work, also there was an xss vulnerability in this code so i fixed it too.

    read owasp's guide for more info https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)

    <?php
    session_start();
    // If user clicks add button
    if($_POST['action'] === 'Add'){
        if(in_array($_POST['id'], $_SESSION['cart'])){
            $errMsg = 'Item ' . htmlentities($_POST['id'],ENT_QUOTES) /* Cross Site Scripting */ . ' already in cart.';
            include 'error.html.php';
            exit();
        }
        // Add new content to cart
        $_SESSION['cart'][] = $_POST['id'];
        header('Location: .');
        exit();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应