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

PHP 中配置 FCKeditor 編輯器完整指南:精簡部署與中文優化

     編輯:PHP 相關知識

前言

FCKeditor (現已更名為 CKEditor 4/5) 曾是 Web 富文本編輯器的主流選擇。雖然官方已停止更新,但大量存量專案仍在使用。本文詳細記錄 PHP 環境下 FCKeditor 的精簡部署、核心配置、文件上傳啟用與中文路徑亂碼解決方案,助你快速落地遷移。

一、精簡部署:目錄瘦身指南

官方完整包超 5MB,實際生產僅需核心文件。刪除以下冗餘內容:


FCKeditor/
├── fckconfig.js          # 核心配置(保留)
├── fckeditor.js          # 核心 JS(保留)
├── fckstyles.xml         # 樣式定義(保留)
├── fcktemplates.xml      # 模板定義(保留)
├── fckeditor.php         # PHP 服務端整合類(保留)
├── editor/
│   ├── _source/          # 刪除:源碼調試版
│   ├── _testcases/       # 刪除:測試用例
│   ├── _samples/         # 刪除:示例頁面
│   ├── filemanager/
│   │   ├── browser/
│   │   │   └── default/
│   │   │       └── connectors/
│   │   │           ├── php/        # 保留:PHP 連接器
│   │   │           ├── asp/        # 刪除
│   │   │           ├── aspx/       # 刪除
│   │   │           ├── jsp/        # 刪除
│   │   │           └── ...         # 刪除其他語言
│   │   └── upload/
│   │       ├── php/        # 保留
│   │       └── ...         # 刪除其他語言
│   └── lang/
│       ├── en.js           # 保留:英文
│       ├── zh.js           # 保留:繁體中文
│       ├── zh-cn.js        # 保留:簡體中文
│       └── *.js            # 刪除其他語言
刪除後核心目錄僅約 800KB,加載速度顯著提升。

二、核心配置:fckconfig.js 關鍵設置

<?php
// fckconfig.js 關鍵配置段
// 1. 默認語言設置
FCKConfig.DefaultLanguage = 'zh-cn'; // 或 'zh' (繁體)

// 2. 文件瀏覽與上傳語言指向 PHP
var _FileBrowserLanguage = 'php';  // 原為 'asp'
var _QuickUploadLanguage = 'php';  // 原為 'asp'

// 3. 編輯器皮膚 (可選)
FCKConfig.SkinPath = FCKConfig.BasePath + 'editor/skins/office2003/';

// 4. 工具欄配置 (精簡版)
FCKConfig.ToolbarSets["Basic"] = [
    ['Source', 'DocProps', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'],
    ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteWord', '-', 'Print', 'SpellCheck'],
    ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
    '/',
    ['Bold', 'Italic', 'Underline', 'StrikeThrough', '-', 'Subscript', 'Superscript'],
    ['OrderedList', 'UnorderedList', '-', 'Outdent', 'Indent', 'Blockquote'],
    ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyFull'],
    ['Link', 'Unlink', 'Anchor'],
    ['Image', 'Flash', 'Table', 'Rule', 'Smiley', 'SpecialChar', 'PageBreak'],
    '/',
    ['Style', 'FontFormat', 'FontName', 'FontSize'],
    ['TextColor', 'BGColor'],
    ['FitWindow', 'ShowBlocks', '-', 'About']
];

FCKConfig.ToolbarSets["Default"] = FCKConfig.ToolbarSets["Basic"];
?>

三、啟用文件上傳:雙連接器配置

FCKeditor 使用兩套獨立連接器:文件瀏覽器 (瀏覽服務器文件) 與 快速上傳 (工具欄圖標直接上傳),必須雙雙啟用。

1. 文件瀏覽器連接器

文件: editor/filemanager/browser/default/connectors/php/config.php

<?php
// 啟用連接器
$Config['Enabled'] = true;

// 設置用戶文件虛擬路徑 (URL 訪問路徑)
$Config['UserFilesPath'] = '/uploads/'; // 必須以 / 結尾,對應 Web 根目錄下 uploads/

// 設置用戶文件物理路徑 (服務器絕對路徑)
$Config['UserFilesAbsolutePath'] = '/var/www/html/uploads/'; // 建議使用絕對路徑

// 允許上傳的文件類型
$Config['AllowedExtensions']['File']    = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'zip', 'rar'];
$Config['DeniedExtensions']['File']     = ['php', 'php3', 'php5', 'phtml', 'asp', 'aspx', 'jsp', 'exe', 'bat'];
$Config['AllowedExtensions']['Image']   = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$Config['DeniedExtensions']['Image']    = [];
$Config['AllowedExtensions']['Flash']   = ['swf', 'flv'];
$Config['DeniedExtensions']['Flash']    = [];

// 最大文件大小 (bytes) - 0 為不限制 (受限於 php.ini)
$Config['MaxFileSize'] = 10 * 1024 * 1024; // 10MB

// 安全:禁止 HTML 執行
$Config['HtmlExtensions'] = ['html', 'htm', 'shtml', 'shtm'];
$Config['SecureImageUploads'] = true; // 檢測圖片偽裝腳本
?>

2. 快速上傳連接器

文件: editor/filemanager/upload/php/config.php

<?php
$Config['Enabled'] = true;
$Config['UserFilesPath'] = '/uploads/';
$Config['UserFilesAbsolutePath'] = '/var/www/html/uploads/';

