如何使用Markdown和MySQL?

I want my users to be able to comment using Markdown and avoiding XSS.

What is the correct sequence of actions to do ?

This is my understanding of how it works:

user input via HTML form using Markdown syntax
$Input = markdown(mysql_real_escape_string($_POST['userInput']));
insert $input into database

And then, Do I need also to use htmlspecialchars ?

mysql_real_escape_string is used to avoid SQL INJECTION. Because it escapes SQL.

XSS can be avoided using strip_tags(), preg_match() and htmlspecialchars() together

XSS is based on html tags that contains exploits. For example scripts in java script, or redirections, or opening files in tags.

strip_tags() removes html tags. Also there is one more interesting function called

htmlspecialchars() for preventing XSS.

The most imporant things to prevent sql injection attack

  1. Data Validation using preg_match
  2. Data Sanitization using strip_tags
  3. Output Escaping using htmlspecialchars

so first you should validate data, then sanitize it and finally escape it using htmlspecialchars.

Escaping should be the last thing you do before inserting data into the database. Running markdown, or any other function on it at that point, is too late.

Secondly, HTML escaping and Markdown conversion is a display concern, and should not affect what's written to the database. Perform these functions when rendering an HTML page, and not before. The database should contain the raw markdown, not the HTML version.