0

I am using a form to register the user on my website and i have a captcha security on it. Everything is working well and good but the only problem that i am facing is that if i enter a wrong captcha or somehow the page refreshes , all the data entered by the user is wiped out.

what i wish to achieve is that even if the captcha entered is wrong and the form is submitted , the form should have all the fields intact as the user filled in excluding the captcha field.

How can this be done? My form is html and the processing page is php

Arihant
  • 3,847
  • 16
  • 55
  • 86
  • 1
    I would fix all of the below answers by adding a call to `isset` and either `htmlspecialchars` or `htmlentities`. – nickb May 02 '12 at 15:31

2 Answers2

4

You can populate the value attribute of your form inputs;

<input type="text" name="username" value="<?php 
  if (!empty($_POST['username'])) { 
    echo htmlspecialchars($_POST['username']); 
  }?>" 
/>
Mike B
  • 31,886
  • 13
  • 87
  • 111
  • 2
    Hello XSS security vulnerability! Don't put raw data from outside the system directly into HTML! (Post edited (within the no history window of oportunity) to fix this, so now +1) – Quentin May 02 '12 at 15:29
  • So for each form field i may apply the same ?? – Arihant May 02 '12 at 15:48
  • I am sorry! That worked for me , made a tiny little mistake! So the above code is XSS secure? am i right? – Arihant May 02 '12 at 15:59
  • 1
    @user1216752 Yes, read [this question to learn all about preventing XSS attacks](http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php) – Mike B May 02 '12 at 16:00
  • Can you tell me how can the same be done for checkboxes and radio buttons?? – Arihant May 02 '12 at 16:01
  • Use `isset()` instead of `!empty()` to also catch value `"0"`. See https://stackoverflow.com/questions/7191626/isset-and-empty-what-to-use. – Peter Nowee Jul 20 '20 at 17:10
0

You need to set the form action to the current page. As long as there are errors, the same script will get called and this script may fill in the form values as described in the other answers. Only on success you will redirect the user to another page.

feeela
  • 29,399
  • 7
  • 59
  • 71
  • Uhm – it's called "Affenformular" and German and there is a nice description in the [German Wikipedia](http://de.wikipedia.org/wiki/Affenformular). – feeela May 02 '12 at 16:03