Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a long question, but I think what you're actually asking boils down to:</p> <p>"Should I escape HTML before inserting it into my database, or when I go to display it?"</p> <p>The generally accepted answer to this question is that you should escape the HTML (via <code>htmlspecialchars</code>) when you go to display it to the user, and <strong>not</strong> before putting it into the database.</p> <p>The reason is this: a database stores data. What you are putting into it is what the user typed. When you call <code>mysql_real_escape_string</code>, it does not alter what is inserted into the database; it merely avoids interpreting the user's input as SQL statements. <code>htmlspecialchars</code> does the same thing for HTML; when you print the user's input, it will avoid having it interpreted as HTML. If you were to call <code>htmlspecialchars</code> before the insert, you are no longer being faithful.</p> <p>You should always strive to have the maximum-fidelity representation you can get. Since storing the "malicious" code in your database does no harm (in fact, it saves you some space, since escaped HTML is longer than unescaped!), and you might in the future <em>want</em> that HTML (what if you use an XML parser on user comments, or some day let trusted users have a subset of HTML in their comments, or some such?), why not let it be?</p> <p>You also ask a bit about other types of input validation (integer constraints, etc). Your database schema should enforce these, and they can also be checked at the application layer (preferably on input via JS and then again server side).</p> <p>On another note, the best way to do database escaping with PHP is probably to use PDO, rather than calling <code>mysql_real_escape_string</code> directly. PDO has more advanced functionality, including type checking.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload