开发者

Best practice for PHP output

开发者 https://www.devze.com 2023-01-25 22:17 出处:网络
I was wondering, whats the best practice on the example below. <?php if(isset($_POST[\'query\'])){ $out = $_POST[\'query\'];

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 pre开发者_运维问答pare 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?


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']);
}

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=….


Yes, you should be using the php function htmlspecialchars http://php.net/manual/en/function.htmlspecialchars.php

also, see this (accepted answer)

Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?


dont know about best practise and that depend on the coder i like turnary

echo (isset($_POST['query']))? htmlspecialchars($_POST['query']):"";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号