Categories
HTTP Tips & Tutorials PHP Tips & Tutorials

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

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,

<?php
$_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
}

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.

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

@kanna
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 are closed.