Swiss Mister
Swiss Mister

Reputation: 3414

MISGUIDED - htmlentities does not work

UPDATE

(I could just delete this question - but I might as well leave it as a reminder to everyone that sometimes the error is somewhere else than where we look...)

I am very sorry that I made you ponder this question: the reason for the "Actual result" was in a completely different location and has nothing to do with htmlentities.

Thanks to everyone who tried to help.


Why is this code not working in my PHP 5.4.32 site?

Code:

$returnValue = htmlentities(urldecode('//echo \'<textarea name="comments" id="comments">$theData</textarea>\';'), ENT_QUOTES, 'UTF-8');
echo '<textarea>' . $returnValue . '</textarea>';

Expected result:

A textarea with the exact string

//echo '<textarea name="comments" id="comments">$theData</textarea>';

Actual result:

A textarea with the exact string

//echo '<textarea name="comments" id="comments">$theData

(the "" in the original string actually closes the html textarea.)

In the same way, scripts can be injected (which is the reason why I originally used the htmlentities).

The very strange thing:

If I simply add the above example code to the beginning of my php file, it works as expected. So there must be some reason why it does not work further down the page. And I have no clue, see no possible reason in the code.

What's wrong?

btw: using htmlspecialchars doesn't change the effect.

Upvotes: 0

Views: 102

Answers (3)

Swiss Mister
Swiss Mister

Reputation: 3414

There is nothing wrong with this code. Works perfectly - the error was somewhere else in my php file...

Upvotes: 0

Jasper N. Brouwer
Jasper N. Brouwer

Reputation: 21817

You shouldn't use urldecode() in this case. urldecode() will give you the original value of an url-encoded string (in PHP the return value of urlencode()). You're not working with url-encoded strings here.

The following should give you the expected result:

$returnValue = htmlentities('//echo \'<textarea name="comments" id="comments">$theData</textarea>\';', ENT_QUOTES, 'UTF-8');
echo '<textarea>' . $returnValue . '</textarea>';

Upvotes: 2

pavel
pavel

Reputation: 27092

Dollar sign $ isn't interpreted in single quotes.

Choose and use one of these:

echo '<textarea name="comments" id="comments">' . $theData . '</textarea>';
echo "<textarea name='comments' id='comments'>$theData</textarea>";
echo "<textarea name='comments' id='comments'>" . $theData . "</textarea>";
echo "<textarea name=\"comments\" id=\"comments\">$theData</textarea>";

Upvotes: 3

Related Questions