本教程基於 CKEditor 4(原 FCKEditor 升級版),適用於 CI 2.x/3.x。現代項目建議直接使用 CKEditor 5 + Composer。
將 ckeditor/ 目錄放入 application/third_party/ckeditor/(推薦)或 public/assets/ckeditor/。
// application/config/config.php
$config['ckeditor_basepath'] = base_url('assets/ckeditor/'); // 公開可訪問 URL
$config['ckeditor_toolbar'] = 'Full'; // Basic / Full / Custom
<?php
// application/helpers/MY_form_helper.php
defined('BASEPATH') OR exit('No direct script access allowed');
if (!function_exists('form_ckeditor')) {
function form_ckeditor($data = '', $value = '', $extra = '') {
$CI =& get_instance();
$basePath = $CI->config->item('ckeditor_basepath');
$toolbar = $CI->config->item('ckeditor_toolbar');
// 輸出 HTML + JS 初始化
$name = is_array($data) ? ($data['name'] ?? '') : $data;
$id = is_array($data) ? ($data['id'] ?? $name) : $name;
$val = is_array($data) ? ($data['value'] ?? $value) : $value;
$attr = '';
if (is_array($extra)) {
foreach ($extra as $k => $v) $attr .= " $k=\"$v\"";
} elseif ($extra) {
$attr = $extra;
}
$html = "<textarea name=\"{$name}\" id=\"{$id}\"{$attr}>" . htmlspecialchars($val) . "</textarea>";
$html .= "<script>
CKEDITOR.replace('{$id}', {
basePath: '{$basePath}',
toolbar: '{$toolbar}',
language: 'zh-cn',
height: " . (isset($data['height']) ? $data['height'] : 300) . "
});
</script>";
return $html;
}
}
<?php
// Controller
$this->load->helper('form');
$this->load->helper('my_form'); // 載入自定義 helper
$data = [
'name' => 'content',
'id' => 'content',
'value' => $article->content ?? '',
'height' => 400,
];
echo form_ckeditor($data);
// config.js 或實例化時配置
CKEDITOR.editorConfig = function(config) {
config.toolbar = 'Custom';
config.toolbar_Custom = [
['Source', '-', 'Bold', 'Italic', 'Underline'],
['NumberedList', 'BulletedList', '-', 'Link', 'Unlink', 'Image'],
['Format', 'FontSize', 'TextColor', 'BGColor'],
['Maximize', 'ShowBlocks']
];
config.extraPlugins = 'codesnippet,image2,widget,lineutils';
config.codeSnippet_theme = 'monokai';
};
CKEditor 4 內建 File Browser 接口,需實現後端上傳端點並返回標準 JSON:
// 後端上傳接口(Controller)
public function ckeditor_upload() {
$config = [
'upload_path' => './uploads/ckeditor/',
'allowed_types' => 'jpg|jpeg|png|gif',
'max_size' => 2048,
'file_name' => uniqid('ck_'),
];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('upload')) {
echo json_encode(['uploaded' => 0, 'error' => ['message' => $this->upload->display_errors('','')]]);
return;
}
$info = $this->upload->data();
echo json_encode([
'uploaded' => 1,
'fileName' => $info['file_name'],
'url' => base_url("uploads/ckeditor/{$info['file_name']}"),
]);
}
// 前端配置
CKEDITOR.replace('content', {
filebrowserUploadUrl: site_url('admin/ckeditor_upload'),
filebrowserUploadMethod: 'form' // 或 'xhr'
});
location ~ \.php$ { deny all; })。HTMLPurifier 或 CI xss_clean() 過濾。csrf_token(CKEditor 4.7+ 支援 filebrowserUploadMethod: 'xhr' 自動攜帶 Cookie)。