-1

I am using following methods to avoid xss attacks. Is this right way to use it?If not please tell me the correct way to avoid attacks.

$first_name=strip_tags($_POST["txt_firstname"]);

This for avoiding xss and

$fname=filter_var($first_name, FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=>"/^[a-zA-Z ]+$/")));
if($fname===FALSE)
{
    echo "error";
}
else {
 echo "success;    
}

is this good way?

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
Kumaran
  • 141
  • 1
  • 2
  • 9

3 Answers3

1

I suggest you use filter_input function with one of the sanitize filters to remove all unwanted characters, and if this is not enough you may as well validate the input by applying an additional filter like you did with filter_var:

$first_name = filter_input(INPUT_POST, 'txt_firstname', 
    FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, 'txt_email',
    FILTER_SANITIZE_EMAIL);

To prevent SQL injections, use prepared statements. See here and here for more.

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
1

strip_tags should remove all tags howevever , You can use filter_var as an alternative for instance to prevent xss attacks

$first_name = filter_var($_POST["txt_firstname"], FILTER_SANITIZE_STRING);

For preventing sql Injection you need to sanitize the POST:

eg:

$first_name = filter_var($_POST["txt_firstname"], FILTER_SANITIZE_STRING);
 $first_name = mysqli_real_escape_string(trim($first_name));
Kheshav Sewnundun
  • 1,236
  • 15
  • 37
1

I'd advise you to use a tool like GUMP to clean/filter/sanitize inputs.

require "gump.class.php";
//remove the line above if you're going to use composer

$gump = new GUMP();

$_POST = $gump->sanitize($_POST);

You can also add your own sanitization filters to filter them and since these tools are specific to handle these problems, in future even if there's a new attack vector found, it will likely be fixed even before you know about them. (as long as you update your tools often)

Cemal
  • 1,469
  • 1
  • 12
  • 19