Return string/int from evaluated php code? - php

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.

Related

PHP functions: passing variables by reference (and if not possible) by value

I am trying to build an "escape" function (as an exercise). The objective of this function is to transform "dangerous" values into safe values to be inserted in a database. The content of this function is not important.
function escape(&$value){
//some code
return $value;
}
Here's the problem: I want to make this function very handy to use, therefore it should be able to support 2 possible scenarios:
1) returning a safe value:
$safe_val = escape($unsafe_val);
2) changing a variable "by reference":
escape($value);
At the moment, my function does its job, however...if I pass something like:
$safe_val = escape(php_native_change_string_to_something($value));
PHP gets angry and says:
Notice: Only variables should be passed by reference
How can I make PHP accept that if something can't be passed by reference it does not matter and it should just ignore the error and continue the execution?
PHP is complaining because the value being passed into escape by escape(php_native_change_string_to_something($value)) is a temporary value (rvalue). The argument has no permanent memory address so it does not make sense to modify the value.
However, despite this not making sense, PHP will still do what you want. You are receiving a notice, not an error. Your code should still produce the output you are expecting. This short program models your setup:
<?php
function escape (&$s) {
return $s;
}
$s = 'TEXT TO ESCAPE';
$new_s = escape( strtolower( $s ) );
echo "$s\n";
echo "$new_s\n";
and produces the following results:
s: TEXT TO ESCAPE
new_s: text to escape
If you would like to get rid of the notice you will need to use the error control operator (#), #escape(php_native_change_string_to_something($value)).
Despite this being something that will work in PHP I would suggest avoiding this type of usage as it will decrease code readability and is not suggested by PHP (as the notice indicates).

Storing value got from function eval in php variable

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"

Evaluate mathematical operations inside a string using PHP

I want to evaluate a mathematical operations inside the string after I get it in that string.
Here is the string
$string = "Add this two numbers [4+2+2]. And [5*3/2] will result to?"
I already get those numbers:
$f_number = "4+2+2";
$s_number = "5*3/2";
How can I evaluate this automatically using any function?
Sample:
echo anyfunction($f_number);//will result to 8
echo anyfunction($s_number);//will result to 7.5
because if I will echo directly it will just output like this:
echo $f_number;//will result to 4+2+2
echo a$s_number;//will result to 5*3/2
You can use eval. It's probably the easiest way out. Mind though that it can also be used for other expressions, because it basically executes any PHP code that is in the string.
But by wrapping it in a function, like you intended, you can at least black box it, and add safety measures later if you need to, or even switch to a different expression evaluator, without having to change all your code.
A simple safety measure would be to check if the string only contains numeric values, whitespace and allowed operators. That way it should be impossible to secretly inject actual code.
function anyfunction($expr)
{
// Optional: check if $expr contains only numerics and operators
// actual evaluation. The code in $expre should contain a return
// statement if you want it to return something.
return eval("return $expr;");
}
echo anyfunction($f_number);

Apply XOR operator in a lambda function

My issue is a bit haywire, I must admit before I carry on. So please do not ask me why I need this. Here goes:
Suppose I have an anonymous function of this sort:
$_ = function(){return true;};
What I aim to achieve is to alter the syntax using the XOR operator as follows:
$_ = ("&"^"#").('*'^'_').("."^"#").('<'^'_').("+"^"_").("#"^")").("/"^"#").("."^"#").(){return true;};
This is met as invalid syntax by PHP. Same goes if I try to append the value of the string 'function' to a variable and then use it as shown below:
$__ = ("&"^"#").('*'^'_').("."^"#").('<'^'_').("+"^"_").("#"^")").("/"^"#").("."^"#")
$_ = $__(){return true;}
Therefore, my question is how could I possibly approach this case and use a XORed value of the keyword 'function'. I know it is possible but fail to perceive how it's being realised.
Thank you in advance for any solutions/guidelines/answers!
Unfortunately for you, PHP doesn't allow you to use a calculated value as a keyword. To over-simplify, PHP has three stages: lexing, parsing, and execution. Keywords are used during the parsing process, and your XORs are calculated during execution. To use your calculated value as a keyword, you'd have to redo the parsing process.
Fortunately for you, in PHP, that's possible using eval, although it has to be a whole new piece of code rather than, say, a single function token. eval needs a whole chunk of code, so you'll need to assemble the whole thing into a string:
$myKeyword = 'function'; // XORs don't matter; the problem is it's calculated
$code = '$myResult = ' . $myKeyword . '() { return true; };';
Then you can pass that to eval:
eval($code); // you could, of course, bypass the intermediate $code variable
Your function is now in $myResult:
$myResult(); // => true
Of course, you'd never want to use this in code you intend to be readable, but I'm almost certain you're just trying to obfuscate your code, in which case readability is intended to be poor.

Is it possible to print php variable withing a variable?

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.

Categories