Re-fill posted form data via PHP securely

2019-07-09 09:24发布

问题:

How can I ref-fill posted form data via PHP in the event of an error. I have a contact form and the user enters a bunch of information and if one field doesn't validate, he loses everything. How can I stop this from happening and make sure it is secure?

I've tried this, but believe I read somewhere it is not secure:

<input type="text" name="name" value="<?php echo $_POST['name']; ?>" />

回答1:

One issue is that if $_POST['name'] contains a ", then the value can 'escape' out and rewrite the page content.

Another is that with strict error checking switched on, accessing a non-existent array index will throw a Notice error.

Here is one safe way of re-filling the form data:

<input type="text" name="name" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>" />

I would personally recommend handling form display and validation through a framework, like Zend_Form within the Zend Framework. (You won't have to change everything else across just to use the form stuff) It makes writing safe and readable code much easier.