This is a follow up to my last question here. The answer posted there actually does not work. So here is the challenge. You are given this code (assume jQuery included):
<input type=text>
<script>
$("input").val(**YOUR PHP / JS CODE HERE**);
</script>
Using jQuery - and not by injecting PHP output directly into the input tag - faithfully reproduce ANY text from the database in the input tag. If the database field says </script>
, the field should say that too. If has Chinese in it, double quotes, whatever, reproduce that too. Assume your PHP variable is called $text
.
Here are some of my failed attempts.
1)
$("input").val("<?= htmlentities($text); ?>");
FAILURE: Reproduces character encoding exactly as is in text fields.
INPUT: $text = "Déjà vu"
OUTPUT: Field contains literal déjà vu
2)
$("input").val(<?= json_encode($text); ?>);
This was suggested as the answer in my last question, and I naively accepted it. However...
FAILURE: json_encode
only works with UTF-8 characters.
INPUT: $text = "Va e de här fö frågor egentlien"
OUTPUT: Field is blank, because json_encode
returns null
.
3)
var temp = $("<div></div>").html("<?= htmlentities($text); ?>");
$("input").val(temp.html());
This was my most promising solution for the weird characters, except...
FAILURE: Does not encode some characters (not sure exactly which, don't care)
INPUT: $text = "</script> Déjà"
OUTPUT: Field contains </script> Déjà
4) Suggested in answers
$("input").val(unescape("<?= urlencode($text); ?>"));
FAILURE: Spaces remain encoded as +'s.
$("input").val(unescape(<?= rawurlencode($text); ?>"));
Almost works. All previous input succeeds, but multibyte stuff, like kanji, remain encoded. decodeURIComponent
also doesn't like multibyte characters.
Note that for me, things like strip_tags
are not an option. Everything must be allowed. People are authoring quizzes with this, and if someone wants to make a quiz that tests your knowledge of HTML, so be it. Also, unfortunately I cannot just inject the htmlentities
escaped text into the value field of the input tags. These tags are generated dynamically, and I would have to totally tear down my current javascript code structure to do it that way.
I feel like I'm SOL here. Please show me how wrong I am.
EDIT
Assume the user initally entered </script> Déjà här fö frågor 漢字
into the db. This would be stored (you would see it in phpMyAdmin) as </script> Déjà här fö frågor 漢字