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. There are just a couple of caveats.
- 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).
- 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. (But is it even possible to have both $_GET and $_POST in one request?)
14. April, 2010 at 14:06
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 …
14. April, 2010 at 23:13
Interesting! I didn’t know that.