1

I've run into an issue. I am building an Ajax application with PHP, and am sanitizing my inputs via htmlspecialchars(). I am then processing the inputted string and using that to set the data attributes of certain html elements. There's my problem.

Let's just say the user wrote <html>. That input, with htmlspecialchars(), would be turned into &lt;html&gt;. Now this is fine for displaying the content, but for the data attributes, I would like it to be inserted as <html>. Is this possible?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Someone
  • 428
  • 5
  • 17
  • What are you going to do with the data attributes? – Pekka Jun 03 '13 at 22:20
  • The user inputs a string, I break down the string, and use the data attributes to search the string. – Someone Jun 03 '13 at 22:21
  • The thing is, you *could* of course refrain from using htmlspecialchars() for that specific case but then you would be nullifying the security that you're using the sanitation for in the first place - you could then just as well stop using it at all on that page. That's probably not a good idea. How are you searching the string, maybe you can convert the special characters back at that point? – Pekka Jun 03 '13 at 22:26
  • Well, I am using a button with the data attributes. So would it be possible to set the data with non-escaped html, and set the physical html of the button with the escaped html? – Someone Jun 03 '13 at 22:28
  • Yes, so what I'm saying is set the data attributes with non-escaped html, and set the inner html of the button with the escaped html. – Someone Jun 03 '13 at 22:32
  • It's fine to use `htmlspecialchars()` for attributes. The browser should decode them when processing the attribute strings. – Barmar Jun 03 '13 at 22:34
  • Got it. Let me try this and I'll tell you what happens. – Someone Jun 03 '13 at 22:35
  • 1
    Note that you only need to use `htmlspecialchars()` at all if PHP is creating the HTML. You don't need to use it when passing data back and forth using AJAX. – Barmar Jun 03 '13 at 22:35
  • So I do have php creating the data attributes. Would I have to use it on those data attributes? – Someone Jun 03 '13 at 22:37
  • So then my plan above wouldn't work, correct? – Someone Jun 03 '13 at 22:38
  • I'm not sure I fully understand the situation, so I don't know. Either way, you could do the decoding (if necessary) in JavaScript: [Javascript decoding html entities](http://stackoverflow.com/q/10715801) – Pekka Jun 03 '13 at 22:43
  • Actually, I just found a solution by creating two different variables based on the same input, one totally stripped of all non-alphabetic characters and one sanitized via htmlspecialchars() – Someone Jun 03 '13 at 22:43

1 Answers1

0

there is a function that reverses what htmlspecialchars does:

htmlspecialchars_decode()

http://php.net/manual/en/function.htmlspecialchars-decode.php

Ziarno
  • 7,366
  • 5
  • 34
  • 40