Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly escape password field on HTML form?

Tags:

php

Input field for password usually accepts a wide range of characters compared to text inputs. The normal way of escaping an input on HTML form involves using htmlspecialchars($_POST['content']) on the input contents.

What if, in the scenario of a failed validation of a password update process, I require the new password to repopulate on the HTML form? Something like '> yeah would have caused the form to malfunction and using htmlspecialchars would produce a totally different password.

Any suggestions?

The html portion as shown:

<INPUT type=password name=password1 value=''&gt;&lt;script&gt;try' size=15 maxlength=15>

The corresponding php code:

function h($str) {echo htmlspecialchars($str);}
echo "<INPUT type=password name=password1 value='", h(@$_POST['password1']), "' size=15 maxlength=15>";

Blank is shown in the form input field.

UPDATE

The problem lies with my htmlspecialchars which does not escape single quotes by default. Now adding the ENT_QUOTES parameters allow the single quote to be escaped and solve my problem. deceze and CodeCaster are right that htmlspecialchars does not change the password. Thanks all.

like image 879
Question Overflow Avatar asked Sep 02 '25 13:09

Question Overflow


2 Answers

No, htmlspecialchars would not produce a totally different password. It would produce value="&gt; yeah" which, when parsed by the browser, is read as > yeah. Password fields are not in any way special in the treatment of special or non-special characters.

like image 155
deceze Avatar answered Sep 05 '25 16:09

deceze


Separate display logic from data logic.

Before you want to display data on an html page, use htmlspecialchars(). If you're about to store it in a database, use the appropriate sql escaping method (like mysql_real_escape_string().

By the way, if an input element contains for example &gt, it will be seen as > when posted;

like image 20
CodeCaster Avatar answered Sep 05 '25 17:09

CodeCaster