w3soft.org by unix-world
0.00
PHP - Escape Javascript and HTML values
Escape values in PHP for use them in a safe mode inside HTML and Javascript. Unicode compliant.
programming language: php 7.0 or later
operating system: any
Updated: 2022-11-20
Method definition: Escape Javascript Value
function escapeJsValue(?string $str) : string {
$escaped = (string) @json_encode((string)$str, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_INVALID_UTF8_SUBSTITUTE);
return (string) substr((string)trim((string)$escaped), 1, -1);
}
Method definition: Escape HTML Value
function escapeHtmlValue(?string $str, bool $html5=true) : string {
if($html5) {
return (string) htmlspecialchars((string)$str, ENT_HTML5 | ENT_COMPAT | ENT_SUBSTITUTE, 'UTF-8', true);
} else {
return (string) htmlspecialchars((string)$str, ENT_HTML401 | ENT_COMPAT | ENT_SUBSTITUTE, 'UTF-8', true);
}
}
Sample usage
$escapedHtmlValue = (string) escapeHtmlValue((string)$escapedHtmlValue); // the content of $escapedHtmlValue (string) can't be predicted, thus always must be escaped to avoid break the HTML (ex: may contain: < or > or ")
$escapedJsValue = (string) escapeJsValue((string)$escapedJsValue); // the content of $escapedJsValue (string) can't be predicted, thus always must be escaped to avoid break the Javascript inside HTML (ex: may contain: \n, single or double quote(s) and other unsafe characters or sequences ; by example '</script>' which will end prematurely the current Javascript section and should not ...)
$html = <<<HTML
<div>This is a sample (safe) value passed from PHP to HTML: {$escapedHtmlValue}</div>
<script>
var myVar1 = '{$escapedJsValue}'; // safe value passed from PHP to Javascript, inside HTML, using single quotes
var myVar2 = "{$escapedJsValue}"; // safe value passed from PHP to Javascript, inside HTML, using double quotes
</script>
HTML;
echo $html;