Securing input with htmlspecialchars

the function I use to secure the input from the user is that:

function secure($sec) {
return mysql_real_escape_string( htmlspecialchars ($sec) );

Then insert the data to database…
But when Im trying to show a message the user posted
if he uses the sign: "
It prints it like that: \"
How can I make it print it the same way without making security holes?

The idea is FIEO: Filter input, escape output

What you’re doing here is filter input and escape input, and that is bound to get you in problems like the one you’re describing in this post.

When you insert something in the database (or update for that matter) only use mysql_real_escape_string (not htmlentities!).
When you show data from the database (as a result from a SELECT query), then use htmlentities.

Don’t mix those two up; as you’ve seen you get unexpected results.

mysql_query('INSERT INTO myTable SET something="'.mysql_real_escape_string($something).'"');

$res=mysql_query('SELECT something FROM myTable');
while ($row=mysql_fetch_assoc($res))
  echo htmlentities($row['something']);

I didnt used htmlentities function I used
htmlspecialchars function…

And I tried your way but it does not support my website language which is hebrew…
Is there any other way to make it work ?

What went wrong exactly?

Are your database and the database connection in UTF-8? If this is the case it should work.

The first you can check by running a SHOW CREATE TABLE on the table in question, and you can make sure the connection uses utf8 by calling mysql_set_charset('utf8');.

It still aint showing me the text properly…
Is there any other way of doing it that will support
Characte encoding: Windows-1255

<meta http-equiv="content-type" content="text/html; charset=windows-1255" />

htmlspecialchars function supports it…

What code are you using now ?