Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

post

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']

  • IF you assign a value to $_POST you should document is very clearly as it is not common nor considered "best" practice.
  • IF you have any extensions of PHP such as Suhosin Patch... it may block such actions..
  • Handle your own arrays, don't depend on $_POST!
  • IF need be, make a copy of $_POST and work with that.
like image 802
KRB Avatar asked Sep 15 '11 15:09

KRB


People also ask

How do you assign a value of a variable to another variable in PHP?

PHP (from PHP4) offers another way to assign values to variables: assign by reference. This means that the new variable simply points the original variable. Changes to the new variable affect the original, and vice a verse.

What does $_ POST do in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.

What is the difference between $post and $_ POST?

$_POST is a superglobal whereas $POST appears to be somebody forgetting the underscore. It could also be a standard variable but more than likely it's a mistake.


2 Answers

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'];
}
like image 108
Michael Berkowski Avatar answered Oct 14 '22 09:10

Michael Berkowski


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.

like image 28
Pekka Avatar answered Oct 14 '22 09:10

Pekka