Okay, so I want to know if there are any (other, and preferably easy) ways to convert a string to a variable.
My code, which works, is as follows:
echo eval('return $'. $date . ';');
$date contains a string. Now, the code works, and I'm fine with leaving it as it is if nothing else, since $date is called from a pre-programmed class declaration:
Time::Format($id = 'id', $name = 'name', $date = 'date->format(Y)');
The reason I ask is due to the PHP official disclaimer/warning on its use of: 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.
As such, I think I am safe in using it, as there is no user-inputted data being eval'd by PHP, it's a string I set as the coder, but I would like a second opinion its use, as well as any input on another simple method to do this (since, if I can avoid it, I'd rather not use a complicated and possibly long block of code to accomplish something that can be done simply (provided it is safe to do quick and dirty).
PHP's variable variables will help you out here. You can use them by prefixing the variable with another dollar sign:
$foo = "Hello, world!";
$bar = "foo";
echo $$bar; // outputs "Hello, world!"
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 have been doing some research online and it appears that the answer to my question is no, but I realize there are times when I might miss something or search for something incorrectly. I know in languages like C++, when a variable is declared it can be declared as int or string. Is it possible to force this in PHP?
For Example:
<?php
(int)$var = 5;
?>
will be validated and not cause an error in PHP, but:
<?php
$var = 5;
?>
will cause an error because it was not cast as a type string, int, object, etc...
I know PHP is loosely typed so this may not be an option, however I would like to use it that way I ensure that I sanitize data appropriately and improve readability by letting others know exactly what is going on with the code. I am hoping there is a way to enforce this in the php.ini file or to load it in a script that will always be executed by my program.
Thank you for any help you can offer!
PHP is loosely typed and does not require you to declare a variable type when declaring a variable. You can’t change that behavior with a magic php.ini directive.
The benefit of having “loose typing” is that it allows for flexibility. It allows you to create dynamic applications without having to worry about the type of the variable – PHP makes this possible by not enforcing variable types.
However, if you must convert a variable into a particular format, just cast it:
$int = (int) $foo;
$str = (string) $foo;
$bool = (bool) $foo;
$float = (float) $foo;
...
There are functions to do the same, e.g. intval(), strval(), boolval() – all of them do the same task, but a function is very useful when you want to use it as a callback to another function.
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.
Is it possible to parse the contents of a constant in PHP?
For example,
define('WHO_AM_I', 'My name is $_SESSION['who_am_i'].'); // setup the constant string
echo eval(WHO_AM_I); // something like this -- but the eval() returns an error
Please note that I do not know the value of the _SESSION var until I actually use the constant later in the script stream.
Thanks.
AMENDED WITH REASON FOR WANTING TO DO THIS
I want to pull "hard coding" out of my script and give the user the ability to configure certain taxonomy in their site. So while I was doing this I also wanted to create a quasi-dynamic constant that I thought I might be able to parse later in the script.
If it can't be done...then it can't be done.
Don't shoot me for asking the question though.
A FINAL COMMENT TO AVOID ALL THIS CONFUSION
The purpose of my question has nothing to do with the eval() function. I am actually regretting having put it in there in the first place.
I put the eval() in the question simply to demonstrate to stackoverflow members that I did a bit if prep on my question rather than asking an open ended -- hey give me a solution without having offered any stab at it myself. So please disregard the eval().
All I want to know is can I somehow craft a define() in an way that makes the assigned value parse-able later in my script. That's it, that's all.
AMENDMENT C
I know I can do the following although I don't want to do it this way:
define('PARSE_ABLE_CONSTANT_PART_A', 'My name is ');
define('PARSE_ABLE_CONSTANT_PART_B', '.');
...later down the script road...
echo PARSE_ABLE_CONSTANT_PART_A . $_SESSION['who_am_i'] . PARSE_ABLE_CONSTANT_PART_B;
I just don't want to do it this way if I can make it slicker using an embedded var in the constant.
This seems really fishy, as other users have pointed out. You could do something like this if you wanted:
define('WHO_AM_I', 'echo \'My name is \'.$_SESSION[\'who_am_i\'];');
eval(WHO_AM_I);
This will always just echo the variable. You need to eval an expression afaik.
Just read your edit. I think you would be better suited with an .ini file, or maybe a static class with static properties. Makes it much more flexible, and you avoid the eval. You are talking user-generated content from what I can see - subjecting that to an eval call seems highly insecure.
A quick example of a static class you could use:
<?php
class myConstants{
public static function _($key){
switch($key){
case "WHO_AM_I":
return "My name is ".$_SESSION['who_am_i'];
break;
case "OTHER_CONSTANT":
// does some other evaluation and returns a string
break;
}
throw new Exception("Constant isn't defined");
}
}
?>
Then you can just echo myConstants::_('WHO_AM_I');
Constants by definition don't allow you to set it with dynamic content.
Here is a quote from the php manual:
As the name suggests, that value cannot change during the execution
of the script
You can see more by going here
You might be thinking of magical constants
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php
eval ("\$text_including_tax = \"$text_including_tax\";");
Scrap my previous answer.
The reason this eval() is here is shown in the php eval docs
This is what's happening:
$text_including_tax = '$tax ...';
...
$tax = 10;
...
eval ("\$text_including_tax = \"$text_including_tax\";");
At the end of this $text_including_tax is equal to:
"10 ..."
The single quotes prevents $tax being included in the original definition of the string. By using eval() it forces it to re-evaluate the string and include the value for $tax in the string.
I'm not a fan of this particular method, but it is correct. An alternative could be to use sprintf()
This code seems to be a bad way of forcing $text_including_tax to be a string.
The reason it is bad is because if $text_including_tax can contain data entered by a user it is possible for them to execute arbitrary code.
For example if $text_include_tax was set to equal:
"\"; readfile('/etc/passwd'); $_dummy = \"";
The eval would become:
eval("$text_include_tax = \"\"; readfile('/etc/passwd'); $_dummy =\"\";");
Giving the malicious user a dump of the passwd file.
A more correct method for doing this would be to cast the variable to string:
$text_include_tax = (string) $text_include_tax;
or even just:
$text_include_tax = "$text_include_tax";
If the data $text_include_tax is only an internal variable or contains already validated content there isn't a security risk. But it's still a bad way to convert a variable to a string because there are more obvious and safer ways to do it.
I'm guessing that it's a funky way of forcing $text_including_tax to be a string and not a number.
Perhaps it's an attempt to cast the variable as a string? Just a guess.
You will need the eval to get the tax rate into the output. Just moved this to a new server and for some reason this line caused a server error. As a quick fix, I changed it to:
//eval ("\$text_including_tax = \"$text_including_tax\";");
$text_including_tax = str_replace('$tax', $tax, $text_including_tax);
It is evaluating the string as PHP code.
But it seems to be making a variable equal itself? Weird.
As others have pointed out, it's code written by someone who doesn't know what on earth they're doing.
I also had a quick browse of the code to find a total lack of text escaping when putting HTML/URIs/etc. together. There are probably many injection holes to be found here in addition to the eval issues, if you can be bothered to audit it properly.
I would not want this code running on my server.
I've looked through that codebase before. It's some of the worst PHP I have seen.
I imagine you'd do that kind of thing to cover up mistakes you made somewhere else.
No, it's doing this:
Say $text_including_tax = "flat". This code evaluates the line:
$flat = "flat";
It isn't necessarily good, but I did use a technique like this once to suck all the MySQL variables in an array like this:
while ($row = mysql_fetch_assoc($result)) {
$var = $row["Variable_name"];
$$var = $row["Value"];
}