首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

CodeIgniter 完美解決 URL 含中文字符:擴展 CI_URI 類與 permitted_uri_chars 設定

     編輯:PHP 相關知識

CodeIgniter 預設禁止 URL 出現非 ASCII 字符,直接拋錯。手動 urlencode() 無效,因 Web Server 會自動解碼後再傳給 PHP。本文提供「擴展核心類」而非修改核心的優雅方案,並解決空格轉 + 被攔截的問題。

方案:建立 application/core/MY_URI.php 覆寫 _filter_uri

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_URI extends CI_URI {
    protected function _filter_uri($str) {
        if ($str !== '' && $this->config->item('permitted_uri_chars') !== '') {
            $str = urlencode($str);
            if (!preg_match("|^[".preg_quote($this->config->item('permitted_uri_chars'))."]+$|i", $str)) {
                exit('The URI you submitted has disallowed characters.');
            }
            $str = urldecode($str);
        }
        return $str;
    }
}

修正 config.php 允許字符集

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\+\-';  // 新增 + 號

或直接支援中文 Unicode 範圍(實測有效):

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_-u4e00-u9fa5';

補充:IIS 環境下中文參數亂碼處理

若 $_SERVER['REQUEST_URI'] 取得的中文為亂碼(IIS 常見),需手動轉碼:

$uri = iconv("gb2312", "UTF-8", $uri);

根因在於 IIS 預設以 GBK/GB2312 編碼 URL,Apache 則為 UTF-8。轉碼後即可正常取得中文參數。

總結

  • 優先用 MY_URI.php 擴展,不動核心,易維護升級
  • permitted_uri_chars 需加入 + 號防空格攔截
  • 不同 Web Server 編碼行為不同,必要時以 iconv 統一為 UTF-8
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved