安全地编码字符串并将其从 html 链接传递到 PHP 程序

发布于 2024-08-29 03:56:20 字数 689 浏览 8 评论 0原文

需要采取哪些系列步骤才能安全编码和 使用 javascript 从 html href 传递一个字符串来构建指向 php 程序的链接。

在 javascript 中设置

// encodes a URI component.
path = "mypgm.php?from=" + encodeURIComponent(myvar) ;

php 中的 URL:

// get passed variables
$myvar = isset($_GET['myvar']) ? ($_GET['myvar']) : ''; 

// decode - (make the string  readable)
$myvar = (rawurldecode($myvar));

// converts characters to HTML entities (reduce risk of attack)
$myvar = htmlentities($myvar);

// maybe custom sanitize program as well?
// see [http://stackoverflow.com/questions/2668854/php-sanitizing-strings-to-make-them-url-and-filename-safe][1]
$myvar = sanitize($myvar);

What series of steps would be reqired to safely encode and
pass a string from a html href using javascript to construct the link to a php program.

in javascript set up URL

// encodes a URI component.
path = "mypgm.php?from=" + encodeURIComponent(myvar) ;

in php:

// get passed variables
$myvar = isset($_GET['myvar']) ? ($_GET['myvar']) : ''; 

// decode - (make the string  readable)
$myvar = (rawurldecode($myvar));

// converts characters to HTML entities (reduce risk of attack)
$myvar = htmlentities($myvar);

// maybe custom sanitize program as well?
// see [http://stackoverflow.com/questions/2668854/php-sanitizing-strings-to-make-them-url-and-filename-safe][1]
$myvar = sanitize($myvar);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三岁铭 2024-09-05 03:56:20

我认为前两行应该没问题。如果必须将其输出为文本,则可以使用 htmlentities。

I think the first two lines should be fine. You would use htmlentities if and when you have to output it as text.

栀子花开つ 2024-09-05 03:56:20

查看您的代码,您真正需要的是:

$myvar = !empty($_GET['myvar']) ? $_GET['myvar'] : '';

除此之外,PHP 还会自动进行 URL 解码。我个人更喜欢在输出数据时执行 htmlentities()htmlspecialchars() ,即:

<?php echo htmlentities($mydata); ?>

您特别需要转义或清理数据的唯一其他时间是如果您正在构建一个 SQL 查询:

$data = mysql_real_escape_string($mydata);
$query = "SELECT * FROM table WHERE stuff = '$mydata'";

这将防止 SQL 注入。除非您正在格式化用户输入或执行验证,否则绝对没有必要进行任何其他类型的清理。

希望这有帮助!

Looking at your code, all you really need is this:

$myvar = !empty($_GET['myvar']) ? $_GET['myvar'] : '';

Beyond that, PHP automatically URL decodes. I personally prefer to do my htmlentities() or htmlspecialchars() when I go to output data, i.e.:

<?php echo htmlentities($mydata); ?>

The only other time you specifically need to escape or sanitize data is if you're building a SQL query:

$data = mysql_real_escape_string($mydata);
$query = "SELECT * FROM table WHERE stuff = '$mydata'";

That will prevent SQL injection. Unless you're formatting user input or performing validation, it's not absolutely necessary to do any other kind of sanitization.

Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文