6

I have this:

<input name="title" type="text" class="inputMedium" value="' . $inputData['title'] . '" />

I want to strip quotes from user input so that if someone enters something like: "This is my title" it wont mess up my code.

I tried this and it's not working:

$inputData['title'] = str_replace('"', '', $_POST['title']);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Babak
  • 279
  • 1
  • 7
  • 16
  • Featured in *[Jeff Atwood: Stack Overflow - Building Social Software for the Anti Social](https://www.youtube.com/watch?v=NcS7ECsA7cc)* at 13 min 25 secs. (Which also indicates the talk was probably about 10 years earlier than the publication date of 2020.) – Peter Mortensen Feb 04 '22 at 03:04

3 Answers3

8

If I understand the question correctly, you want to remove " from $inputData['title'], so your HTML code is not messed up?

If so, the "right" solution is not to remove double-quotes, but to escape them before doing the actual output.


Considering you are generating HTML, **you should use the [`htmlspecialchars`][1] function**; this way, double-quotes *(and a couple of other characters)* will be encoded to HTML entities, and will not cause any trouble when injected into your HTML markup.

For instance:

echo '<input name="title" type="text" class="inputMedium" value="'
   . htmlspecialchars($inputData['title'])
   . '" />';

Note: depending on your situation (especially, about the encoding/charset you might be using), you might to pass some additional parameters to htmlspecialchars.

Generally speaking, you should always escape the data you are sending as an output, not matter what kind of output format you have.

For instance:

  • If you are generating some XML or HTML, you should use htmlspecialchars
  • If you are generating some SQL, you should use mysql_real_escape_string, or an equivalent, depending on the type of database you're working with
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • Just noticed: one could use single quotes instead of double quotes in the input html (like ). But since htmlspecialchars leaves single quotes alone, this might be a security hole? – Sam Feb 28 '10 at 23:21
2

User input should be run through htmlspecialchars() to be used in this sort of case.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
-1

I highly recommend you to use htmlentities($string, ENT_QUOTES) before displaying anything user generated anywhere...

Kirzilla
  • 16,368
  • 26
  • 84
  • 129
  • 1
    htmlentities hasnt work for me, only htmlspecialchars() did. The problem was that for some reason htmlentities would not handle accent correctly – Guillermo Mar 15 '10 at 16:57