diff --git a/docs/DataTables-Advanced.md b/docs/DataTables-Advanced.md
index 8b34e78..ab51707 100644
--- a/docs/DataTables-Advanced.md
+++ b/docs/DataTables-Advanced.md
@@ -49,7 +49,11 @@ $dt->from('users')
->addPermanentSelect('users.role', 'users.last_login_at')
->setColumns('id', 'name', 'email')
->addRender('name', static fn (string $name, array $row) =>
- sprintf('%s (%s)', htmlspecialchars($name), $row['role'])
+ sprintf(
+ '%s (%s)',
+ htmlspecialchars($name, ENT_QUOTES, 'UTF-8'),
+ htmlspecialchars((string) $row['role'], ENT_QUOTES, 'UTF-8')
+ )
);
```
@@ -149,8 +153,8 @@ You almost never need this, but for completeness:
use InitPHP\Database\Utils\Datatables\Renderer;
$renderer = new Renderer();
-$renderer->add('email', fn (string $e) => '' . $e . '');
-$renderer->add('name', fn (string $n) => strtoupper($n));
+$renderer->add('email', fn (string $e) => '' . htmlspecialchars($e, ENT_QUOTES, 'UTF-8') . '');
+$renderer->add('name', fn (string $n) => htmlspecialchars(strtoupper($n), ENT_QUOTES, 'UTF-8'));
$dt = new Datatables($db, null, $renderer);
$dt->setColumns('id', 'name', 'email');
diff --git a/docs/DataTables-Introduction.md b/docs/DataTables-Introduction.md
index e9b60cf..77a6334 100644
--- a/docs/DataTables-Introduction.md
+++ b/docs/DataTables-Introduction.md
@@ -37,7 +37,9 @@ DB::createImmutable([
'password' => '...',
]);
-header('Content-Type: application/json');
+// Always send a JSON content type: the response echoes the request back in
+// "post", and a page served as text/html would run markup in it.
+header('Content-Type: application/json; charset=utf-8');
echo (new Datatables(DB::getDatabase()))
->from('users')
@@ -58,14 +60,18 @@ $('#users').DataTable({
ajax: '/api/users/datatables',
columns: [
{ data: 'id', title: 'ID' },
- { data: 'name', title: 'Name' },
- { data: 'email', title: 'Email' },
+ // DataTables writes cell values into the page as HTML. Text columns must
+ // use the text() renderer so that "
" shows up as text.
+ { data: 'name', title: 'Name', render: $.fn.dataTable.render.text() },
+ { data: 'email', title: 'Email', render: $.fn.dataTable.render.text() },
{ data: 'created_at', title: 'Created' }
]
});
```
+> **Escape cell values.** DataTables.js puts what the server returns into the page as HTML. Names, e-mail addresses and any other user-supplied column must go through `render: $.fn.dataTable.render.text()` on the client, or through `htmlspecialchars()` in a server-side [renderer](DataTables-Renderers.md#security--always-escape-on-the-way-out) when you build the HTML yourself. Otherwise a user who registers with `
` as their name runs script in the browser of whoever opens the table.
+
The `columns[].data` keys on the client must match the column names you registered with `setColumns()` on the server. See [DataTables — Bootstrap recipe](Recipe-DataTables-Bootstrap.md) for a complete page.
## The response envelope
diff --git a/docs/DataTables-Renderers.md b/docs/DataTables-Renderers.md
index 8504a5f..944b8fd 100644
--- a/docs/DataTables-Renderers.md
+++ b/docs/DataTables-Renderers.md
@@ -40,7 +40,11 @@ Now every `email` cell in the response is an `` element. The unrendered `emai
$dt->setColumns('id', 'first_name', 'last_name', 'full_name')
->addPermanentSelect('first_name', 'last_name')
->addRender('full_name', fn (mixed $_value, array $row) =>
- trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''))
+ htmlspecialchars(
+ trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')),
+ ENT_QUOTES,
+ 'UTF-8'
+ )
);
```
@@ -48,7 +52,7 @@ $dt->setColumns('id', 'first_name', 'last_name', 'full_name')
1. `setColumns()` declares it (so the client has an index for it).
2. `addPermanentSelect()` ensures the source columns (`first_name`, `last_name`) ride along on every SELECT (see [Advanced](DataTables-Advanced.md)).
-3. The renderer composes the value from those siblings.
+3. The renderer composes the value from those siblings and escapes it, because the cell is inserted into the page as HTML.
## Formatting timestamps
@@ -87,8 +91,8 @@ $dt->from('users')
// Client
columns: [
{ data: 'id', title: 'ID' },
- { data: 'name', title: 'Name' },
- { data: 'actions', title: '', orderable: false, searchable: false }
+ { data: 'name', title: 'Name', render: $.fn.dataTable.render.text() }, // user text, no PHP renderer
+ { data: 'actions', title: '', orderable: false, searchable: false } // HTML built (and escaped) in PHP
]
```
@@ -97,9 +101,10 @@ columns: [
## Mutating sibling columns
```php
-$dt->addRender('name', static fn (string $name, array $row) =>
- $row['is_admin'] ? '👑 ' . $name : $name
-);
+$dt->addRender('name', static function (string $name, array $row): string {
+ $safe = htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); // the cell is rendered as HTML
+ return $row['is_admin'] ? '👑 ' . $safe : $safe;
+});
```
`$row` is passed by **value** — the helper copies it before invoking the renderer. So you can read sibling columns freely; you cannot use a renderer to mutate a sibling that has its own renderer running later.
@@ -111,6 +116,7 @@ $response = $dt->toArray();
foreach ($response['data'] as $i => $row) {
$response['data'][$i] = transformRow($row);
}
+header('Content-Type: application/json; charset=utf-8'); // not text/html: "post" echoes the request
echo json_encode($response);
```
@@ -119,8 +125,8 @@ echo json_encode($response);
`addRender()` overwrites any previous registration for the same column:
```php
-$dt->addRender('name', fn ($v) => strtoupper($v));
-$dt->addRender('name', fn ($v) => strtolower($v));
+$dt->addRender('name', fn ($v) => htmlspecialchars(strtoupper($v), ENT_QUOTES, 'UTF-8'));
+$dt->addRender('name', fn ($v) => htmlspecialchars(strtolower($v), ENT_QUOTES, 'UTF-8'));
// strtolower wins.
```
@@ -143,7 +149,16 @@ $dt->addRender('name', static fn (string $name) =>
$dt->addRender('name', static fn (string $name) => "{$name}");
```
-DataTables.js sets cell innerHTML directly — anything you emit ends up in the DOM as-is.
+DataTables.js sets cell innerHTML directly — anything you emit ends up in the DOM as-is. That applies to columns **without** a renderer too: a plain `name` value goes into the cell unescaped. On the client, give every user-supplied text column `render: $.fn.dataTable.render.text()`:
+
+```js
+columns: [
+ { data: 'name', title: 'Name', render: $.fn.dataTable.render.text() },
+ { data: 'email', title: 'Email', render: $.fn.dataTable.render.text() }
+]
+```
+
+Do not combine the two on the same column: a column that already returns escaped HTML from PHP would be escaped a second time by `text()`. Choose one place per column.
## Renderers and the count queries
diff --git a/docs/Recipe-DataTables-Bootstrap.md b/docs/Recipe-DataTables-Bootstrap.md
index e1725c8..500dc57 100644
--- a/docs/Recipe-DataTables-Bootstrap.md
+++ b/docs/Recipe-DataTables-Bootstrap.md
@@ -117,9 +117,11 @@ That's the entire server side. Three database round-trips (`recordsTotal`, `reco
},
columns: [
{ data: 'id', title: 'ID' },
- { data: 'name', title: 'Name' },
- { data: 'email', title: 'Email' },
- { data: 'role', title: 'Role' },
+ // These columns hold user-supplied text, and DataTables inserts cell
+ // values as HTML: render them as text so markup is not executed.
+ { data: 'name', title: 'Name', render: $.fn.dataTable.render.text() },
+ { data: 'email', title: 'Email', render: $.fn.dataTable.render.text() },
+ { data: 'role', title: 'Role', render: $.fn.dataTable.render.text() },
{ data: 'created_at', title: 'Joined' },
{ data: 'actions', title: '', orderable: false, searchable: false }
],
@@ -137,6 +139,7 @@ That's the entire server side. Three database round-trips (`recordsTotal`, `reco
|---|---|
| `setColumns('id', 'name', ...)` order | `columns[].data` order |
| `setColumns(null)` for actions | `orderable: false, searchable: false` |
+| user-supplied text (`name`, `email`, `role`) | `render: $.fn.dataTable.render.text()` — cells are inserted as HTML |
| `addPermanentSelect("'' AS actions")` | gives the renderer something to attach to |
| `addRender('actions', fn)` | renders the cell HTML |
| `where('active', 1)` | invisible filter — only active users ever leave the server |
@@ -179,6 +182,8 @@ The response will look like:
If `Users` is already a Model with soft deletes:
```php
+header('Content-Type: application/json; charset=utf-8');
+
echo (new Datatables(new App\Model\Users()))
->setColumns('id', 'name', 'email', 'role', 'created_at', null)
// … renderers …
@@ -200,6 +205,8 @@ if ($activeOnly) {
$dt->where('active', 1);
}
+header('Content-Type: application/json; charset=utf-8');
+
echo $dt->setColumns('id', 'name', 'email', 'role', 'created_at', null)
->addRender(/* … */);
```
diff --git a/docs/Recipe-Upsert.md b/docs/Recipe-Upsert.md
index 5f1eb78..231e051 100644
--- a/docs/Recipe-Upsert.md
+++ b/docs/Recipe-Upsert.md
@@ -153,6 +153,15 @@ final class Upserter
$columns = array_keys($row);
$params = [];
+ // Identifiers cannot be bound as parameters, and the column names come
+ // from the *keys* of $row. Allow only plain identifiers, so a key such as
+ // "name) VALUES (1); DROP TABLE items; --" can never reach the SQL.
+ foreach ([$table, $conflictColumn, ...$columns] as $identifier) {
+ if (preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/D', (string) $identifier) !== 1) {
+ throw new \InvalidArgumentException('Invalid identifier.');
+ }
+ }
+
foreach ($row as $key => $value) {
$params[':' . $key] = $value;
}
@@ -177,7 +186,7 @@ final class Upserter
}
```
-> The wrapper interpolates `$table` and `$conflictColumn` directly — identifiers cannot be bound. **Only call it with hard-coded strings**, never user input.
+> The wrapper interpolates `$table`, `$conflictColumn` and the **keys of `$row`** directly — identifiers cannot be bound. The check at the top rejects anything that is not a plain identifier, but it only guards the syntax, not which tables and columns are allowed: pass hard-coded table and column names, and never use `$_POST` (or any other request array) as `$row`. Build `$row` from the fixed set of fields you expect, as the example below does.
Use it: