PHP: convert TinyMCE strings
Blogs20112011-10-30
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
//1. allow HTML tags list:
$allowedTags='<p><strong><em><u><h1><h2><h3><h4><h5><h6><img>';
$allowedTags.='<li><ol><ul><span><div><br><ins><del>';
//2. parse HTTP request string:
if(isset($_POST['elm']) && !empty($_POST['elm']) {
if (get_magic_quotes_gpc())
$content = $_POST['wysiwyg'];
else
$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.
