William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

JS/PHP functions for string escape

Here I list some common JS/PHP functions for string escape or, encode special characters.

1. JavaScript: encodeURIComponent()

In pure JavaScript, the encodeURIComponent() is used when sending web request to encode a URI component. This function encodes special characters as: , / ? : @ & = + $ #

The following is a snippet from my codes to send a request to PHP backend from JS’s Prototype:

new Ajax.Updater(pid, url, {
  parameters: {
    update_submit: 1,
    email: encodeURIComponent(email),
    rowno: rowno,
    time: new Date().getTime(),
    processing: encodeURIComponent(processing)

Also, we can use JS’s function to manually escape special chars(e.g.: < > &):

html.replace(/&/g, "&amp ;").replace(/</g, "&lt ;").replace(/>/g, "&gt ;");
// Or:
function escape(html) {
  var escaped = html;
  var findReplace = [[/&/g, "&amp ;"], [/</g, "\&lt ;"], 
                        [/>/g, "&gt ;"], [/"/g, "&quot ;"]]
  for(item in findReplace)
    escaped = escaped.replace(item[0], item[1]);
  return escaped;

The good thing is that at server side, php script directly receivea the request data, without decode (it does it hiddenly).

2. jQuery: form.serialize()

jQuery has no escape function itself, although there is a plugin jquery.escape to do so.
So how to escape specially chars when sending a request? use jQuery form.serialize().
jQuery’s .serialize() encodes a set of form elements as a string for submission.

The following is from my jQuery codes:

$('#form1').submit(function() {
  var data=$('#form1').serialize()+'&search_form1=1';
    type: "POST",
    url: MyPackage.url,
    data: data,
    success: function(data) {

At server side, php script gets the orignal passing parameters without decode.

3. PHP: htmlspecialchars()

Always use it to display complex data (get from DB or web request) on the webpage.

When rendering web page, if there are special chars included in displayed string, the display will be broken.
PHP’s htmlspecialchars() solves this problem. It convert special characters to HTML entities.

The translations performed are:

  • ‘&’ (ampersand) becomes ‘&amp ;’
  • ‘”‘ (double quote) becomes ‘&quot ;’ when ENT_NOQUOTES is not set.
  • ”’ (single quote) becomes ‘&#039 ;’ only when ENT_QUOTES is set.
  • ‘<' (less than) becomes '<'
  • ‘>’ (greater than) becomes ‘&gt ;’

Use htmlspecialchars() to filter text input values on forms for later display and/or database storage, the following are examples:


<input type="text" value="<?=htmlspecialchars($row['ADDRESS1']);?>">

echo '<input type=text value="'.htmlspecialchars($data).'" />';

If manually process, e.g, date format convert, or Unicode chars, use preg_replace() or str_replace() instead.

4. PHP: mysql_real_escape_string()

Always use it to before Database Operation (select, insert, update).

PHP’s mysql_real_escape_string() escapes special characters in a string for use in an SQL statement,
which prepends backslashes to the following characters: \x00, \n, \r, \, ‘, ” and \x1a.
This function must always (with few exceptions) be used to make data safe before sending a query to MySQL, or insert string like O’reilly into a database.

A very good example of using mysql_real_escape_string() is from http://php.net/manual/en/function.mysql-real-escape-string.php:

Example #1 Simple mysql_real_escape_string() example
$query=sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",

Example #2 An example SQL Injection Attack
// We didn't check $_POST['password'], 
// it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE 
  user='{$_POST['username']}' AND password='{$_POST['password']}'";

// This means the query sent to MySQL would be:
echo $query;
The query sent to MySQL:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password. 

5. PHP: addslashes()

A simple alternative function is addslashes() when we’re entering data into a database.
PHP’s addslashes() returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote (‘), double quote (“), backslash (\) and NUL (the NULL byte).
The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data.
So addslashes() is automatically used when we get data from web request.

I don’t use it normally. Only use it in very specific condition. In most case, the mysql_real_escape_string() and htmlspecialchars() can cover.

6. PHP: urlencode()

php’s form auto encode the post/get data, so no extra steps is neccessary.
However, if manually process is needed, PHP’s urlencode() is a convenient way.
It is helpful when encoding a string for a query part of a URL, or, pass variables to the next page.

$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';

Don’t forget on the server side, in php code, use urldecode to decode the passing parameters.
If we want to safe process, the above steps are safe enough, but not necessary:
Don’t use urlencode() or urldecode() if the text includes an email address, as it destroys the “+” character, a perfectly valid email address character.


2 responses to “JS/PHP functions for string escape

  1. offshore bank accounts 04/12/2011 at 11:55 am

    PHP 4 4.3.0 PHP 5 mysql real escape string Escapes special characters in a string for use in a SQL statement. mysql real escape string which prepends backslashes to the following characters .

  2. rastkovukasinovic 12/12/2011 at 11:47 am

    Thank you for this great article. Can I reference here for my next UX article? I wan to include link for further explanation and not bug people with code snippets too much so I can focus on concepts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: