title: How to prevent code injection attacks in PHP?
body: <p>I am a bit confused, there are so many functions in PHP, and some using this, some using that. Some people use: <code>htmlspecialchars()</code>, <code>htmlentities()</code>, <code>strip_tags()</code> etc</p>
  
  <p>Which is the correct one and what do you guys usually use?</p>
  
  <p>Is this correct (advise me a better one, if any):</p>
  
  <pre><code>$var = mysql_real_escape_string(htmlentities($_POST['username']));
  </code></pre>
  
  <p>This line can prevent MySQL injection and XSS attack??</p>
  
  <p><strong>Btw, is there any other things I need to pay attention besides XSS attack and MySQL injection?</strong></p>
  
  <p><strong>EDIT</strong></p>
  
  <p>To conclude:</p>
  
  <p>If I want to insert string to the database, I do not need to use <code>htmlentities</code>, just use the <code>mysql_real_escape_string</code>. When displaying the data, use <code>htmlentities()</code>, is that what you all mean??</p>
  
  <p>Summarize:</p>
  
  <ul>
  <li><code>mysql_real_escape_string</code> used when insert into database</li>
  <li><code>htmlentities()</code> used when outputting data into webpage</li>
  <li><code>htmlspecialchars()</code> used when?</li>
  <li><code>strip_tags()</code> used when?</li>
  <li><code>addslashes()</code> used when?</li>
  </ul>
  
  <p>Can somebody fill in the question mark?</p>