According When to encode space to plus (+) or %20? when we have any space in html form name or value, our browser will encode the space into "+", but what if we have "plus" sign in value (for example like text field) which is typed by user intentionally? Will our web server misunderstood the symbol and change it back to space? How are we going to avoid this?
2 Answers
Will our web server misunderstood the symbol and change it back to space?
No, because when a +
character is entered in a form, it gets encoded to %2B
.
Here's an example (fiddle):
<form method="POST" action="/">
<input name="foo" type="text" value="+">
<input name="bar" type="text" value="bacon sauce">
</form>
<script>
// This encodes the form, (i.e. that's what your server receives)
alert( $('form').serialize() );
</script>
The alert box will show: foo=%2B&bar=bacon+sauce
This implies that +
is encoded as %2B
. So on your server, just convert all +
characters to a space
, and %2B
to +
, but you should probably leave the decoding part to your framework or a library.
Here's a fiddle you can use to play with parameter encoding: fiddle
The Plus needs to be converted into the urlencoded form with the % notation. In this case %2B.
-
1When you Post the data via browser the browser will encode the strings correctly for you. And if you need to encode the string on the client side you cloud also use the js urlencode function or the jQuery stuff from the other answer.– rekireNov 12, 2012 at 6:13
-
1You almost never have to explicitly encode your url parameters. Like rekire said, the browser does this for you.– surjNov 12, 2012 at 6:18
-
1@GMsoF Let's say your form has a field named "foo". If the user enters
+
in the form and hits the submit button, the browser converts that+
to%2B
. Then, when your server receives your request, it converts the%2B
back to a+
. So, when you callgetParameter("foo")
, you will get back a+
character.– surjNov 12, 2012 at 6:21 -
1@GMsoF Here's a fiddle that you can use to play with the parameter encoding: jsfiddle.net/3MFX2/4– surjNov 12, 2012 at 6:33
-
1So it is in that case. And every char which needs to been protected will get in a form of % and its hexadecimal value.– rekireNov 12, 2012 at 6:33
%2b
->+
->(space)
, which is why it must be done once only.getParameter("name")
.