Risks of using PHP eval for string math - php

I have a question about eval() secourity risks
This is my own code
<?php
$str = 'nabi<'.$_GET['hackme']; // $_GET['hackme']=2;
$str = str_replace("nabi", 1, $str);
$hmm = eval('return ('.$str.');');
if($hmm){
echo 'yeah';
}
else{
echo 'no';
}
Result is will be:
yeah
My code workes well
It's what i want!
But i am afraid of the security risks!
Please offer a new solution

If all you're doing is checking if something is less than 1, typecast $_GET['hackme'] to int or double.
$str = 'nabi<' . (int) $_GET['hackme'];

There is zero security... Every code passed to hackme will be executed.

Related

Is there any difference in performance between assigning a long string to a variable and subsequently appending smaller strings to a variable?

As the title says, is there a difference in performance between:
$var = "Very long string to add";
and
$var = "Appending";
$var.= "subsequentially";
$var.= "short";
$var.= "strings";
I like to use the second method becouse i can keep the code more clean, but I'm worried multiple assignments could affect performance, is it something worth worrying about?
Is there a way to test it maybe?
Yes, there is a way to measure it ... see this function ... but hard to say how much precise this would be.
Test example is below.
<?php
$s1 = microtime(true);
$var1 = "Very long string to add";
$e1 = microtime(true);
$s2 = microtime(true);
$var2 = "Appending";
$var2.= "subsequentially";
$var2.= "short";
$var2.= "strings";
$e2 = microtime(true);
echo 'Big string: ' . number_format($e1 - $s1, 9, '.', '') . 's';
echo PHP_EOL;
echo 'Appended: ' . number_format($e2 - $s2, 9, '.', '') . 's';
Tests looked mostly like this:
Big string: 0.000001907s
Appended: 0.000002146s
Big string: 0.000000954s
Appended: 0.000003099s
Big string: 0.000000954s
Appended: 0.000002146s
Both solutions take up max 1 or 2 micro-seconds, so, ... yes, the appending technique is a little more performance-costly, but not so significantly that you should care :) ...
... unless you count every micro-second, then i would recommend you a language other than PHP.

Use my php variable as a formula to calculate something

I'm working in an invoice system, that has to calculate different formulas for every product, which will need to be filled with Width, Height, and Material cost.
I did a database where i'm storing
t_title -> "Curtain 1"
t_formula -> "({ANCHO}*{ALTURA})*{PRECIO}"
and then php does this:
<?php
$ancho = str_replace("{ANCHO}", $_POST['ancho'], $articulo['t_formula']);
$alto = str_replace("{ALTURA}", $_POST['alto'], $ancho);
$precio = str_replace("{PRECIO}", $_POST['precio'], $alto);
$total = $precio; echo eval($total);
?>
and the result is not giving anything, but a blank space.
How can i make it to work? I know that php can't calculate from variables as php but, i can't find another way to do it.
The eval() function expects the string parameter to be a proper code statement.
$str = '(10*10) * 1000';
echo eval($str);
will give you an error, because php cannot evaluate that string. However,
$str = 'return (10*10) * 1000;';
echo eval($str);
will evaluate the expression correctly.
You should use:
$total = 'return ' . $precio . ';';
echo eval($total);
Your using eval is wrong. The string passed to eval must be valid PHP code. i.e:
$precio2 = '$total = '.$precio.';';
eval($precio2);
echo $total;
http://php.net/manual/en/function.eval.php

Change from string to variable

Hi Guys , just need a tiny help here . the green numbers on the right are strings . how do I change them to numbers ? Additionally I also need them to be 2 decimal place. What function do I use?? I tried the method below but the output was 0. Answers all welcome.
$profitText = $profitText*1;
$profitText = (float)$profitText;
round($profitText,2);
number_format($profitText, 2);
EDITED
Okay guys the deriving of this variable is really complex. every step has its functional purpose but heres the derivation. After the last profitText at the bottom, I realised this is now a string. why is that so? and how do I fix it?
$offeropen=$row['offerprice'];//1.3334
$pips=$offerpricepl-$offeropen;//difference btw prices , eg. 0.0023
$closedb=$offerpricepl;// nothing
$pips1=round($pips, 6);// round to 6 decimal points
$pips2 = str_replace('.', '', $pips1);// remove decimal
if ($pips2<0)
{
$pips2 = str_replace('-', '', $pips2);// methodology for adjusting figures and negative values back
$pips2 = ltrim($pips2, '0');
$pips2 = -1 * abs($pips2);
}
else {
$pips2 = ltrim($pips2, '0');// for triming 0 on the left
}
$pips3=$pips2/$minipipskiller;// methodology
$ticksize= "0.0001";// FOR PROFIT AND LOSS
$lot1 = "100000";
$sizecalc=$row['size'] * $lot1;
if ($row['type']=="buy")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
if ($row['type']=="sell")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
$zero= '0';
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$profitText=ltrim($profitText,'0');
Here's your problem:
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
You're trying to turn $profitText into a number. It's actually a string of HTML, and PHP can't manage to work out what it's supposed to do with it, so when you cast it to a number, it's returning 0.
Solution:
Use $profitandloss instead
this will do both requested points together:
$floatProfitVar = number_format($profit, 2, '.');
I think you need
floatval(mixed var)
http://www.php.net/manual/en/function.floatval.php
$profit = round(floatval(trim($profitText)), 2);
Proof: http://codepad.org/jFTqhUIk
The function you're looking for is sprintf or printf and has been designed for exactly that job:
printf('%.2F', '1.8'); # prints "1.80"
Demo: https://eval.in/44078
You can use string input for the float number parameter (F = float, locale independent) as well as integer or float input. PHP is loosely typed.
Use sprintf if you want to get back a string, printf prints directly.
$value = intval(floatval($profitText)*100)/100.0
I don't think this $profitText = $profitText*1; would work unless you first do $profitText = (float)$profitText;. Remember that you have to convert the string first before you can do any manipulation.
floatval(mixed $var) can also be used instead of typecasting but typecasting should work fine

