-3

I'm trying to populate a form with some data that contains special characters (e.g. single quote, double quote,<,>,?,","".~,,!@#$%^&*()_+}{":?<<>,./;'[.] etc) :

<input type="text" name="message" size="200" maxlength="200"
 value =<?php echo $message;?>> 

However, $message, which comes from a MySQL table, isn't displayed correctly - any HTML output that should be in $message is broken.

How do I do this properly?

Tim Post
  • 33,371
  • 15
  • 110
  • 174
PHP
  • 159
  • 3
  • 3
  • 12
  • 4
    Possible duplicate of [How to properly escape html form input default values in php?](http://stackoverflow.com/questions/6249151/how-to-properly-escape-html-form-input-default-values-in-php) – Paul Roub Apr 15 '16 at 17:56

4 Answers4

17

This will prevent your tags from being broken by the echo:

<?php echo htmlentities($message); ?>

Alexandre Danault
  • 8,602
  • 3
  • 30
  • 33
10

If you want to display it

echo htmlspecialchars($messge, ENT_QUOTES, 'UTF-8');

That's what I usually do.

Since the answers are difference:

htmlentities-vs-htmlspecialchars is worth checking out.

Community
  • 1
  • 1
Touch
  • 1,481
  • 10
  • 19
2

I normally use the following code, see htmlspecialchars

<?php echo htmlspecialchars($videoId, ENT_QUOTES | ENT_HTML5); ?>
Hugo Delsing
  • 13,803
  • 5
  • 45
  • 72
-1

whats wrong with using a constant ?

<?php
define(foo,'<,>,?,","".~,,!@#$%^&*()_+}{":?<<>,./;');
$foo2="'[.]";
echo constant('foo').$foo2;
?>

you need to put the '[.]' into a variable, as a constant will break on a ' (single quote).

Degar007
  • 107
  • 1
  • 5