-4

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
  • 32,782
  • 15
  • 106
  • 168
PHP
  • 139
  • 2
  • 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

15

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

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

Alexandre Danault
  • 8,424
  • 3
  • 29
  • 33
9

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,443
  • 10
  • 18
2

I normally use the following code, see htmlspecialchars

<?php echo htmlspecialchars($videoId, ENT_QUOTES | ENT_HTML5); ?>
Hugo Delsing
  • 13,512
  • 5
  • 41
  • 69
-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
  • 77
  • 1
  • 5