PHP输出的最佳做法 [英] Best practice for PHP output

查看:136
本文介绍了PHP输出的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,下面的例子中的最佳做法是什么。

I was wondering, whats the best practice on the example below.

<?php

if(isset($_POST['query'])){
  $out = $_POST['query'];
}

?>
<div><?php echo $out; ?></div>
<input type="text" value="<?php echo $out; ?>" />

使用上述代码会对网站构成威胁。或者我需要在使用之前准备输出,如上所述。通过准备我的意思是编码或转义特殊字符。

Using the above code would this pose a threat to website. Or would I need to prepare the output before using it as above. By prepare I mean encode it or escape special characters.

我知道您需要转义它并验证数据库使用的输入,输出方式如何? >

I am aware you need to escape it and validate inputs for db use, how about for outputting it?

推荐答案

是的,由于你把它放在HTML中,你应该使用 htmlspecialchars

Yes, since you’re putting it out into HTML you should use encode HTML’s special characters appropriately with htmlspecialchars:

if (isset($_POST['query'])) {
    $out = htmlspecialchars($_POST['query']);
}

此外, $ out 仅在 $ _ POST ['query'] 存在时定义;如果 $ _ POST ['query'] 不存在,则应考虑使用默认值。否则,如果启用了注册全局变量(这是一个坏主意),您可以通过URL查询字符串与?out = ...

Besides that, $out is only defined when $_POST['query'] exists; you should think about having a default value if $_POST['query'] does not exist. Because otherwise, when register globals are enabled (that alone is a bad idea) you could set that variable via the URL query string with ?out=….

这篇关于PHP输出的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