电商平台(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
$conis 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_titleis set to unique), you won't get any feedback to debug the issue. - Empty Form Action: While an empty
actionworks (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?
- Prepared Statements: We swapped direct SQL insertion for a prepared statement, which separates user input from SQL logic entirely, eliminating SQL injection risks.
- Connection Validation: Added a check to ensure
$conis a valid connection before running any queries. - Error Handling: Added an
elseblock to catch failed queries and show a helpful error message (note: in production, replacemysqli_error($con)with logging to a secure file instead of displaying it to users). - Explicit Form Action: Used
htmlspecialchars($_SERVER['PHP_SELF'])to safely define the form submission target and prevent XSS in the action attribute. - Input Sanitization: Used
trim()to remove extra whitespace andhtmlspecialchars()to escape special characters, which helps prevent XSS when you display the category name on your site.
Additional Recommendations
- Set the
cat_titlecolumn in yourcategoriestable toUNIQUEto prevent duplicate categories from being inserted. - In production, disable PHP error display (
display_errors = Offin 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
相关产品推荐
相关产品推荐

