Why do I have to use POST instead of GET?

2019-07-27 10:41发布

问题:

When I use <form action="code.php?id=1" method="post"></form>, the form id is passed in the URL. But when I write the same code by replacing 'POST' by 'GET', the id is not passed to the URL.

Why?

回答1:

When you submit a GET form, the values from the form are appended to the action URL, as the "query string" after the ?. Specifying an existing query string in the action attribute of such a form creates an ambiguity. Browsers don't merge the two query strings, they just throw away the old query string and build the new one based on the form.

With a POST form, there is no ambiguity: the data from the form is sent separately from the URL, so there is no need for the query string to be over-written.

However, it's probably best not to mix the two kind of parameters, so the solution is always to include your extra parameters as hidden fields, then it will work with both GET and POST forms:

<input type="hidden" name="id" value="1">


回答2:

Better way is to pass id in hidden field.

<form action="code.php" method="post">
    <input type="hidden" value="1" name="id" />
</form>


回答3:

If your form is as below

<form action="code.php?id=1" method="post">
<input typ"text" name="username" />
<input type="submit" />
</form>

example script in code.php

<?php
print_r($_GET);
print_r($_POST);
print_r($_REQUEST);
?>

You will get form data in post array and url parameters in get array, in request you will get both get and post data in one array. But if you change from post to get method your form data added with the url instead of appending. This issue is because of ambiguity. To get solution i this situation, create a hidden field in your form those you also want to send with query string.



标签: php html post get