Monday, June 20, 2011

PHP $_REQUEST: why or why not

Many PHP developers hold this as a rule: avoid using $_REQUEST and always use $_POST or $_GET. If you ask why, the answer may be 'it is not secure'. Why using $_REQUEST is not secure? Well, i believe you can NOT find a strong proof. You may bring up Cross-Site Request Forgeries (CSRF), but that is not $_REQUEST's fault. Even you use $_GET or $_POST, you still may suffer CSRF, easily.

Another reason might be that in your system, you have this very bad practice: http://hengrui-li.blogspot.com/2011/06/php-get-post-precedence.html, which you should not.

A more decent reason is, prior to PHP5.3, COOKIE data is also populated into $_REQUEST, and takes the higher priority than GET and POST(Open php.ini, you can find variables_order = "GPCS", read the document and you will know more). In PHP5.3, this issue has gone. COOKIE data will not get populated in $_REQUEST by default. Prior to PHP5.3, you can change php.ini if you have control on your server. If you don't? Well, talk about this situation later.

So, what is the benefit of using $_REQUEST? The truth is, in most cases, we don't care if the data is submitted via GET or POST. By using $_REQUEST, we gain so much flexibility on both client side and server side. For example, if we are developing an API, we define this API accepts several parameters, and return the result in certain format. We don't really want to restrict the users that they can only call this API via POST. That is all up to the user. As long as a user submits the correct data, the API should work as expected. It also helps in debugging and testing by allowing both POST and GET. We can easily simulate an API request with test data.

Ok, back to the question. What if we are in PHP5.2 and cannot change server settings and we still want to gain the flexibility? Well, simply do this: $params = array_merge($_GET, $_POST);

No comments: