PHP: The GETPOST trick

With PHP, you often want to process input from forms.  Sometimes GET forms are appropriate, sometimes POST.  But which of those you use is a decision for the input side; when you’re processing the form information, do you really care if it’s from GET or POST?  I’ve found that, while I sometimes want to have the same page accept either GET or POST, I never care which it is.  (If it matters, I include some other parameter to show which action the user is performing.)

Therefore, it would be nice if there were a way to treat the input as “just an array” without caring if it’s GET or POST.  Fortunately, there is a way, a simple one at that.

$getpost = array_merge((array) $_GET, (array) $_POST);

This will create an array, $getpost, that contains every key and value from both $_GET and $_POST.  It will work even if the arrays are null (assuming you’re running a recent version of PHP, that is, PHP 5).  Now you can use $getpost to access your submitted form elements without worrying which type of request it was.  Also, the array_merge will not affect the original $_GET or $_POST arrays, so you can still access them if you which.

There are just a couple of caveats:

  1. If your keys are numeric, they may get renumbered.  I don’t know if it’s even possible to have form elements with numeric names (and even if it’s possible, it’s not a good idea).
  2. If both $_GET and $_POST each have a key with the same name, the latter ($_POST in this case) will be used and the former will be forgotten.  (As KimikoMuffin points out in the comments, it is possible to have both GET and POST in the same request.)

2 Responses to

  1. Gravatar KimikoMuffin says:

    Yes, for the record, it is possible to have both $_GET and $_POST in one request. I do it in my site’s system all the time — $_POST for the content of a comment on an article or login details, and $_GET for i.e. what page you’re doing it on. Having both $_GET and $_POST is entirely on the designer, and therefore, any conflict between the two is entirely their fault …

  2. Gravatar JohnEvans says:

    Interesting! I didn’t know that.

Leave a Reply »

You must be logged in to post a comment » login.