Contents

PHP without a framework

For your own CMS or an older application. A <textarea> becomes the editor, the form posts HTML and HtmlSanitizer checks it on the server. PHP 8.1+ is enough.

VEditor in the PHP test application

Installation

With Composer (see Installation) or from the release ZIP:

require __DIR__ . '/veditor/autoload.php';   // or vendor/autoload.php

Make the assets/ directory public, for example as /veditor/.

Form

<?php
session_start();
$_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));
$nonce = base64_encode(random_bytes(16));
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-$nonce'; style-src 'self'; "
    . "style-src-attr 'unsafe-inline'; img-src 'self' https: data: blob:; "
    . "frame-src 'self' https://www.youtube-nocookie.com https://player.vimeo.com; connect-src 'self'; object-src 'none'; "
    . "base-uri 'none'; form-action 'self'");
?>
<link rel="stylesheet" href="/veditor/veditor-content.css">
<link rel="stylesheet" href="/veditor/veditor.css">

<form method="post" action="/save.php">
    <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
    <textarea name="content" id="content"><?= htmlspecialchars($article['body']) ?></textarea>
    <button>Save</button>
</form>

<script type="module" nonce="<?= htmlspecialchars($nonce) ?>">
    import { VEditor } from '/veditor/js/index.js';

    await VEditor.create('#content', {
        language: 'en',
        licenseKey: 'VED1.…', // your key; leave it out on local and test addresses
        ai: { url: '/veditor-ai.php', csrfToken: <?= json_encode($_SESSION['csrf_token']) ?> },
    });
</script>

Or render the same with one call:

echo VEditor\Widget::render([
    'name' => 'content',
    'value' => $article['body'],
    'assetsUrl' => '/veditor',
    'options' => ['language' => 'en', 'licenseKey' => 'VED1.…'],
    'aiUrl' => '/veditor-ai.php',
    'csrfToken' => $_SESSION['csrf_token'],
    'nonce' => $nonce,
]);

Widget::render() escapes the content and the options (JSON with JSON_HEX_*) and dispatches a veditor:ready event on the <textarea> with the editor in event.detail.editor.

The toolbar is set by the toolbar option, in options of Widget::render() or in the VEditor.create() options (item names in Editor options):

'options' => ['language' => 'en', 'toolbar' => ['bold', 'italic', 'link', '|', 'bulletedList', 'numberedList', '|', 'undo', 'redo']],

Widget options

KeyDefaultDescription
namecontentname of the form field
value''HTML content, escaped in the <textarea>
idgeneratedid of the <textarea>; by default veditor-{name}-{random}
assetsUrl''URL of the assets/ directory (styles and js/index.js)
options[]editor options
aiUrl, csrfTokennoneAI endpoint and CSRF token, merged into options['ai']; without csrfToken the token from options['ai'] stays, as do its other keys
filePickerUrlnoneyour file manager page, opened with VEditor.createIframePicker()
uploadUrl, uploadFieldnone, uploadupload endpoint for dropped and pasted images (VEditor.createUploader()); csrfToken is sent in X-CSRF-Token
noncenoneCSP nonce of the <script>
attributes[]extra <textarea> attributes; true gives an attribute without a value, false and null leave it out, on* names are ignored

Saving

<?php
// save.php
require __DIR__ . '/vendor/autoload.php';

use VEditor\HtmlSanitizer;

session_start();
$styles = []; // the same array as the editor's `styles` option

if (!hash_equals($_SESSION['csrf_token'] ?? '', (string) ($_POST['csrf'] ?? ''))) {
    http_response_code(403);
    exit;
}
try {
    $clean = (new HtmlSanitizer())->allowStyles($styles)->sanitize((string) $_POST['content']);
} catch (LengthException $e) {
    http_response_code(413);
    exit('The content is too large.');
}
// save $clean

AI endpoint

<?php
// veditor-ai.php – only for users who may edit content
require __DIR__ . '/vendor/autoload.php';

use VEditor\AiApi;
use VEditor\HtmlSanitizer;
use VEditor\License;

session_start();
$request = [
    'post' => $_SERVER['REQUEST_METHOD'] === 'POST',
    'csrfValid' => hash_equals($_SESSION['csrf_token'] ?? '', (string) ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '')),
    'body' => AiApi::readBody(veditor_config()), // null = too large (HTTP 413)
    'host' => License::requestHost(),
];
session_write_close();
// The same styles as on save, otherwise HTML returned by AI loses their classes.
$styles = [];
$sanitizer = (new HtmlSanitizer())->allowStyles($styles);

if (AiApi::wantsStream($request['body'])) {
    AiApi::sendStream(veditor_config(), $request, $sanitizer);
    exit;
}

[$status, $data] = AiApi::handle(veditor_config(), $request, $sanitizer);
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Check that the user is logged in and may edit content before this code runs. The paths assume the scripts sit next to vendor/; in a public/ directory use __DIR__ . '/../vendor/autoload.php'. See AI and Server configuration.

Showing the content

<link rel="stylesheet" href="/veditor/veditor-content.css">
<div class="veditor-content"><?= $article['body'] ?></div>

Output the stored HTML unescaped only because it was sanitized on save.

Something unclear? Send feedback on the documentation.