What happens if you go to a GET url with a POST request?

Let's say I have a page called display.php

and the user is browsing display.php?page=3

. I want to allow the user to do things like vote via POST request and then return them back to the page they were on. So if I make a POST request for display.php?page=3

the page information is also available to the script?

0


source to share


3 answers


The simple answer is yes. The GET URL can be used as the submit URL for the POST form. PHP will have both POST and GET information available to it in the normal way when the form is submitted.



This does not mean you should do it, but it will work.

+2


source


In PHP, you can get request variables from special global arrays:

$_GET['page'] (for GET requests)
$_POST['page'] (for POST requests)
$_REQUEST['page'] (for either)

      

It looks like you are looking for "Redirect after Post", I would suggest to split display.php and vote.php into separate files. The vote looks something like this:



<?php
//vote.php
$page_number = (int)$_REQUEST['page'];
vote_for_page($page_number); //your voting logic
header('Location: display.php?page=' . $page_number); //return to display.php

      

Please note that blindly accepting unanimated form data can be dangerous for your application.

Edit: Some people find it bad form to use $ _REQUEST to handle both cases. The danger is that you can signal an error if you receive a GET while expecting a POST. Usually GET is reserved for viewing and POST is reserved for making changes (create / update / delete operations). Whether or not this is really a problem depends on your application.

+1


source


Yes, the GET array is always populated with URL parameters regardless of the request method. You can try this with a simple page:

<form action="test.php?a=b" method="post">
    <input name="a"/>
    <input type="submit"/>
</form>
<pre>
POST:
<?php print_r($_POST); ?>
GET:
<?php print_r($_GET); ?>
</pre>

      

+1


source







All Articles