KRB
KRB

Reputation: 5175

Can I assign a value to a $_POST variable in PHP?

For example, I am using a $_POST variable to insert data into a DB. Just before this query I have a few tests and if they are true I want to adjust that (hidden) $_POST value.

Ex.

if($baby_dragon_eats_children){
  $_POST['hidden_value'] = "grapes";
}

Can $_POST['hidden_value'] be assigned a new value and then be passed to another function as $_POST and be able to access the new $_POST['hidden_value']?

Thanks


$_POST['consolidate_answers']

Upvotes: 15

Views: 27526

Answers (4)

Michael Berkowski
Michael Berkowski

Reputation: 270609

You can assign values to $_POST, but if you do so you should document it very clearly with comments both at the point of assignment and the later point of access. Manually manipulating $_POST can break future programmers' (including your own) expectations of what is in the superglobal and where it came from.

There may be other alternatives, like:

$my_post = $_POST;
$my_post['hidden_value'] = 12345;

// In a function:
function func() {
   // Emulate a superglobal
   echo $GLOBALS['mypost']['hidden_value'];
}

Upvotes: 25

Yam Marcovic
Yam Marcovic

Reputation: 8141

Find an alternative!

The $_POST variable has a distinct responsibility. Do not abuse its globalism.

I'd say don't abuse globalism either way, even if it means changing the design you have (or have in mind).

But if you choose not to, then consider creating a dedicated global registry just for your needs. Don't manipulate language built-ins.

Upvotes: 1

Pekka
Pekka

Reputation: 449385

Can $_POST['hidden_value'] be assigned a new value and then be passed to another function as $_POST and be able to access the new $_POST['hidden_value']?

It can in normal PHP.

However, extensions like the Suhosin Patch may block this.

Also, it feels wrong in general. $_POST is intended to contain the raw, incoming POST data - nothing else. It should not be modified IMO.

A better way to go would be to fetch all the data you plan to insert into the database into an array, and do the manipulations in that array instead.

Upvotes: 11

DaveRandom
DaveRandom

Reputation: 88647

You can, it will work, but don't.

Create a copy of $_POST, perform your tests on that and modify that instead. For example.

$postdata = $_POST;
if ($postdata['somevalue'] != 'someothervalue') $postdata['newvalue'] = 'anothervalue';
// ...

If you manipulate variables auto-created by PHP, it will probably come back to haunt you later on when the variable doesn't hold the data you expect it to.

Upvotes: 5

Related Questions