简体   繁体   English

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

[英]safely encode and pass a string from a html link to PHP program

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. 需要采取什么系列的步骤才能安全地编码并使用javascript从html href传递字符串来构造到php程序的链接。

in javascript set up URL 在javascript中设置网址

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

in php: 在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);

I think the first two lines should be fine. 我认为前两行应该没问题。 You would use htmlentities if and when you have to output it as text. 如果需要将htmlentities输出为文本,则可以使用htmlentities。

Looking at your code, all you really need is this: 查看您的代码,您真正需要的是:

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

Beyond that, PHP automatically URL decodes. 除此之外,PHP会自动对URL进行解码。 I personally prefer to do my htmlentities() or htmlspecialchars() when I go to output data, ie: 我个人更喜欢在输出数据时执行htmlentities()htmlspecialchars() ,即:

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

The only other time you specifically need to escape or sanitize data is if you're building a SQL query: 特别需要转义或清理数据的其他唯一时间是,如果要构建SQL查询,请执行以下操作:

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

That will prevent SQL injection. 这样可以防止SQL注入。 Unless you're formatting user input or performing validation, it's not absolutely necessary to do any other kind of sanitization. 除非您要格式化用户输入或执行验证,否则绝对没有必要进行任何其他类型的清理。

Hope this helps! 希望这可以帮助!

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

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