EnexoOnoma
EnexoOnoma

Reputation: 8834

How to prevent XSS attack in my function?

I am creating a function for my $_POST inputs to prevent SQL Injection BEFORE adding the values into database. I use it on login/register and when a user needs to post an article. As far as I know, this does not secure it from XSS.

Should I create a different function when I output data or edit this?

Thank you.

function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}

Upvotes: 0

Views: 758

Answers (4)

shesek
shesek

Reputation: 4682

You shouldn't save values as encoded HTML to your database. Do that when outputting them, not when saving them (saving encoded HTML makes it harder to search in it, makes their size bigger, makes it harder to use them in formats other than HTML and generally just wrong - your database should store the actual text, not the text formatted to be displayed in a specific way).

Also, as Quamis said, you should probably look at PDO or some other DBAL that lets you use prepared statements instead of escaping it manually.

Upvotes: 0

Quamis
Quamis

Reputation: 11087

Try using prepared statements. They are designed to automatically escape things. They should also keep your queries cleaner in the source code.

Upvotes: 3

alex
alex

Reputation: 490637

You talk about XSS and then SQL injection...

SQL

Use mysql_real_escape_string() or better still bind params with a library such as PDO.

If magic_quotes is a possibility, use...

function sqlEscape($str) {
   if (get_magic_quotes_gpc()) {
      $str = stripslashes($str);
   }
   return mysql_real_escape_string($str);
}

Regarding your example, why do you need to use trim() to make data safe? Also, why use the error supressor on trim()?

XSS

Use htmlspecialchars($str, ENT_QUOTES) to prevent HTML special characters from having special meaning.

Upvotes: 3

nbelmont
nbelmont

Reputation: 71

I use the following, which works just fine to prevent injections:

function clean($str) {
    $value = mysql_escape_string(stripslashes(htmlspecialchars($str)));
    return $value;
}

Upvotes: 0

Related Questions