cdonts
cdonts

Reputation: 9609

FieldStorage input removes some characters

Putting "c++" in a input box, my Python script just receives "c".

Here's the HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<body>
    <input id="inputtxt" type="text">&nbsp;
    <a onclick="window.location='escapetest.py?q='+document.getElementById('inputtxt').value;">Go!</a>
</body>
</html>

And the python script which receives the request:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cgitb; cgitb.enable()

from cgi import FieldStorage


inputstr = FieldStorage()["q"]

print "Content-Type: text/html; charset=utf-8"
print
print inputstr.value

The output is:

c

Running Python 2.7 (x64) and using Firefox.

Upvotes: 1

Views: 68

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123420

You are not properly escaping your value; the + character in a URL-encoded query value is the encoded value for a space, so really you are printing:

"c  "

A c with two spaces. Use the encodeURIComponent() function to properly escape the input value, where spaces will be replaced by + and + will be replaced by %2B, so that Python can decode that back to +:

<a onclick="window.location='escapetest.py?q='+encodeURIComponent(document.getElementById('inputtxt').value);">Go!</a>

Upvotes: 2

Related Questions