PHP POST Variables
A POST Variable is a special kind of variable that is used for handling form data. POST variables are created when a (POST type) form is submitted. They will contain all values of the form fields. Although a form can send its data through the POST method or the GET method. When using the POST method, the values of the form fields are stored inside these POST variables. There will be created an array $_POST containing all data. Each form field has its own sub-variable to this array ($_POST[‘form_field_name’]). Take for example this form:
<form method=”POST” action=”<?=$_SERVER[‘PHP_SELF’];?>”> <input type=’text’ name=’username’> <input type=’password’ name=’password’> <input type=’submit’ name=’submitBut’ value=’Login!’> </form>
The above form has 3 fields. Two of them are text fields which can be given values to by the user. The other ‘field’ is a submit button ( which will automaticly be given the value ‘Login!’ in this example ). The method of the form is set to ‘POST’, which means: once the user presses the submit button, all form data is stored into the $_POST array and sent to the target page ( as set in the action parameter of the form tag ). In this example form the values of 3 fields will be stored inside the $_POST array like this:
$_POST[‘username’] = “ ... “; $_POST[‘password’] = “ ... “; $_POST[‘submit’] = “Login!”;
Where … would be replaced by the user filled in values.
How to check whether a form was submitted
We know that once a form is submitted the $_POST array is created containing all form data. Therefore we can just check whether the $_POST array is set to define whether the form was submitted.
<?php
if(isset($_POST) AND !empty($_POST)) { //if the $_POST array is set and not empty
//... form was submitted ...
}else{
//... form isn’t submitted yet ...
}
?>
Note: If multiple forms can be submitted at one page, you could identify the submitted form by checking
for example the POST variable for the submit button of that form.
Example of usage
<?php
if(isset($_POST) AND !empty($_POST)) { //if the $_POST array is set and not empty
//... form was submitted ...
// -> show filled in form values
echo “<p><b>Username:</b> “.$_POST[‘username’].” </p>”;
echo “<p><b>Password:</b> “.$_POST[‘password’].” </p>”;
}else{
//... form isn’t submitted yet ...
// -> show form
?>
<form method=”POST” action=”<?=$_SERVER[‘PHP_SELF’];?>”>
<input type=’text’ name=’username’>
<input type=’tetx’ name=’password’>
<input type=’submit’ name=’submitBut’ value=’Login!’>
</form>
<?php
}
?>