Posts Tagged ‘form’

how to process a form with php using one page

Tuesday, June 24th, 2008

Many first time coders in PHP tend to use a form on one page, and a PHP script on a completely different page in order to process it. This is highly irritating since you need to make two pages instead of one, and also, if there is an error you have to redirect back to the original page whilst jumping through hoops to send the data back to the original page.

There is however a rather simple way to do this. First you need to create your (X)HTML document. Below, I’ve created a simple example form using XHTML 1.1

As you can see, it has a single text box and a submit button, with ID’s Name and Submit respectively. Also note the action="". This will automatically make your page post the data to the same page. Many people include the

which is discouraged, since it can lead to XSS Attacks, and since it is not required, it’s just asking for trouble.

OK, onto the PHP code. Here’s some simple PHP, which will check if the form has been posted, by checking if the $_POST['Submit'] is set

	$_POST['Name'] = strip_tags($_POST['Name']);
	$contentdiv = '
Your name is '.$_POST['Name'].'
'; }else{ $contentdiv = '
Please enter your name below
'; } ?>

As you can see, I’ve added the content output I wish to be displayed into a simple <div>. All that is left now is to add some PHP code to the XHTML code to echo out the $content, and save as a .php file and it will all be finished

The PHP code is simply <?php echo $contentdiv; ?> and is added between the <body> and the <form> tags.

You can try out this code by clicking here, or download the script using the button below

Form processor download