Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web

Naming Form Elements Dynamically

4.00/5 (1 vote)
13 Mar 2015CPOL1 min read 11.5K   22  
I am just applying the principle of Defence in Depth

Introduction

In this tip, I am going to add one more security layer to a web form submission.

Normally, when naming form elements, we choose static/fixed name for each element.

In my technique, I am going to hash the names of the form elements using dynamic salted values, so that a name of an element varies from a user to another!

Namely, I choose a concatenation of the “IP address, the user agent, beside a fixed string” as a salt to hash the name of a form element.

This way, we greatly reduce the risk of playing with our form!

Using the Code

Here is a PHP function that hashes a name of a form element using SHA1 and a dynamically salted string:

PHP
function HashedFieldName($field){
$salt='hawom169';
$fullSalt=$_SERVER['HTTP_USER_AGENT'].getRealIpAddr().$salt.$field.$salt;
return 'A'. substr(sha1($fullSalt),0,20);
}

The function getRealIpAddr() is used to get the user IP address, I  took it from https://gist.github.com/owcall/2928583.

Then, the function HashedFieldName($field) is used to name a form element like this:

PHP
<?php $namefield='username';?>
<input type="text" id="txtname" name="<?php echo(HashedFieldName($namefield)) ?>">

Looking carefully to the code, we will see that I used a fixed value for the ID property of the text element; this way, we can easily access that element via JavaScript at the client side:

JavaScript
var obj=document.getElementById('txtname');
   if(obj.value==''){
       window.alert('You must enter your name');
	   obj.focus();
	   return false;
    }

To expose the form submitted data at the server side, we may use a code like this:

PHP
echo("Thank you " . $_POST[HashedFieldName($namefield)].",Your registration is completed successfully!");

What is Next?

In my next article, I am going to provide a complete solution that uses my technique: Preventing Resending by Refresh and Reducing the Need of Captcha.

Points of Interest

  • The example is provided in PHP, it is obvious that it can be used by any other technology such as .NET or Java.
  • The same technique can also be used for dynamically naming cookies (session cookies), which reduces the risk of cookie theft.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)