简体   繁体   English

如何清理在JavaScript中使用的参数?

[英]How to sanitize parameters for use in javascript?

I have the following php code: 我有以下php代码:

<?php $redirect_lp = $_GET['lp']; ?>
<script>
    setTimeout(function(){
        window.location.href = "<?php echo $redirect_lp; ?>";
    }, 10)
</script>

how do I sanitize $redirect_lp ? 如何清除$redirect_lp

I know this code is bad because of this attack: 我知道这段代码由于这种攻击是不好的:

http://example.com/index.php?lp= "-alert("XSS\\n\\n"%2bdocument.domain)-" http://example.com/index.php?lp= “ -alert(” XSS \\ n \\ n“%2bdocument.domain)-”

to protect from this particular attack, I santizie for " : 为了避免受到这种特殊攻击,我将"表示为"

$redirect_lp = str_replace("\"", "", $redirect_lp);

is this enough? 这够了吗?

First remove all illegal characters from the $redirect_lp variable, then check if it is a valid URL: 首先从$redirect_lp变量中删除所有非法字符,然后检查它是否是有效的URL:

<?php 
   $redirect_lp = $_GET['lp']; 

   // Remove all illegal characters from a url
   $redirect_lp = filter_var($redirect_lp, FILTER_SANITIZE_URL);
?>
<?php if (filter_var($redirect_lp, FILTER_VALIDATE_URL)): ?>
    <script>
       setTimeout(function(){
           window.location.href = "<?php echo $redirect_lp; ?>";
       }, 10)
    </script>
<?php endif; ?>

There are plenty of ways you can filter a string in PHP . 有很多方法可以过滤PHP中的字符串 Here's one way to sanitize a URL : 这是一种清理URL

// Remove all illegal characters from a url
filter_var($redirect_lp, FILTER_SANITIZE_URL);

Or alternatively you can filter the input as you get it: 或者,您也可以过滤输入内容:

$redirect_lp = filter_input(INPUT_GET, 'lp', FILTER_SANITIZE_SPECIAL_CHARS);

Basically you need to use the function htmlspecialchars() whenever you want to output something to the browser that came from the user input. 基本上,每当您想要将来自用户输入的内容输出到浏览器时,都需要使用htmlspecialchars()函数。

The correct way to use something like this (enough to prevent XSS-attack): 使用类似这样的正确方法(足以防止XSS攻击):

echo htmlspecialchars($redirect_lp, ENT_QUOTES, 'UTF-8');

After this kind of sanitation that you can validate url ( filter_var() with FILTER_VALIDATE_URL flag) and allow further steps to redirect user to specified page if validation passed of course. 经过这种卫生处理后,您可以验证url(带有FILTER_VALIDATE_URL标志的filter_var() ),并允许进一步的步骤(如果当然通过了验证)将用户重定向到指定的页面。

PS: You also might want to use strip_tags() , but keep in mind that it removes tags but not special characters like " or ' , so if you use strip_tags() you also have to use htmlspecialchars() . PS:您可能还想使用strip_tags() ,但请记住,它会删除标签,但不能删除诸如"'类的特殊字符,因此,如果您使用strip_tags() ,则还必须使用htmlspecialchars()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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