William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP: convert TinyMCE strings

PHP: convert TinyMCE strings

If you use famous wysiwyg tool TinyMCE + PHP, it is common to convert TinyMCE string into MySQL DB or present as HTML. This easily causes problems if operating special chars (\’, “, &, < > \.) etc. Here I list the 2 cases: TinyMCE output as HTML; and TinyMCE output to Database.

1. without a database

Here is a very useful help article for the convert WITHOUT Database operation: How-to implement TinyMCE in PHP. I summary and use like this: (suppose the tinymce <textarea id=’elm’>)

//1. allow HTML tags list:
//2. parse HTTP request string:
if(isset($_POST['elm']) && !empty($_POST['elm']) {
 if (get_magic_quotes_gpc()) 
  $content = $_POST['wysiwyg'];
  $content = addslashes($_POST['wysiwyg']);

//3. filter the string, only allowed tags are passed.
$content = strip_tags($content,$allowedTags);

//4. display parsed string as HTML:
<textarea id="elm1" name="elm1" rows="15" 
 cols="80"><?php echo $content;?></textarea>

2. with a database

TinyMCE string can NOT be directly inserted into Database, some pre-processed should be taken in case of special chars.

  • use mysql_real_escape_string to escapes special characters in a string for use in an SQL statement; it prepends backslashes to the following characters:
    \x00, \n, \r, \, ‘, ” and \x1a.

    This function must always be used to make data safe before sending a query to MySQL.

  • if using PEAR MDB2, use escape to quote a string so it can be safely used in a query.

  • for magic_quotes_gpc (boolean):
    Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ‘ (single-quote), ” (double quote), \ (backslash) and NUL’s are escaped with a backslash automatically.

    The setting is in php.ini, can be viewed by phpinfo(); and normally, the magic_quotes is off by default.

So when use TinyMCE and other WYSIWYG tools, make sure the edited content are used for DB operation, or just HTML display, then take action to control the string.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: