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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)