A problem that always has existed, is the way in which you communicate PHP with JavaScript in the client side cause of special characters inside the string that may make your JS code crash completely. For example, take a look to the following code:
<?php
$str = <<<EOF
Test
String
EOF;
?>
<script>
var myString = "<?php echo $str ?>";
</script>
If this code is processed by a JS engine e.g in the browser, you will see the following exception:
As indeed, our string in PHP has multiple lines and it's being printed as well in the same way. The string needs to be escaped namely replacing special characters that may pollute your JavaScript in order to make it suitable for JavaScript. In this article we'll show you how easily is to print safely a string from PHP inside a JavaScript context using a Symfony helper.
Printing safely a string from PHP to JavaScript
Fortunately, instead of including complex methods that probably no one will understand, Symfony 1.4 included a lot of helpers like the DateHelper
, NumberHelper
, UrlHelper
and others. Such helpers offer a lot of methods that are frecuently used by developers. One of these helpers is the Escaping helper, that as its name says, include a couple of methods that can be used to escape special characters of strings in different situations. To include this helper on your views/actions you can simply use the use_helper
method and the name of the helper as first argument, that in this case is the Escaping helper:
<?php use_helper("Escaping"); ?>
This will allow you to use different plain php functions where the helper has been loaded. The one that we need to print safely a string from PHP inside a JavaScript context is theĀ esc_js_no_entities
method, this methodĀ escapes a string, making it suitable to be placed in a JavaScript string. It returns the escaped value, so instead of printing your variable, print the value returned by the method passing your string as first argument:
<?php // Include the Escaping Helper of Symfony 1.4 ?>
<?php use_helper("Escaping"); ?>
<?php
$str = <<<EOF
Test
String
EOF;
?>
<script>
var myString = "<?php echo esc_js_no_entities($str) ?>";
</script>
PHP will print the following markdown:
<script>
var myString = " Test\n String";
</script>
Quick and functional isn't? There are more useful escaping methods in the collection of methods of the Escaping helper like esc_specialchars
, esc_raw
, so don't forget to take a look to the official legacy documentation of the helper here.
Happy coding !