Escape string to output HTML (and JS).
composer require rancoud/security
use Rancoud\Security\Security;
// When you want to escape text for HTML output.
echo '<p>' . Security::escHTML('<script>alert("test");</script>') . '</p>' . "\n";
// -> <p><script>alert("test");</script></p>
// When you want to escape text for HTML attribute output.
echo '<div data-attr="' . Security::escAttr('my-data"><script>alert("test");</script><div hidden="') . '">' . "\n";
// -> <div data-attr="my-data"><script>alert("test");</script><div hidden=""></div>
// When you want to escape text for JS output.
echo 'const value = "' . Security::escJS('";alert("test");let a="') . '";' . "\n";
// -> const value = "\x22\x3Balert\x28\x22test\x22\x29\x3Blet\x20a\x3D\x22";
// When you want to escape text for URL output.
echo Security::escURL('https://example.com') . "\n";
// -> https%3A%2F%2Fexample.com
// When you want to escape text for CSS output.
echo 'body {background-color: ' . Security::escCSS('red;} body {background-image: url("https://example.com");') . '}' . "\n";
// -> body {background-color: red\3B \7D \20 body\20 \7B background\2D image\3A \20 url\28 \22 https\3A \2F \2F example\2E com\22 \29 \3B }
// Checks if charset is supported.
Security::isSupportedCharset('ISO-8859-15');
// -> true
Security::isSupportedCharset('foo');
// -> false
Escapes text for HTML output.
public static function escHTML($text, string $charset = 'UTF-8'): string
Escapes text for HTML attribute output.
public static function escAttr($text, string $charset = 'UTF-8'): string
Escapes text for JS output.
public static function escJS($text, string $charset = 'UTF-8'): string
Escapes text for URL output.
public static function escURL($text, string $charset = 'UTF-8'): string
Escapes text for CSS output.
public static function escCSS($text, string $charset = 'UTF-8'): string
Checks if charset is supported.
public static function isSupportedCharset(string $charset): bool
Charsets supported are only charsets shortlisted (see list below) which are also supported by mbstring extension.
More info at PHP documentation and at the PHP libmbfl README
Charsets shortlisted:
- BIG5
- BIG5-HKSCS
- CP866
- CP932
- CP1251
- CP1252
- EUC-JP
- eucJP-win
- GB2312
- ISO-8859-1
- ISO-8859-5
- ISO-8859-15
- KOI8-R
- MacRoman
- Shift_JIS
- SJIS
- SJIS-win
- UTF-8
- Windows-1251
- Windows-1252
composer ci
for php-cs-fixer and phpunit and coverage
composer lint
for php-cs-fixer
composer test
for phpunit and coverage