如何在我的功能中防止XSS攻击?

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);
}

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

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

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

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.

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.