Thursday, February 12, 2009

Understanding the difference between post and get

Let me explain with an example

<form name="form1" action="test.php" method="GET">
<input type="textbox" name="username">
<input type="textbox" name="useraddress">
</form>

Here in the form we have method="GET". Thus when the form is submitted the URL will be shown as
test.php?username=rajesh&useraddress=testing123

Each line after the basic URL begins with the name attribute of one of the form elements,
followed by an equal sign and the contents of the input fields. URLs cannot
contain spaces or certain characters (such as my smiley), so the browser encodes
them as hexadecimal values, a process known as URL encoding.

The first name attribute is preceded by a question mark (?) and the others by an
ampersand (&). You’ll see this type of URL when using search engines, which helps
explain why everything after the question mark is known as a query string.

Now when you use the same form with method="POST"

<form name="form1" action="test.php" method="POST">
<input type="textbox" name="username">
<input type="textbox" name="useraddress">
</form>

Here nothing can be shown in the URL except the php page test.php.So no global variables are shown in the URL.If you want to test the POST values use the below code

<pre>
<?php if ($_POST) {print_r($_POST);} ?>
</pre>

This displays the contents of the $_POST superglobal array if any post data has
been sent.

When you click the Refresh button in your browser. You will probably see a warning similar to the following. This tells you that the data will be resent, which is exactly what you want. Click OK or Send depending on your browser.

Simply in one word we can say "get method sends your data in a very exposed way, making it vulnerable to alteration. Also, some browsers limit the maximum length of a URL, so it can be used only for small amounts of data."

About the post in one word "The post method is more secure and can be used for much larger amounts of data".

By default, PHP permits up to 8MB of post data, although hosting companies may set a smaller limit.

Because of these advantages, you should normally use the post method with forms. The get method is used mainly in conjunction with database searches, and has the advantage that you can bookmark a search result because all the data is in the URL.

0 comments:

Post a Comment