Php change post data to variable
I am trying to change $ _POST data in variable format, here is my code:
<?php
$_POST["abc"]=2;
$post = array("abc");
foreach($post as $field) {
global $field;
$field = $_POST[$field];
}
echo $abc;
?>
but when i try to run this code i get:
PHP note: variable Undefined: abc in / var / www / on line 8
How can I change the selected POST variables in a loop to regular variables? (for example, $ _POST ["abc"] to $ abc)
source to share
You can try with a PHP variable .
<?php
$_POST["abc"]=2;
$post = array("abc");
foreach($post as $field) {
global $$field;
$$field = $_POST[$field];
}
echo $abc;
?>
source to share
If you want to get the $ _POST key as a direct conversion of variables, you can use the following script.
<?php
$_POST["abc"]=2;
$_POST["xyz"]=5;
$post = $_POST;
foreach($post as $key=>$field) {
$$key = $field;
}
echo $abc . "<br/>"; //2
echo $xyz; //5
?>
Here "$$" is used to dynamically create a variable from another line output.
A working example is available here: http://sugunan.net/demo/fof.php
source to share
My approach:
$abc = $_POST['abc'];
or
list($abc,$def,$etc) = array($_POST['abc'],$_POST['abc'],$_POST['def'],$_POST['etc']);
or
$postNeeded = array("abc","def","etc");
foreach($postNeeded as $variable){
if(isset($_POST[$variable])){
${$variable} = $_POST[$variable];
}}
etc. for every variable I need from $ _POST, your approach will make you vulnerable to code injection unless $ _POST is cleared. Over time, I ended up using just $ _POST ['var'] instead of additional variables, but of course it depends on the project. Hope my answer helps. GL.
source to share