// 同樣配置允許/禁止擴展名、大小限制...
// 關鍵差異:此處處理工具欄「插入圖片/文件」直接上傳的請求
?>
權限關鍵:確保 UserFilesAbsolutePath 目錄存在且 Web 服務器進程 (www-data/nginx/apache) 有 讀寫執行權限 (chmod 755 或 775,配合 chown)。

四、PHP 頁面整合調用

<?php
require_once 'FCKeditor/fckeditor.php'; // 引入整合類

// 實例化編輯器
$oFCKeditor = new FCKeditor('article_content'); // 表單字段名
$oFCKeditor->BasePath = '/FCKeditor/';          // 編輯器相對網站根目錄 URL
$oFCKeditor->Value = '<p>初始內容...</p>';    // 初始值 (已編碼 HTML)
$oFCKeditor->Width = '100%';
$oFCKeditor->Height = '400';
$oFCKeditor->ToolbarSet = 'Basic';              // 使用精簡工具欄
$oFCKeditor->Config['CustomConfigurationsPath'] = ''; // 禁用自定義配置文件
$oFCKeditor->Create();                          // 輸出 HTML
?>

五、中文文件名亂碼終極解決方案

FCKeditor 早期版本對中文文件名支援極差,上傳後文件名變亂碼、下載 404、無法刪除。核心問題在於 編碼不一致 (UTF-8 專案 vs 系統默認 GBK/Big5)。

方案:統一轉碼處理 (修改上傳連接器)

文件: editor/filemanager/upload/php/commands.php (或 upload.php)

<?php
// 在文件保存前,統一將文件名從 UTF-8 轉為系統編碼 (Linux 通常為 UTF-8,Windows 為 GBK)
// 但為跨平台兼容,建議:上傳時重命名為 UUID + 原擴展名,資料庫記錄原文件名

function sanitizeFileName($fileName) {
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $allowedExt = ['jpg','jpeg','png','gif','pdf','doc','docx','xls','xlsx','zip','rar'];
    if (!in_array($ext, $allowedExt)) $ext = 'bin';
    
    // 生成唯一文件名:時間戳 + 隨機數 + 擴展名
    $newName = date('YmdHis') . '_' . mt_rand(1000, 9999) . '.' . $ext;
    return $newName;
}

// 在 move_uploaded_file 之前調用
$originalName = $_FILES['NewFile']['name'];
$safeName = sanitizeFileName($originalName);
$targetPath = $Config['UserFilesAbsolutePath'] . $safeName;

if (move_uploaded_file($_FILES['NewFile']['tmp_name'], $targetPath)) {
    // 返回給編輯器的 URL (使用安全文件名)
    $url = $Config['UserFilesPath'] . $safeName;
    // 可選:將原始文件名存入資料庫,供下載時恢復
    // saveFileMapping($safeName, $originalName);
    echo "";
} else {
    echo "";
}
?>

進階:資料庫映射表設計

CREATE TABLE `editor_files` (
  `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `storage_name` VARCHAR(100) NOT NULL COMMENT '存儲文件名 (UUID)',
  `original_name` VARCHAR(255) NOT NULL COMMENT '用戶原始文件名',
  `file_path` VARCHAR(500) NOT NULL COMMENT '相對存儲路徑',
  `file_size` INT UNSIGNED DEFAULT 0,
  `mime_type` VARCHAR(100) DEFAULT '',
  `upload_ip` VARCHAR(45) DEFAULT '',
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY `uk_storage` (`storage_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

六、常見問題排查表

現象原因解決方案
編輯器工具欄顯示空白/報錯BasePath 路徑錯誤檢查 $oFCKeditor->BasePath 必須以 / 結尾,且為網站根目錄相對 URL
「服務器未配置」錯誤連接器 Enabled=false檢查兩個 config.php 均設 $Config['Enabled'] = true
上傳成功但圖片不顯示UserFilesPath 路徑錯誤確保 UserFilesPath 為 Web 可訪問的 URL 路徑 (如 /uploads/),非服務器絕對路徑
中文文件名下載亂碼Content-Disposition 編碼下載腳本使用 header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($originalName)) (RFC 5987)
大文件上傳失敗php.ini 限制調整 upload_max_filesize, post_max_size, max_execution_time, memory_limit

七、遷移建議:拥抱 CKEditor 5

FCKeditor 已停止維護 10+ 年,存在 XSS 漏洞 (CVE-2011-1779 等)、不支援現代瀏覽器特性、無響應式設計。建議漸進式遷移:

  1. 新功能:直接使用 CKEditor 5 (模塊化、TypeScript、協同編輯)。
  2. 存量數據:FCKeditor 輸出標準 HTML,CKEditor 5 可直接編輯,無需數據遷移。
  3. 共存過渡:同頁面按業務區分加載不同編輯器,逐步替換。
<!-- CKEditor 5 經典模式快速上手 -->
<script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>
<textarea id="editor" name="content"></textarea>
<script>
ClassicEditor.create(document.querySelector('#editor'), {
    language: 'zh-cn',
    toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'undo', 'redo']
}).catch(error => console.error(error));
</script>

總結

FCKeditor 在 PHP 中的配置核心在於:精簡目錄、雙連接器啟用、路徑權限正確、中文文件名重命名策略。本文提供的配置模板可直接用於生產環境。但鑒於安全性與可維護性,強烈建議新專案採用 CKEditor 5 或現代替代方案 (如 TipTap、Editor.js),舊專案制定遷移計劃並修補已知漏洞。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved