How to make $_POST more secured?

2019-05-23 17:06发布

问题:

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

回答1:

Read this link thoroughly it will help u about form validations and security purpose - http://phpsec.org/projects/guide/2.html



回答2:

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.



标签: php security