Matthew Ruddy
Matthew Ruddy

Reputation: 925

Eval and array index as variable

I've made a topic about trying to use an array index as a variable name previously, and received one answer that interested me here.

One of the answers suggested using eval(), although didn't recommend it due to its potential security issues.

$string = 'welcome["hello"]';
eval('$' . $string . " = 'thisworks';");

// This also works : eval("$$string = 'thisworks';");

// I could then print the array keys value like this
print( $welcome["hello"] ); // Prints 'thisworks'

However, this solution is the simplest, and is probably the most appropriate for what I want to achieve. I am actually working on a Wordpress admin panel, full of various options the user can set. Each option is set through a variable containing a multi-dimensional array, like this (only much larger):

$options = array(
 array(
  'id' => 'option_id', // The name of the input field
  'type' => 'text', // Input type
  'value' => 'some value here' // Input value
 )
);

When the user saves the options, a function fires, creating an array out of all the various input values and saving them into the database. Like below, although highly stripped down:

foreach ( $options as $o ) {
 if ( isset( $_POST[ $o[ 'id' ] ] ) ) {
  $settings[ $o[ 'id' ] ] = $_POST[ $o[ 'id' ] ];
 }
}

Some of the options from the multi-dimensions options variable, are to be saved as a part of an array, instead of a string. These options contain square brackets in their ID's, like 'option_id[value1]'.

This is where things get complicated. Currently, I am having to send the ID through a function that checks for the square brackets [], then telling the save function what to do with it appropriately (save as an array or string).

This is why the eval solution is ideal. It allows me to create a variable that's already an array and contains the index, without having to use other functions to disect the ID. It severely reduces a long winded process, or so I believe.

So in essence, is there a safer, similar way I can go about using eval, or using alternative functionality. What are the dangers of using eval in the way above? Can malicious code be executed in the context used above? Surely executing code before a $ would cause PHP errors?

Upvotes: 3

Views: 3741

Answers (1)

Kenneth Spencer
Kenneth Spencer

Reputation: 1532

Using eval in this way seems like a hack to me and is unlikely to be performant. Why not use variable variables to achieve the same thing?

$string = 'welcome';
$key = "hello";

${$string}[$key] = "this works better";
print( $welcome["hello"] ); // Prints 'this works better'

Upvotes: 3

Related Questions