Php set value as a number

How do I output a value as a number in php? I suspect I have a php value but it is outputting as text and not as a number.
Thanks
Here is the code - Updated for David from question below
<?php
if (preg_match('/\-(\d+)\.asp$/', $pagename1, $a))
{
$pageNumber = $a[1];}
else
{ // failed to match number from URL}
}
?>
If I call it in: This code it does not seem to work.
$maxRows_rs_datareviews = 10;
$pageNum_rs_datareviews = $pagename1; <<<<<------ This is where I want to use it.
if (isset($_GET['pageNum_rs_datareviews'])) {
$pageNum_rs_datareviews = $_GET['pageNum_rs_datareviews'];
}
If I make page name a static number like 3 the code works, if I use $pagename1 it does not, this gives me the idea $pagename1 is not seen as a number?
My stupidity!!!! - I used $pagename1 instead of pageNumber
What kind of number? An integer, decimal, float, something else?
Probably the easiest method is to use printf(), eg
printf('The number %d is an integer', $number);
printf('The number %0.2f has two decimal places', $number);
This might be blindingly obvious but it looks like you want to use
$pageNum_rs_datareviews = $pageNumber;
and not
$pageNum_rs_datareviews = $pagename1;
echo (int)$number; // integer 123
echo (float)$number; // float 123.45
would be the easiest
I prefer to use number_format:
echo number_format(56.30124355436,2).'%'; // 56.30%
echo number_format(56.30124355436,0).'%'; // 56%
$num = 5;
echo $num;
Any output is text, since it's output. It doesn't matter what the type of what you're outputting is, since the human eye will see it as text. It's how you actually treat is in the code is what matters.
Converting (casting) a string to a number is different. You can do stuff like:
$num = (int) $string;
$num = intval($string);
Googling php string to number should give you a beautiful array of choices.
Edit: To scrape a number from something, you can use preg_match('/\d+/', $string, $number). $number will now contain all numbers in $string.

Just a question about str_replace

I have a question about str_replace in PHP. When I do:
$latdir = $latrichting.$Lat;
If (preg_match("/N /", $latdir)) {
$Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
$Latcoorl = str_replace ("S ", "-",$latdir);
}
print_r($latdir);
print_r($Latcoorl);
print_r($latdir); gives :N52.2702777778
but print_r ($Latcoorl); gives :N52.270277777800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Yes, it adds a lot of zeros. Can someone explane this behavior just for the fun of it?
print_r ($latrichting);
give's: N
print_r ($Lat);
This give's the weird long number.
So its probably not the str_replace command, you think ?
$latmin2 = bcdiv($latsec, 60, 20);
$latmin_total = $latmin + $latmin2;
$lat = bcdiv($latmin_total, 60, 20);
$latdir = array("N" => 1, "S" => -1);
$latcoorl = $latdir * $latdir[$latrichting];
Happy New Year.
Your string replace search string has a space before the 'N' while the dumped value looks like it's N:
Not sure what it has to do with all the zeros though.
On my system this code fragment:
<?php
$latdir = ':N52.2702777778';
If (preg_match("/N /", $latdir)) {
$Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
$Latcoorl = str_replace ("S ", "-",$latdir);
}
print_r($latdir);
print_r($Latcoorl);
?>
gives the following result:
:N52.2702777778:N52.2702777778
My best guess is you have something after this code that prints out a serie of 0.
How I would do it; just a variation of Anthony's original answer that keeps everything as numeric and doesn't lapse into string mode.
$Latcoorl = ($latrichting == "N") ? ($Lat) : (-1 * $Lat);
The string operations you did won't generate any 0s.
The 0s have to come from $lat. What did you do with $lat? any division by pi? PHP will try to store the most accurate possible float number in $lat. That's not really a problem, its a correct behavior. Just truncate the number when displayed, or round it up.

Categories