PHP: Using GET and POST Form Data Together

Thursday, March 12, 2009

You can use GET and POST both at the same time because they are both passed in separately, even having the same variable names in both cases. The most common practice of this is to pass some configuration variables to your script via GET, while allowing user input to come as a POST.

This can be especially useful in some situations because GET parameters are saved in bookmarks, and POST parameters are not. Therefore you can place a few items in the GET string that will affect whether someone makes a bookmark, giving you the information you need to display the page properly. The following script demonstrate how we can use the GET string to indicate that the page has been posted but send the user's data via a POST. This way if someone bookmarks the "posted" page, the user will be presented a custom error if he returns to the page.

<?php
if (isset($_GET['state']) && ($_GET['state'] == 'save')) {
    if (count($_POST) == 0) {
        die("ERROR:  This page has been improperly accessed.");
    }
    echo "You claim to live in state: {$_POST['state']}\n";
    echo "The script in is the '{$_GET['state']}' state.\n";
}
?>
<form action="<?= $_SERVER['PHP_SELF'] ?>?state=save" method="post" name="f1">
In what state do you live? <input name="state" type="text" />
<input type="submit" />
</form>


Hope it helps.

0 comments: