You are here
Home > Web Development > PHP Development > How to use both PHP GET and POST in the Same Page ?

How to use both PHP GET and POST in the Same Page ?

Both GET and POST Method present in different Places in the server’s memory, so they can be call on the same page if any one want. One use might be to display different messages on a form depending on what’s in the query string.

http://www.yoursite.com/conatct_form.php?

<?php
if(isset($_POST[‘submit’]) {
if($_GET[‘lang’] == “english”) {
echo(“First Name: ” . $_POST[‘firstname’] . “<br />\n”);
echo(“Last Lame: ” . $_POST[‘lastname’] . “<br />\n”);
} else if($_GET[‘lang’] == “Hindi”) {
echo(“Nikhil: ” . $_POST[‘firstname’] . “<br />\n”);
echo(“Tomar: ” . $_POST[‘lastname’] . “<br />\n”);
}
?>
<form method=”post”>
<p>First name: <input type=”text” name=”firstname” /></p>
<p>Last name: <input type=”text” name=”firstname” /></p>
<input type=”submit” name=”submit” value=”Submit” />
</form>

Instead of using GET and POST arrays, you can also use the $_REQUEST array, which will contain the combined contents of the data. If GET and POST variables have the same name, POST will take priority. It’s recommended not to do this unless you really have to, because it can be confusing, and it’s best to be clear about where an input is coming from.

One more thing to notice: the “action” on the form is now missing. Technically, this is not valid HTML. However, by not putting in an action, browsers will assume that the form is submitting to itself. This is important because it will also preserve the querystring when the form is submitted (the ?lang=english part). You can use server variables like $_SERVER[‘PHP_SELF’] and $_SERVER[‘QUERY_STRING’] to build an action value.

If you are using a version of PHP earlier than 4.2.0, you should strongly consider setting register_globals to “off” in your .htaccess file (if you are using Apache server) for the exact same reasons as were mentioned in the previous tutorial on GET. If you have PHP 4.2.0 or later, don’t worry about it.

Leave a Reply

Top