Post Syntax

How to submit data with forms

Hm.. So you want a form on your website? And you want to be able to do something with the data which has been submitted. So, let us assume you have a page, with a form. If you do not know how to do this, have a look atthe HTML tutorials. Anyway. Our page, form.html, has the following form:

<form action=”process.php” method=”POST”>
<input type=”text” name=”MyVar1″>Enter text here
<input type=”text” name=”MyVar2″>Enter text here
<input type=”submit”>

When the submit button is pressed, the data is submitted over the internet, to the form processing script, which you have in the file process.php. So, what happens there? Basically, all the text which you type into the textfields, become the value of variables, while the names of the textfields, become the name of variables. And like passing variables through the URL, these variables are placed in a global variable array, but in this case, the POST array. So like in the GET situation, you can retrieve the values from the POST array in the processing page:

1
2
3
4
<? 
 $myvar1 = $_POST['MyVar1'];
 $myvar2 = $_POST['MyVar2'];
 ?>
<? 
 $myvar1 = $_POST['MyVar1'];
 $myvar2 = $_POST['MyVar2'];
 ?>

An issue is that you can not be certain that the page which is loaded, was accessed through a link with added variables. So you need to check whether the variable was set before actually using it:

1
2
3
4
5
6
7
8
9
10
<? 
 if(isset($_POST['MyVar1']))
   {
   $myvar1 = $_POST['MyVar1'];
   }
 else
   {
   $myvar1 = 1;  // Set a default value for the variable
   }
 ?>
<? 
 if(isset($_POST['MyVar1']))
   {
   $myvar1 = $_POST['MyVar1'];
   }
 else
   {
   $myvar1 = 1;  // Set a default value for the variable
   }
 ?>

A third issue has to do with the safety of your programs, and the vulnerability of the program to hacking. In PhP you can automatically have the variables extracted from the $_POST array. This is set in the php.ini, and called “REGISTER_GLOBALS”, which should be switched off. If you switch it to on, the variables are automatically defined in the script, and people can pass values through the form to the script you are running. This is in particular a problem when you are using database driving scripts, but can also affect other scripts. (Have a look at a paper about SQL inject). It is therefore wise to check whether the variable is actually of the type, and holds the information which you would expect. In an other tutorial we will get into this.

Leave a Reply