2

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?

Val
  • 17,336
  • 23
  • 95
  • 144
  • Good question. these 2 examples are different. While using htmlspecialchars for the second one should be unconditional, but for the first one it's going to be used only for untrusted input (because it would be unwise if you are site admin and want to use some HTML) – Your Common Sense Nov 18 '10 at 10:19
  • OK I understand but all the answers below says Yes, none explain why, or what makes it so dangerous or an example of attack? – Val Nov 18 '10 at 10:28
  • Thats more like it :) thank you guys. – Val Nov 18 '10 at 10:42
  • note that your second example has nothing to do with threats and shuch. it's just HTML rule. – Your Common Sense Nov 18 '10 at 11:48

3 Answers3

3

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

Gumbo
  • 643,351
  • 109
  • 780
  • 844
2

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?

Community
  • 1
  • 1
Wizzard
  • 12,582
  • 22
  • 68
  • 101
1

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

echo (isset($_POST['query']))? htmlspecialchars($_POST['query']):"";
Barkermn01
  • 6,781
  • 33
  • 83