I'm currently using the following format to save a value from an HTML form $item_name=$_POST['item_name'];
This saves the value, but how to I also save the name attribute in a variable?
Thanks in advance!
Assuming you want to store each element of $_POST variable as a key-value pair, then you can try:
$var = array();
foreach($_POST as $key => $val) {
$var[$key] = $val;
}
I'm saving a lot of values and want to avoid typing each one out.
Please, make your mind first.
Global variables are intended to be typed by hand.
If you want some automated processing - just keep them in a form of array.
Looks like rdt.exe's answer is what you're looking for.
maye you noticed you have to use the name to access the $_POST-array and get the value. if you want to store the name in a variable, too, just do:
$item_name_name = 'item_name';
$item_name_value = $_POST[$item_name_name];
you could also use some kind of loop to dynamically create variables with the according names like this:
foreach( $_POST as $name => $value ){
$$name = $value;
}
both ways are some kind of unnecessary and useless in my opinion, but you havn't stated what exactly you're trying to achive - so maybe this helps.
An alternative approach:
$keysarray = array_keys ( $_POST);
print_r( $keysarray);
This will give you all the keys in array
The function you are looking for is called extract.
This will create variables for all the $key=>$val pairs in the array.
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound');
export($_EXAMPLE);
echo $bird; # prints "chicken"
echo $dog; # prints "greyhound"
Watch out though - this is a huge security risk. So are the solutions described in some of the other answers.
The problem with doing something like this is that a user can tamper with the POST data, and set parameters other than the ones she is supposed to set. If they set variables that are actually variable names in your application, those variables can be overwritten.
$is_admin = false;
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound', 'is_admin' => 'true');
export($_EXAMPLE);
if ($is_admin) { # this will now evaluate to true.
# do sensitive stuff...
}
Related
Here is a fairly big object dumped using print_r.
https://docs.google.com/document/d/175RLhWlMQcyhGR6ffGSsoJGS3RyloEqo4EEHCL2H2vg/edit?usp=sharing
I am trying to change the values of the uploaded_files.
Towards the end of that object you'll see something like
[uploaded_files] => Array
(
[attachment] => /home2/magician/public_html/development/testing/wp-content/uploads/wpcf7_uploads/Central-Coast-Montessori-logo.jpg
[attachment2] => /home2/magician/public_html/development/testing/wp-content/uploads/wpcf7_uploads/Andrew.jpg )
My code
// move the attachments to wpcf7ev temp folder
foreach ($cf7ev_object['uploaded_files'] as $key => $uploaded_file_path) {
$new_filepath = WPCF7EV_UPLOADS_DIR . '/' . basename($uploaded_file_path);
wpcf7ev_debug("New file path is {$new_filepath}");
rename($uploaded_file_path, $new_filepath);
wpcf7ev_debug("'{$key}'is the KEY for {$uploaded_file_path}");
wpcf7ev_debug($cf7ev_object['uploaded_files']);
$cf7ev_object['uploaded_files'][$key] = $new_filepath; // this is not updating
}
To loop through it I have been using
foreach ($cf7ev_object->uploaded_files as $key => $uploaded_file_path) {
and this has worked.
But shouldn't it be
foreach ($cf7ev_object['uploaded_files'] as $key => $uploaded_file_path) {
? As '->' is for accessing methods?
And specifically I want to update the values of those uploaded_files, so to do that I need to do
$cf7ev_object['uploaded_files'][$key] = $new_filepath; // this is not updating
? But this doesn't seem to be working.
I think I need to be clear on how to access values in an object.
Thanks.
First of all, regarding the single arrow "->" that is how you reference an objects values. But I won't get into that. Since you say it works, $cf7ev_object is obviously an object.
You say you want to "access the values in the object".
var_dump($cf7ev_object);
This will spit out what is in that object. I gather you are a bit of a newbie, so I will try to help you out best I can with the limited data you provided (you may want to expand your question.
Looping is not a one-shot deal. You can have nested loops and nested loops inside of those. However, it is a resource hog if you're not careful. Here is an exercise that might help you.
$new_array = array();
foreach($cf7ev_object->uploaded_files as $key => $value) {
$new_value = $value;//do something to the $value here
$new_array[$key] = $new_value;
}
//take a look at your work now:
print_r($new_array);
I hope this helps. Note: your google doc is restricted, public can't see it.. And your question is too vague. Let me know if I can help more.
If you want to change the object array values instantly you just set it equal to the above loop result:
$cf7ev_object->uploaded_files = $new_array;
In the following script function clean($data) calls it within it, that I understand but how it is cleaning data in the statement $data[clean($key)] = clean($value);??? Any help is appreciated.. I am trying to figure it out as I am new to PHP. Regards.
if (ini_get('magic_quotes_gpc')) {
function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
$data[clean($key)] = clean($value);
}
} else {
$data = stripslashes($data);
}
return $data;
}
$_GET = clean($_GET);
$_POST = clean($_POST);
$_REQUEST = clean($_REQUEST);
$_COOKIE = clean($_COOKIE);
}
Your Question:
So if I undertsand correctly you want to know what is the function doing in the line
$data[clean($key)] = clean($value);
The Answer:
See the prime purpose of the function is to remove slashes from string with php's stripslashes method.
If the input item is an array then it tries to clean the keys of the array as well as the values of the array by calling itself on the key and value.
In php arrays are like hashmaps and you can iterate over the key and value both with foreach loop like following
foreach ($data as $key => $value) {....}
So if you want to summarize the algorithm in your code snippet it would be as under
Check if the input is array. If it is not then go to step 4
For each item of array clean the key and value by calling clean method on it (Recursively)
Return the array
clean the input string using stripslashes method
5 return the cleaned input
From my understanding it's not cleaning the key but creates a new element with a clean key while the uncleaned key remains.
$a['foo\bar'] : val\ue
becomes
$a['foo\bar'] : val\ue
$a['foobar'] : value
Someone correct me if im wrong.
Maybe you'll understand the code better if it's put this way:
foreach ($data as $key => $value) {
$key = clean($key); // Clean the key, the
$value = clean($value); // Clean the value
$data[$key] = $value; // Put it in the array that will be returned
}
Assuming you have an array like this:
$_POST = array(0 => 'foo', 1 => array('bar' => 'baz'));
the following will happen:
Call clean($_POST);
call clean 0
call clean 'foo'
$return[0] = 'foo'
call clean 1
call clean 'bar'
call clean 'baz'
$return[1] = array('bar' => 'baz');
You should probably read this: http://www.codewalkers.com/c/a/Miscellaneous/Recursion-in-PHP/
The main purpose of the function is to clean an associative array or a single variable. An associative array is an array where you define keys and values for that keys; so are special arrays used in PHP like $_GET $_POST and so on.
The meaning of "cleaning" is to check whether magic quotes are active - this causes some characters in these arrays to be escaped with backslashes when you post dynamic data to a PHP page.
$_GET["Scarlett"] = "O' Hara" becomes with magic quotes $_GET["Scarlett"] = "O\' Hara"
So if magic quotes are active, the function takes care of this, and slashes are stripped so that the strings retain their correct, not escaped value.
The algorithm checks if the data passed to the function is an array, if not it cleans directly the value.
$string = "Escapes\'in\'a string";
clean($string);
is it an array? No. Then return stripslashes(my data)
$array = array("key\'with\'escapes"=>"value\'with\'escapes", "another\'key"=>"another value");
clean($array)
is it an array? Yes. So cycle through each key/value pair with foreach, take the key and clean it like the first example; then take the value and do the same and put the cleaned versions in the array.
As you see the function has two different behaviours differentiated by that "if" statement.
If you pass an array, you activate the second behaviour that in turns passes couples of strings, not arrays, triggering the first behaviour.
My thought is that this function doesn't work properly, though. Anyone got the same sensation? I have it not tested yet but it seems it's not "cleaning" the key/values in the sense of replacing them, but adds the cleaned versions along the uncleaned ones.
I have built an empty associative array whos keynames refer to submitted post data. I can capture the postdata just fine, but I run into trouble trying to instantiate variables who's names match the array key.
for example:
$insArray = array('rUsername'=>'', 'rPass'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCeckOption'=>'', 'rEmail'=>'');
foreach($insArray as $key=>$value){
if (filter_input(INPUT_POST, $key) != ''){
$key = stripslashes(filter_input(INPUT_POST, $key));
$insArray[$key] = $key;
}
}
First line creates the empty array, then the foreach loops through this array. Now it gets tricky.
filter_input(INPUT_POST, $key) captures the value located in the post data matching the current key, rUsername in this case
$key is where the problem lies. I want the NAME of the new variable to be the associative key name, for example I want to replace $key with $rUsername in the first iteration, $rPass in the second, and so on. I tried using two $$, but I know that's not right. Never tried doing this before, but it would be helpful if I could figure it out.
UPDATE:
This is the final code which was a combination of two of the answers provided.
if (isset($_POST['submit'])) {
//Build array of variables to be put into database
$insArray = array('rUsername'=>'', 'rPassword'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCheckOption'=>'', 'rEmail'=>'');
foreach(array_keys($insArray) as $key){
$insArray[$key] = filter_input(INPUT_POST, $key);
$$key = filter_input(INPUT_POST, $key);
}
}
Gave me exactly the output I wanted, thanks guys!
You're not accessing $_POST at all, so all you're doing is taking some array members you defined yourself, filtering them for harmful POST characters (why would you attempt to inject your own code?) and then creating a new array from those self-defined key values.
If I'm guessing right at what you want, it should be this:
foreach(array_keys($insArray) as $key) {
$insArray[$key] = stripslashes(filter_input(INPUT_POST, $_POST[$key]));
}
The use of stripslashes suggests that you're on a braindead version of PHP which has magic_quotes enable. You should upgrade to a modern version of PHP and/or turn them off.
The solution is change
$key = stripslashes(filter_input(INPUT_POST, $key));
to
$$key = stripslashes(filter_input(INPUT_POST, $key));
See http://www.php.net/manual/en/language.variables.variable.php
Also, recheck your code, which are doing some mistakes..
If I understand you correctly, Im going to suggest this approach:
$defaultValues = array('rUsername'=>'', 'rPass'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCeckOption'=>'', 'rEmail'=>'');
$values = array_map('stripslashes', array_merge($defaultValues, array_filter($_POST)));
extract($values, EXTR_SKIP);
echo $rUsername;
echo $rPass;
.........
By using the snippet above, you have to take into account the following
Im using the extract function with EXTR_SKIP so you dont overwrite existing variables. Make sure to only use the variables you need in your code and sanitize them appropietly.
By using array_filter on the $_POST superglobal im "erasing" all empty or null variables. so if an expected key was not sent via $_POST, it defaults to the value specified by the $defaultValues array.
I dont quite understand why you are using filter_input without the third parameter (filter constants).
Hope this will help, If not may be I have misunderstood the problem.
Instead of
$key = stripslashes(filter_input(INPUT_POST, $key));
$insArray[$key] = $key;
Try
$insArray[$key] =stripslashes(filter_input(INPUT_POST, $key));
Then after the foreach loop
extract($insArray);
I have a table with a whole bunch of fields and records in it (40+fields).
I use my MySQL result like so:
<?php
$field1 = $row['field1'];
$field2 = $row['field2'];
$field3 = $row['field3'];
?>
As you see, the variable name is the same as the field name.
How can I do this for all fields, without having to type em all out? Would be really awesome for when I add more fields!
I know about the eval function, however I am not sure of how to use it in this case.
Also, how can I generate an array with the results? Like so:
<?php
$arr = array(
'field1'=>$row['field1']
);
?>
You can use extract():
extract($row);
However, take great care you don't pollute your namespace with this function. Say you already have a variable named $car, and you have a field in your database called car. You could be unwittingly overwriting your existing variables!
It may be safer, then, to use:
extract($row, EXTR_SKIP); // don't extract variables that already exist in the namespace
EDIT: In regards to your edit, you don't need to create an array for the results... your $row array is the result. If you construct the array as in your edit, $arr['field1'] = $row['field1'], so why not bypass the construction of this array altogether and just use the original $row?
The extract() function does exactly this:
extract($row);
By default it will override any existing variable (e.g. if you already have a field1 variable, it will override it). You can disable this by passing EXTR_SKIP as second parameter:
extract($row, EXTR_SKIP);
Or you can prefix all variables:
extract($riw, EXTR_PREFIX_ALL, 'row');
Also, how can I generate an array with the results?
$arr = $row;
$post_keys = array_keys($_POST);
$special_keys = array();
for($i=0;$i<count($post_keys);$i++){
if(strpos($post_keys[$i], "special") !== false){
$special_keys[] = $post_keys[$i];
}
}
I have numerous post vars with naming conventions such as special0, special0_time, special0_duration, special1, special1_time etc.... What I want to do is to find out how many main groups there are, so special0, special1 etc... The code I currently have searches all key names that have "special" in it, thus retrieving more than I want.
PHP already builds an array for parameters that uses the array like syntax (e.g. arg[]). See How do I create arrays in a HTML <form>?
Gumbo is correct, however if you still need to perform such a task, regex can help:
if(preg_match('/^(?<key>special[0-9]+)_/ix', $post_keys[$i], $match)){
$special_keys[] = $match['key'];
}
After which you can run array_unique() on $special_keys to get an array of groups.
For easier maintenance try this structure:
$_POST = array(
'special' => array(
array('time'=>, 'duration'=>, ''=>),
array('time'=>, 'duration'=>, ''=>),
array('time'=>, 'duration'=>, ''=>),
),
);
Then you can do stuff like count($_POST['special']) and $_POST['special'][1]['time']