JS/PHP functions for string escape
Blogs20112011-03-18
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, "& ;").replace(/</g, "< ;").replace(/>/g, "> ;");
// Or:
function escape(html) {
var escaped = html;
var findReplace = [[/&/g, "& ;"], [/</g, "< ;"],
[/>/g, "> ;"], [/"/g, "" ;"]]
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';
$.ajax({
type: "POST",
url: MyPackage.url,
data: data,
success: function(data) {
$('#div_display').hide().html(data).show(200);
}
});
});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 ’& ;’
- ’”’ (double quote) becomes ’” ;’ when ENT_NOQUOTES is not set.
- ''' (single quote) becomes ’’ ;’ only when ENT_QUOTES is set.
- ’<’ (less than) becomes ’<’
- ’>’ (greater than) becomes ’> ;’
Use htmlspecialchars() to filter text input values on forms for later display and/or database storage, the following are examples:
<textarea><?=htmlspecialchars($stringFromTable/$stringFromWebRequest);?>
</textarea>
<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'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
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']}'";
mysql_query($query);
// 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.
