简体   繁体   中英

How to avoid SQL injection and XSS attacks when in PHP?

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?

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM