Escaping in PHP
I write a lot of PHP code and often have to generate strings for use inside other languages. Instead of continually reinventing the wheel, here's a page that provides generic solutions.
PHP to HTML
This is built into the language. You may see
htmlspecialchars(), but it is now preferred to use
htmlentities() to convert a string that is to be embedded in HTML. Here's how one can use this when you mix HTML and PHP.
<p>My name is <?php echo htmlentities($name); ?> </p>
PHP to URL
The standard way is to use the built-in function
urlencode(). It works well.
<a href="/redirect.php?site=<?php echo urlencode($url); ?">Go to the URL you wanted.</a>
To use this glorious function, you need to merely pass it a string and optionally use the
true as a second parameter.
PHP to JSON
- We don't need to worry about
- Only double-quoted strings are allowed.
- Only properly escaped text is permitted.
The easy way to convert anything into JSON is with
json_encode(), but that will fail you if you try to encode strings that are not UTF encoded. For that reason, you should first detect if the string is in UTF-8. If not, encode it and you now may may safely call
json_encode() on the result.