tags:

views:

231

answers:

3

Let's say I have a page called display.php and the user is viewing display.php?page=3. I want to allow the user to do an action like voting via a POST request and then bring them back to the page they were on. So, If I do a POST request to display.php?page=3 would the page information also be available to the script?

+1  A: 

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

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

It sounds like you are looking for "Redirect after Post", I would suggest separating display.php and vote.php into separate files. 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

Note that blindly accepting unsanitized form data can be hazardous to your app.

Edit: Some folks consider it bad form to use $_REQUEST to handle both cases. The hazard is that you may want to signal an error if you receive a GET when you expect a POST. Typically GET is reserved for viewing and POST is reserved for making changes (create/update/delete operations). Whether this is really a problem depends on your application.

allclaws
I was thinking about the second option but I'd still like to know if the GET array will be populated despite making a POST request.
Eugene M
Anything making changes really should have a CSRF-prevention token as a parameter, so you really don't have to worry too much about someone using a GET (e.g., by getting someone to click a link) to do something nefarious.
derobert
+2  A: 

The simple answer is 'yes'. You can use a GET-style URL as the submission URL for a POST form. PHP will have both the POST and GET information available to it in the usual ways when the form is submitted.

This is not to say that you should do this, but it will work.

Mark Hatton
+1  A: 

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

<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>
mcrumley