You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

电商平台(eShop)新增商品分类功能代码正确性核查请求

Review & Fixes for Your eShop Category Insertion Code

Hey there! Let's walk through your code step by step to spot issues and get it ready for production. Here's what we need to address, plus a revised version of your code:

Key Issues in the Original Code

  • Critical SQL Injection Vulnerability: You're directly inserting user input ($_POST['new_cat']) into your SQL query without sanitization. This lets attackers run malicious SQL commands that could delete your entire categories table or steal sensitive data.
  • No Database Connection Check: The code assumes $con is a valid database connection, but if the connection fails, mysqli_query() will throw unhandled errors that break your functionality.
  • Missing Error Handling for Queries: If the insert fails (e.g., duplicate category name if your cat_title is set to unique), you won't get any feedback to debug the issue.
  • Empty Form Action: While an empty action works (submits to the current page), it's more explicit to define it, which improves readability and avoids edge cases in some browsers.
  • Potential XSS Risk: If you display the category name on your site later, unfiltered user input could lead to cross-site scripting attacks (attackers injecting malicious scripts into your pages).

Fixed & Secure Code

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" style="padding:80px;">
    <b>Insert New Category:</b>
    <input type="text" name="new_cat" required/>
    <input type="submit" name="add_cat" value="Add Category" />
</form>

<?php
// First, validate database connection exists
if (!isset($con) || !$con) {
    die("Error: Database connection not established.");
}

if(isset($_POST['add_cat'])){
    // Sanitize input to prevent XSS (always use when outputting this data later too!)
    $new_cat = trim($_POST['new_cat']);
    $new_cat = htmlspecialchars($new_cat, ENT_QUOTES, 'UTF-8');

    // Use prepared statements to eliminate SQL injection risks
    $insert_cat = "INSERT INTO categories (cat_title) VALUES (?)";
    $stmt = mysqli_prepare($con, $insert_cat);
    mysqli_stmt_bind_param($stmt, "s", $new_cat);
    $run_cat = mysqli_stmt_execute($stmt);

    if($run_cat){
        echo "<script>alert('New Category has been inserted!')</script>";
        echo "<script>window.open('eshop.php?view_cats','_self')</script>";
    } else {
        // For development only - replace with file-based logging in production
        echo "<script>alert('Error inserting category: " . mysqli_error($con) . "')</script>";
    }

    // Clean up the prepared statement
    mysqli_stmt_close($stmt);
}
?>

What Changed?

  1. Prepared Statements: We swapped direct SQL insertion for a prepared statement, which separates user input from SQL logic entirely, eliminating SQL injection risks.
  2. Connection Validation: Added a check to ensure $con is a valid connection before running any queries.
  3. Error Handling: Added an else block to catch failed queries and show a helpful error message (note: in production, replace mysqli_error($con) with logging to a secure file instead of displaying it to users).
  4. Explicit Form Action: Used htmlspecialchars($_SERVER['PHP_SELF']) to safely define the form submission target and prevent XSS in the action attribute.
  5. Input Sanitization: Used trim() to remove extra whitespace and htmlspecialchars() to escape special characters, which helps prevent XSS when you display the category name on your site.

Additional Recommendations

  • Set the cat_title column in your categories table to UNIQUE to prevent duplicate categories from being inserted.
  • In production, disable PHP error display (display_errors = Off in php.ini) and log errors to a secure file instead.
  • Add server-side validation for the category name (e.g., minimum length, allowed characters) to improve user experience and data quality.

内容的提问来源于stack exchange,提问作者Thanasis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:56:39