I need help figuring out the syntax for the eval function - or even if eval is the right approach. I have a column in my mysql database which holds the name of a PHP function I need to run. There are also PHP variables that would like to leave as variable until they are passed to the function. Below is what I have so far:
eval($valRec[$key]($key,$value));
$valRec is the array which contains the results of a mysql SELECT. $key is a variable which references the name of the column that contains the function name.
$key and $value are the PHP variables that I need to pass into the function.
In the end, I want to end up with:
functionName($key,$value);
which PHP should run.
Hopefully I explained it clearly - thank you in advance for any help!
Eval is probably not what you want. Look at call_user_func and call_user_func_array. They let you call a function whose name is in a variable.
call_user_func($valRec[$key], $key, $value);
All you need to do is:
$valRec[$key]($key,$value);
Reference: variable functions.
In php, you could do below;
$func = 'strtolower';
$foo = $func($bar);
So in your case, $valRec[$key]($key,$value); will just work.
Check the demo.
Addtion:
The reason why your eval not work is because eval need to take a string as parameter, not don't forget ; to end the statement, or it will be syntax error.
So you need to do:
eval($valRec[$key].'($key, $value);');
I haven't used PHP recently, but the concept of eval is to evaluate a string.
As such, you need to create the string representing the line of code you want run.
In your case that means:
eval($valRec[$key] . '($key, $value);');
You've said it yourself, you want to end up with functionName($key,$value); so you need to make a string that is that, then pass it to eval.
see this example,
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
this is the output
This is a $string with my $name in it.
This is a cup with my coffee in it.
you need to read this, when is eval evil in php?
Related
eval("echo {$row11['incentive']};");
In my table column named incentive , I have values stored like a string for eg. '($workshop_sales*0.005)' and there are mutliple kind of formula stored for calculation of incentive.
I have result generated using above code in php but when I am going to store its value in any variable then it is not getting stored.
How can I store its result? is it possible or not ??
Instead of echoing inside the eval-ed code, return the value:
<?php
$workshop_sales = rand(1000, 9999);
$row11['incentive'] = '($workshop_sales*0.005)';
$result = eval("return {$row11['incentive']};");
var_dump($result);
From the docs:
eval() returns NULL unless return is called in the evaluated code, ...
And obvious eval is dangerous-statement (also from the docs):
Caution The eval() language construct is very dangerous because it
allows execution of arbitrary PHP code. Its use thus is discouraged.
If you have carefully verified that there is no other option than to
use this construct, pay special attention not to pass any user
provided data into it without properly validating it beforehand.
simply you can assign the variable to the new value inside the eval function
and use your variable later
for example :
eval('$result = "2";');
echo $result;
this will print out the value of the $result variable
PS,
you have to take a look at what #yoshi had mentioned about the dangerous of using eval
Assumption:
$workshop_sales = 15;
$row11['incentive'] = '($workshop_sales*0.005)';
Variant 1 Saving result directly (unsecure):
$foo = eval("return {$row11['incentive']};");
echo $foo; //Outputs 0.075
Variant 2 Replace variable before (should be pretty secure)
function do_maths($expression) {
eval('$o = ' . preg_replace('/[^0-9\+\-\*\/\(\)\.]/', '', $expression) . ';');
return $o;
}
//Replace Variable with value before
$pure = str_replace("\$workshop_sales", $workshop_sales, $row11['incentive']);
//$pure is now (15*0.005)
//Interpret $pure
$foo = do_maths($pure);
echo $foo; // Outputs 0.075
But be careful with eval(), it is evil.
Further information on When is eval evil in php?
The main problems with eval() are:
Potential unsafe input. Passing an untrusted parameter is a way to fail. It is often not a trivial task to make sure that a parameter (or part of it) is fully trusted.
Trickiness. Using eval() makes code clever, therefore more difficult to follow. To quote Brian Kernighan "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it"
I've read through multiple tutorials on regex and it's associated functions but I am stumped on this one.
I have a really simple replace that looks for a specific delimiter and parses the name of a PHP variable. Here it is:
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $this->file));
I keep getting errors about php not liking the #1 in ${$1}. Fair enough, can't start a variable name with a number, I knew that...
So I tried:
var_dump(preg_replace('/{{\$(.*?)}}/', ${'$1'}, $this->file));
Same thing.
Yet if I try:
var_dump(preg_replace('/{{\$(.*?)}}/', '$1 yo', $this->file));
It works...
So, how do I get php to echo a variable named whatever $1 is.
For example:
$hola = yo;
$string = hello{{$hola}}hello{{$hola}};
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $string));
And the output would be:
helloyohelloyo
Spank you!
EDIT
I should also mention that I am aware that there is a standard recommendation on how to match php variables with regex, but i'd like to get it working with a regex that I fully understand first.
Like so:
$hola = 'yo';
$string = 'hello{{$hola}}hello{{$hola}}';
$result = preg_replace_callback('/\{\{\$(.*?)\}\}/', function ($matches) use ($hola) {
return ${$matches[1]};
}, $string);
var_dump($result);
preg_replace_callback calls a callback on every match.
In order to use the $hola variable inside the callback you need to explicitly make it available inside the function (use ($hola)).
All this said... I don't get it. What this code does is essentially what PHP already does out-of-the-box.
$hola = 'yo';
$string = "hello{$hola}hello{$hola}";
echo $string; // "helloyohelloyo"
I have a very simple question. But is really making me crazy.
I have a statement say:
example and example with one php variable like $loggedin_user_name
First of all, I want to store the above sentence in MySQL database and then take it back whenever I want to print the above statement. It seems that their is no issue.
But when I tried to print data after extracting from database it is printing the same statement. But i guess, it has to print the logged in user name instead of $loggedin_user_name in the above statement.
So, is it possible to print the variable within the variable? If yes, please suggest a way.
use sprintf()
$str = "example and example with one php variable like %s";
Then load it from database and fill
$out = sprintf($str, $loggedin_user_name);
If it is always the same variable name, I would suggest using
echo str_replace($fromDb, '$variableToReplace', $variableToReplace);
You can use preg_match to find you variable name in string and then replace it with str_replace.
$name = "ABC";
$bla = "$name";
echo $bla; //ABC
Will always be "ABC", because PHP is evaluating your variable when asigning to $bla.
You can use single-quotes to avoid that behaviour (like $bla='$name'; //$name) or you quote the $-sign (like $bla="\$name"; //$name). Then you can store your string like you wanted into your database.
But you can not (only when using eval(), wich you MUST NOT DO in good PHP-Code) build this behaviour, that php has, when printing fulltext.
Like Mentioned in another answer, you should use printf or sprintf and replace the $loggedin_user_name with %s (for "string).
Best would be to concatinate a string:
$exampleWithUsername = 'example' . $loggedin_user_name;
echo $exampleWithUsername;
'example' is a hardcoded string, but you can give it a variable containing string $example, or directly concatinate $username into $example.
You can use eval function, it can be used like your example:
$loggedin_user_name = 'bilal';
$str = "example and example with one php variable like $loggedin_user_name";
eval("\$str = \"$str\";");
echo $str;
Cons:
If your str variable or string/code which you give to eval as a parameter is filled by users, this usage creates a vulnerability.
In case of a fatal error in the evaluated code, the whole script exits.
This is annoying me. In theory it should be easy but I don't live in theory.
Basically, I have an option to set a custom algorithm to make a 'code' that is either string or int.
This is user generated, and I then call that.
I have attempted to execute it using this code:
$code = eval('return($custalg);');
but that returns the actual algorithm entered, and not the value it would produce.
So my question is, how would I manage to execute the string in $custalg as php and then save the result into a variable?
It looks you are not aware of difference between single quoted ' and double quoted " strings in PHP. You should use:
$code = eval("return($custalg);");
if you want $custalog to be expanded:
The most important feature of double-quoted strings is the fact that
variable names will be expanded. See string parsing for details.
See more in docs.
So basically correct syntax depends on what $custalg is and where it is assigned. In your case I guess your $custalg is assigned in main code so you do not want substitution. Use code like this then:
$code = eval("return \$custalg;");
You can get an echoed output with using the PHP output control functions:
ob_start();
eval("echo $custalg;");
$tmp = ob_get_contents();
ob_end_clean();
$evalOutput = $tmp;
Or you just assign the return value to a global variable.
I was looking through some code for work, and came across this line:
eval("\$element = \"$element\";");
I'm really confused as to why any PHP developer would've written this line. What purpose does this serve, besides setting a variable to itself?
Luckily, the function this line is in is never called.
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
The above example will output:
This is a $string with my $name in it.
This is a cup with my coffee in it.
http://php.net/manual/en/function.eval.php
I do just ctl+c ctrl+v :-)
It converts the value of the variable to a string, but I wouldn't recommend using it.
Use the function strval() instead. Have a look at the manual.
This assigns the string-converted contents of the variable $element to a variable called $element. Another way to do this is to use strval, or in some cases print_r($x, true)
It doesn't really do much except converting the value to string or might serve as a poor alternative to sprintf. But if the variable contains double quotes, this is gonna cause some trouble. You really wouldn't want to eval a code like this:
$element = 'foo"bar';
Not to mention some even more harmful code. Seems like a place for a "php injection" :D
Don't use it.