2

This is a sample code that i got from Facebook Engineering page.

<?php
if ($_POST['name']) {
?>
    <span>Hello, <?=$_POST['name']?>.</span>
<?php 
} else {
?>
<form method="post">
What is your name?<br>
<input type="text" name="name">
<input type="submit">
</form>
<?php
}

It says that the above code is not secured because it is open to cross site scripting. the correct way is to pass the $_POST['name'] via htmlspecialchars(). However, they stated that it is poor programming practice.

Is always passing $_POST variable via a htmlspecialchars() inefficient?

I can't thought of any way to make it secure. They introduce XHP which i am reluctant to use.

Reference: https://www.facebook.com/notes/facebook-engineering/xhp-a-new-way-to-write-php/294003943919

Slay
  • 1,285
  • 4
  • 20
  • 44
  • I would recommend to follow this question [Best Way to stop Sql Injection][1] [1]: http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php – Moyed Ansari May 07 '12 at 05:01
  • @MoyedAnsari Don't see what this has to do with SQL injection at all. Derek, I suggest you read this - http://blog.astrumfutura.com/2012/03/a-hitchhikers-guide-to-cross-site-scripting-xss-in-php-part-1-how-not-to-use-htmlspecialchars-for-output-escaping/ – Phil May 07 '12 at 05:03
  • @Derek Also, they don't say using `htmlspecialchars()` is *poor practice*, just that it *might* be better to use something that escapes HTML output by default. I would recommend [Twig](http://twig.sensiolabs.org/) over that `echo` mess in XHP though. – Phil May 07 '12 at 05:06
  • Thanks Phil, i think i misread it.. @MoyedAnsari reading that now. – Slay May 07 '12 at 05:09

1 Answers1

0

the correct way is to pass the $_POST['name'] via htmlspecialchars(). However, they stated that it is poor programming practice.

It's not poor practice in itself. The problem is that when you have to type htmlspecialchars every single time you drop text content into HTML, you are quite likely to forget one, leaving a vulnerability.

What that page is saying, correctly, is that it's better to have a templating language that HTML-escapes by default, so that you don't have to think about it. This is a lesson most web frameworks have learned by now, but raw PHP still doesn't have a convenient way to do that.

bobince
  • 528,062
  • 107
  • 651
  • 834