Secure User Input with Markdown

Posted in PHP by

You often have to validate user input, for examples in comments. Allowing html markup is insecure, bbcode is old. Markdown is the solution. Markdown alone does not secure the user input, but together with htmlspecialchars it will provide a better security.

Never trust user input

Read more about Markdown. Download a php implementation.

Assumed you have a textarea name="msg" in a form method="post". You don't want to allow any html markup, because it could be abused. You still want to allow your users to use elements like strong,em,p and so on. The Markdown syntax allows to write common elements with a simpler syntax, that is good for people without html knowledge. And the basic elements can be explained in a small box next to the textarea. Once the user pressed the submit button, we have the content in $_POST['msg']. We have to options now: Remove all HTML or just escape it, so it displays as written in the textarea. Below a small example of the possible script.

<php
include "markdown.php";
//For showing HTML as text
$_POST['msg'] = htmlspecialchars($_POST['msg']);
//For removing all HTML elements
$_POST['msg'] = strip_tags($_POST['msg']);
$my_html = Markdown($_POST['msg']);

That's it. Well nearly. We gonna do a testrun with Markdown. And if it went fine, report back.

Published at , Updated at 2011-10-25

next: Exception prev: user friendly urls