Security

PHP Security Code Snippets

Context-aware HTML escaping and CSRF token helpers.

Overview

Context-aware HTML escaping and CSRF token helpers.

Code example

<?php
declare(strict_types=1);
function htmlEscape(string $v): string { return htmlspecialchars($v,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }
function newCsrfToken(): string { return bin2hex(random_bytes(32)); }
function verifyCsrfToken(string $known,string $sent): bool { return $known!==''&&$sent!==''&&hash_equals($known,$sent); }

How to use it

Place the snippet in a namespaced helper or service file, adapt its inputs to your application and add tests for expected and edge-case behavior.

Notes

The example is intentionally small. Validate untrusted input, handle exceptions and document any PHP extension or database requirements.