萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

FCKeditor 整合 PHP + Smarty 模板引擎完整教學

前言

FCKeditor(現 CKEditor)是經典富文本編輯器。本文示範如何在 PHP + Smarty 架構中整合:後端實例化編輯器、配置工具欄、語言、寬高,前端模板輸出編輯器 HTML,並說明資料提交與安全過濾要點。

後端整合代碼

<?php
require_once 'Smarty.class.php';
require_once '../include/FCKeditor/fckeditor.php';

$smarty = new Smarty();
$BasePath = '../include/FCKeditor/';

$fck = new FCKeditor('p_info'); // 表單欄位名
$fck->BasePath = $BasePath;
$fck->ToolbarSet = 'News';      // 自定義工具欄
$fck->Width = '700';
$fck->Height = '350';
$fck->Config['AutoDetectLanguage'] = false;
$fck->Config['DefaultLanguage'] = 'zh-cn';

$content = $fck->CreateHtml(); // 生成編輯器 HTML/JS
$smarty->assign('content', $content);
$smarty->display('fck.tpl');
?>

Smarty 模板輸出

<!-- fck.tpl -->
<form method="post" action="save.php">
    <table>
        <tr>
            <td valign="top" class="font12en">
                <{$content}>  {* 輸出編輯器 *}
            </td>
        </tr>
        <tr>
            <td><input type="submit" value="儲存"></td>
        </tr>
    </table>
</form>

自定義工具欄配置

編輯 FCKeditor/fck_config.js:

FCKConfig.ToolbarSets["News"] = [
    ['Source', 'DocProps', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'],
    ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteWord', '-', 'Print', 'SpellCheck'],
    ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
    ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
    '/',
    ['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']
];

然後在 PHP 中設定 $fck->ToolbarSet = 'News'; 即可套用。

資料接收與安全過濾

<?php
// save.php
$content = $_POST['p_info'] ?? '';

// 必須過濾 XSS!推薦 HTMLPurifier
require_once 'HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'p,b,i,u,em,strong,a[href|title],img[src|alt|width|height],ul,ol,li,br,span[style],div[style]');
$purifier = new HTMLPurifier($config);
$safeContent = $purifier->purify($content);

// 入庫
$stmt = $pdo->prepare('INSERT INTO articles (content) VALUES (?)');
$stmt->execute([$safeContent]);
?>

遷移建議:升級至 CKEditor 4/5

FCKeditor 已停止維護(2009 年)。現代專案建議直接整合 CKEditor 5:

  • 模組化架構、ES6 原生、支援 React/Vue/Angular 整合包。
  • 線上建構器可視化配置工具欄、插件。
  • PHP 端僅需處理資料儲存與 HTMLPurifier 過濾。
copyright © 萬盛學電腦網 all rights reserved