CodeIgniter 內建 Cart 類別預設限制商品名稱僅能包含英數字、破折號、底線、冒號與空格,導致中文商品名稱無法加入購物車。本文提供修正正則與最佳實踐建議。
檔案:system/libraries/Cart.php 第 186-190 行:
if (!preg_match("/^[".$this->product_name_rules."]+$/i", $items['name'])) {
log_message('error', 'An invalid name was submitted as the product name: '.$items['name'].' The name can only contain alpha-numeric characters, dashes, underscores, colons, and spaces');
return FALSE;
}
預設 $this->product_name_rules = a-z0-9:_\-\s,不含中文字元。
直接擴充允許字元範圍,支援中文、全形符號:
<?php
// 在 application/libraries/MY_Cart.php 繼承覆蓋(不修改核心)
class MY_Cart extends CI_Cart {
public function __construct() {
parent::__construct();
// 擴充:中文、日文、韓文、全形標點、空格
$this->product_name_rules = 'a-z0-9:_\-\s\x{4e00}-\x{9fff}\x{3040}-\x{309f}\x{30a0}-\x{30ff}\x{ac00}-\x{d7af}\x{ff00}-\x{ffef}';
}
}
說明:使用 Unicode 範圍,需在正則加 u 修飾符(CI 3.x 已支援)。
/* 註解掉驗證邏輯
if (!preg_match("/^[".$this->product_name_rules."]+$/i", $items['name'])) {
log_message('error', 'An invalid name was submitted...');
return FALSE;
}
*/
風險:失去輸入驗證,可能導致 XSS、資料庫編碼問題或前端顯示異常。
<?php
// 控制器中
$name = $this->input->post('product_name');
// 過濾危險字元,保留中英數常用符號
$name = preg_replace('/[^\p{L}\p{N}\p{P}\s]/u', '', $name);
// 或直接 urlencode 存儲,前端解碼顯示
$name = urlencode($name);
$this->cart->insert([
'id' => $id,
'qty' => $qty,
'price' => $price,
'name' => $name,
'options' => ['size' => 'L']
]);
application/libraries/MY_Cart.phpconfig/config.php 有 $config['subclass_prefix'] = 'MY_';utf8mb4_general_ci(支援 Emoji)database.php 設定 'charset' => 'utf8mb4', 'dbcollat' => 'utf8mb4_general_ci'<meta charset="utf-8">最佳實踐:採用方案一(擴充正則)+ 方案三(控制器預處理)雙重保障,既保留驗證又靈活處理多語系商品名稱。