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.
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"
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!"
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.
I need help figuring out the syntax for the eval function - or even if eval is the right approach. I have a column in my mysql database which holds the name of a PHP function I need to run. There are also PHP variables that would like to leave as variable until they are passed to the function. Below is what I have so far:
eval($valRec[$key]($key,$value));
$valRec is the array which contains the results of a mysql SELECT. $key is a variable which references the name of the column that contains the function name.
$key and $value are the PHP variables that I need to pass into the function.
In the end, I want to end up with:
functionName($key,$value);
which PHP should run.
Hopefully I explained it clearly - thank you in advance for any help!
Eval is probably not what you want. Look at call_user_func and call_user_func_array. They let you call a function whose name is in a variable.
call_user_func($valRec[$key], $key, $value);
All you need to do is:
$valRec[$key]($key,$value);
Reference: variable functions.
In php, you could do below;
$func = 'strtolower';
$foo = $func($bar);
So in your case, $valRec[$key]($key,$value); will just work.
Check the demo.
Addtion:
The reason why your eval not work is because eval need to take a string as parameter, not don't forget ; to end the statement, or it will be syntax error.
So you need to do:
eval($valRec[$key].'($key, $value);');
I haven't used PHP recently, but the concept of eval is to evaluate a string.
As such, you need to create the string representing the line of code you want run.
In your case that means:
eval($valRec[$key] . '($key, $value);');
You've said it yourself, you want to end up with functionName($key,$value); so you need to make a string that is that, then pass it to eval.
see this 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";
?>
this is the output
This is a $string with my $name in it.
This is a cup with my coffee in it.
you need to read this, when is eval evil in php?
{$row['info']}
How do I use stripslashes() php function on this?
I've tried :
stripslashes({$row['info']}), doesnt work and this: {stripslashes($row['info'])}
Neither work.
Do I have to use a $var first??
Thanks
stripslashes returns the modified string, leaving its argument unchanged. You have to assign the result to a variable:
$var = stripslashes($row['info']);
That said, why are you doing this? You almost certainly shouldn't be. There is no reason to strip slashes on data coming from the database, unless you've double-escaped the slashes when the data was inserted.
Your question is somewhat confusing.
stripslashes() takes parameter and converts backslashed symbols to normal ones. more over, it does not affect the parameter. it returns stripped version.
so $result = stripslashes($source) or $row["info"] in your case.
$var = stripslashes($row['info']);
is more correct. Or in string, use it like this
echo "something".stripslashes($row['info'])." some more thingy";
It almost seems, that you are using heredoc syntax because of your {}. Question, is why? Are you seriously displaying your results like this?:
echo <<<my_results
Info: {$row['info']}
my_results;
Well, since that is cool way to do so then here is your fix:
$row_info = stripslashes($row['info']);
echo <<<my_results
Info: {$row_info}
my_results;
However, I do not recommend that approach. Rather do it like this:
echo 'Info:' . stripslashes($row['info']);
Because {stripslashes($row['info'])} doesn't work indeed and stripslashes({$row['info']}) is an anecdote!