I'm very new to php .I want to convert the string to integer value.
I used following code to convert
$val='(100*2)';
echo (int)($val); //This will showing output as 0
But echo (int)((100*2)); /This will showing output as 200
Please help me any one to solve this .Thanks advance
(int)($val) evaluates to 0 because $val's value is not a numeric string (ie one that can be directly cast to a number).
If you really need this kind of functionality, try eval():
$val='(100*2)';
echo (int)($val); //This will showing output as 0
eval('$newval='.$val.';');
echo $newval;
But be warned: eval() can be dangerous!
From http://php.net/manual/en/function.eval.php:
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.
EDIT: Added .';' to eval parameter to make it a legit php instruction.
The most common suggestion will be - evaluate your string as PHP code, like:
$val = '(100*2)';
eval('$val = '.$val.';');
-but that's unsafe, eval should be avoided as long as possible.
Alternatively, there is bcParser for PHP, which can solve such issues. That's more safe than eval.
Finally, I doubt that you really need do such things - it seems you're solving some problem with wrong method (see XY-problem description)
You can do it using php eval function.
For that first you have to check for special characters and equation characters.
$val='(100*2)';
echo matheval($val);
function matheval($equation)
{
$equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation);
// fix percentage calcul when percentage value < 10
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
// calc percentage
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
// you could use str_replace on this next line
// if you really, really want to fine-tune this equation
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
if ( $equation == "" )
{
$return = 0;
}
else
{
eval("\$return=" . $equation . ";" );
}
return $return;
}
I not recommended this, but you can use eval to suit your need
eval('$val = (100*2)');
echo intval($val);
Why not just:
$x=intval(100);// <- or an other value from the cleaned user input
$y=intval(2);
$val=$x*$y;
echo $val;
You are not giving a goal.
I can just explain why your code works like it does.
'(100*2)' is a String that cannot be converted to int, since it does contain other chars than numbers. Every String that cannot be converted will result in 0.
echo (int)(100*2) will work, because you use numbers and no strings. No need to convert, either, would work without the cast, just echo (100*2);
Remember PHP use loose typing. You will almost never need to convert types. This scenario is very set up.
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 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);
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.
The CMS I'm using has a plugin that pulls a series of pages based on how you've tagged those pages. Everything is working fine, but I need to display the number of pages returned after a user sends a query.
The variable that the number of records is stored in is a string. The small script I'm writing tries to check if this string is blank, and if so echo nothing, but if it's not blank echo the number of pages returned.
<?php
if ($count !== ''){
echo "text";
}
?>
However, whenever it's passed when the string is supposed to be empty it treats it as if it is not. I'm not sure what I'm doing wrong or what the string contains that it's not empty.
I found a resource about converting strings to integers but it set it to 0. Thanks for any help.
$count will never be equal to ' ' if you trim it before.
It cannot be equal to ' ' after trim, you should check if it is equal to an empty string and not a string with a white space. (trim deletes white spaces)
trim — Strip whitespace (or other characters) from the beginning and end of a string
http://php.net/manual/en/function.trim.php
trim removes all spaces, so $count == ' ' will always be false if you trimmed first. The easiest change to your code would be to replace the ' ' with ''. Or you could just do this: echo trim($count) === '' ? '' : "text";
trim() is going to remove all white-space characters from the beginning and end of the string. Unless there is content in the middle, you'll likely end up with a completely empty string. If you're testing for this, try checking empty() or is_null().
if (empty($string)) {
echo "String is empty.";
}
I find it's better using built-in functions instead of hard-coding a =='' comparison.
Use var_dump() to check the type and the content of the variable.
Check the manual
Your code seems wrong; you've got "!==", where I'd swear you need to have "!=" (only one equals sign). I'm not sure what "!==" would evaluate to, but I'd bet it's not what you want.
It seems from the comments that your "blank" string is not blank, but instead has something odd in it. Assuming that it's not too odd I'd just try this:
$count = intval($count);
if ($count) {
echo 'text';
}
Though this assumes that the $count actually looks like a number to intval when it's got a number in it -- we may need to take a look at this "string" you're getting back in more detail to figure out what's really in it.
Hopefully you've already taken the advice given by others and looked at the resulting page source after doing a var_dump() -- otherwise I'd guess that $count has XML in it, or something else that won't render well if you dump it to an HTML page and view the page rather than the source...
If nothing else, you could really try brute-forcing it:
$count = intval(preg_replace('/[^\d]/', '', $count));
if ($count) {
echo 'text';
}
...but really it'd be better to work out what this odd plug-in is giving you, and why. Which CMS and plugin is it? Are there some docs available for this thing that's returning $count to you? Do you have the plugin source?
I know some people may just respond "never" as long as there's user input. But suppose I have something like this:
$version = $_REQUEST['version'];
$test = 'return $version > 3;';
$success = eval($test);
This is obviously a simplified case, but is there anything that a user can input as version to get this to do something malicious? If I restrict the type of strings that $test can take on to comparing the value of certain variables to other variables, is there any way anybody can see to exploit that?
Edit
I've tried running the following script on the server and nothing happens:
<?php
$version = "exec('mkdir test') + 4";
$teststr = '$version > 3;';
$result = eval('return ' . $teststr);
var_dump($result);
?>
all I get is bool(false). No new directory is created. If I have a line that actually calls exec('mkdir test') before that, it actually does create the directory. It seems to be working correctly, in that it's just comparing a string converted to a number to another number and finding out the result is false.
Ohhhh boy!
$version = "exec('rm-rf/...') + 4"; // Return 4 so the return value is "true"
// after all, we're gentlemen!
$test = "return $version > 3";
eval($test);
:)
You would have to do at least a filter_var() or is_numeric() on the input value in this case.
By the way, the way you use eval (assigning its result to $success) doesn't work in PHP. You would have to put the assignment into the eval()ed string.
If you do this. Only accept ints.
If you must accept strings, don't.
If you still think you must. Don't!
And lastly, if you still, after that, think you need strings. JUST DON'T!
yes, anything. I would use $version = (int)$_REQUEST['version']; to validate the data.
You need to be more precise with your definitions of "malicious" or "safe". Consider for example
exec("rm -rf /");
echo "enlarge your rolex!";
while(true) echo "*";
all three snippets are "malicious" from the common sense point of view, however technically they are totally different. Protection techniques that may apply to #1, won't work with other two and vice versa.
The way to make this safe would be to ensure that $version is a number BEFORE you try to eval.
Use this code to remove everything except numbers (0-9): preg_replace('/[^0-9]+/', '', $version);