Pergunta

On my server I have magic_quotes turned off. When a user save content as article in my DB from a form, I use

$text = mysql_real_escape_string($_POST['text']); to prevent SQL Injecion.

This is my input <img src="image.png"></img> and this is what it is saved in the DB <img src="image.png"></img>

When I echo htmlentities($row['text']); i get <img src="image.png"></img> printed on screen, on view source I get &lt;img src=&quot;image.png&quot;&gt;&lt;/img&gt;.

My questions are

  1. Isn't supposed to be saved in DB like <img src=\"image.png\"></img> to prevent SQL Injections ?
  2. Is htmlentities is a good candidate to prevent XSS attacks?
  3. Should I turn on magic_quotes?
Foi útil?

Solução

Isn't supposed to be saved in DB like <img src=\"image.png\"></img> to prevent SQL Injections ?

No, SQL injections are widely misunderstood, mainly because they actually have nothing to do with SQL as they are just string manipulation. You don't need to alter the data you insert into the database, you only have to alter the string you send to the database server as query (unless you do the wise choice and use prepared statements instead of escaping the query string). The data, once stored, should be in its original state.

Is htmlentities is a good candidate to prevent XSS attacks?

Yes but htmlentities() is good for sending data as output to the browser, not for storing it into the database (as the data from the DB might be used for something other than a web page).

Should I turn on magic_quotes?

No, you should use prepared statements.

Outras dicas

  1. It seems that your magic quotes is enabled. Check it.
  2. There are a lot of articles about this but for quick starting don't allow to use javascript and external images.

Getting escaped data out of the database suggests it's been double-escaped - does your PHP have magic_quotes_gpc turned on? If you want to sanitize HTML and allow only certain constructs you specify through, then I suggest using HTMLPurifier which'll get as strict or lax as you want.

Use mysql_real_escape_string and turn the quotes back to normal:

$text = str_replace('\"', '"', $row['text']); // Alternative one
$text = preg_replace("/X/", '"', $row['text']); // Alternative two. X needs to be \\", \\\" or \\\\", perhaps \\\\\"

Answers to updated questions:

Correct saving of data goes like this:

input -> php - > mysql_real_escape_string -> db -> php -> htmlspecialchars -> browser

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top