PHP eval $a="$a"? - php

I was looking through some code for work, and came across this line:
eval("\$element = \"$element\";");
I'm really confused as to why any PHP developer would've written this line. What purpose does this serve, besides setting a variable to itself?
Luckily, the function this line is in is never called.

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
The above example will output:
This is a $string with my $name in it.
This is a cup with my coffee in it.
http://php.net/manual/en/function.eval.php
I do just ctl+c ctrl+v :-)

It converts the value of the variable to a string, but I wouldn't recommend using it.
Use the function strval() instead. Have a look at the manual.

This assigns the string-converted contents of the variable $element to a variable called $element. Another way to do this is to use strval, or in some cases print_r($x, true)

It doesn't really do much except converting the value to string or might serve as a poor alternative to sprintf. But if the variable contains double quotes, this is gonna cause some trouble. You really wouldn't want to eval a code like this:
$element = 'foo"bar';
Not to mention some even more harmful code. Seems like a place for a "php injection" :D
Don't use it.

Related

Using each match in preg_replace() in PHP

I've read through multiple tutorials on regex and it's associated functions but I am stumped on this one.
I have a really simple replace that looks for a specific delimiter and parses the name of a PHP variable. Here it is:
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $this->file));
I keep getting errors about php not liking the #1 in ${$1}. Fair enough, can't start a variable name with a number, I knew that...
So I tried:
var_dump(preg_replace('/{{\$(.*?)}}/', ${'$1'}, $this->file));
Same thing.
Yet if I try:
var_dump(preg_replace('/{{\$(.*?)}}/', '$1 yo', $this->file));
It works...
So, how do I get php to echo a variable named whatever $1 is.
For example:
$hola = yo;
$string = hello{{$hola}}hello{{$hola}};
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $string));
And the output would be:
helloyohelloyo
Spank you!
EDIT
I should also mention that I am aware that there is a standard recommendation on how to match php variables with regex, but i'd like to get it working with a regex that I fully understand first.
Like so:
$hola = 'yo';
$string = 'hello{{$hola}}hello{{$hola}}';
$result = preg_replace_callback('/\{\{\$(.*?)\}\}/', function ($matches) use ($hola) {
return ${$matches[1]};
}, $string);
var_dump($result);
preg_replace_callback calls a callback on every match.
In order to use the $hola variable inside the callback you need to explicitly make it available inside the function (use ($hola)).
All this said... I don't get it. What this code does is essentially what PHP already does out-of-the-box.
$hola = 'yo';
$string = "hello{$hola}hello{$hola}";
echo $string; // "helloyohelloyo"

Convert String to Variable

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!"

Is it possible to print php variable withing a variable?

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.

PHP eval syntax

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?

Using stripslashes on a database row 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!

Categories