php 如何在php中正确转义html表单输入默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6249151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:47:12  来源:igfitidea点击:

How to properly escape html form input default values in php?

phphtmlformsxss

提问by Ryan

Given the following two html/php snippets:

给定以下两个 html/php 片段:

<input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" />

and

<textarea name="content"><?php echo $_POST['content']; ?></textarea>

what character encoding do I need to use for the echoed $_POSTvariables? Can I use any built in PHP functions? Please assume that the $_POSTvalues have not been encoded at all yet. No magic quotes no nothing.

我需要对回显$_POST变量使用什么字符编码?我可以使用任何内置的 PHP 函数吗?请假设这些$_POST值还没有被编码。没有魔法引述什么都没有。

回答by rid

Use htmlspecialchars($_POST['firstname'])and htmlspecialchars($_POST['content']).

使用htmlspecialchars($_POST['firstname'])htmlspecialchars($_POST['content'])

Always escape strings with htmlspecialchars()before showing them to the user.

htmlspecialchars()向用户显示字符串之前,始终使用 转义字符串。

回答by Niklas

htmlspecialcharswould work in both cases. Have a look at the different flag options to avoid quotation marks being a problem in the inputcase.

htmlspecialchars在这两种情况下都可以使用。查看不同的标志选项以避免引号在input案例中成为问题。

回答by Eric

Given it is kinda long I would put it in a function

鉴于它有点长,我会把它放在一个函数中

<?PHP
function encodeValue ($s) {
    return htmlentities($s, ENT_COMPAT|ENT_QUOTES,'ISO-8859-1', true); 
}
?>

This has ENT_QUOTESto make sure single and double quotes are encoded, but it will also encode special characters(Like in José) instead of inserting an empty string.

这有ENT_QUOTES以确保对单引号和双引号进行编码,但它也会编码特殊字符(如 José),而不是插入空字符串。

Then you can do:

然后你可以这样做:

<input type="text" name="firstname" value="<?= encodeValue($_POST['firstname']) ?>" />

and

<textarea name="content"><?= encodeValue($_POST['content']) ?></textarea>