PHP: How to distinguish values in $_POST or $_GET that are sent via HTTP requests and those that are set / assigned in the code

by Yang Yang on March 4, 2010

html form codeTo send parameters to a PHP script, you can either fabricate a form and post a few variables by the POST method or simply send a request of a URL full of GET value pairs. This way, in the server side PHP script code, you can retrieve these parameters sent from the client in $_POST or $_GET. The trick is, other than receiving the values from client requests, you can manually assign values to them in your code. For example,

$_POST['test'] = 100;

Wherein $_POST['test'] can be used in any way possible as you can with one that is received from a HTTP request. But how can we know the posted ones from the assigned ones? The PHP function filter_has_var() is the answer. To check if a posted variable is really posted from a client request:

if (filter_has_var(INPUT_POST, 'test')) {
	// $_POST['test'] is posted from the client
} else {
	// $_POST['test'] is assigned locally

The same rule applies to $_GET. To make sure if a $_GET value is received by URL request:

if (filter_has_var(INPUT_GET, 'test')) {
	// $_GET['test'] is posted from the client by query strings in the URL
} else {
	// $_GET['test'] is assigned locally
kanna April 2, 2010 at 11:08 am

I have no idea how this could be useful?

Codez December 19, 2011 at 9:55 am

really useful if your checking a get or post from a form to validate the post or get was only used on the form on your page, other wise people can inject your site through your url bar.

Comments on this entry are closed.

Previous post:

Next post: