Im a student studying PHP, Java. but I don't know if eval can access outside variable.
My code :
<?php
$o = "This is just test character";
$code = "echo $o;"
eval($code);
?>
does it active? if not, how can i make it to active? (my purpose is eval() can access outside variable..)
sorry for my bad english and thx for listening.
Apart from the obvious missing ; on line 2
The issue you're having with eval is the string you're passing is not valid PHP.
<?php
$o = "This is just test character";
$code = '<?php echo $o;';
eval('?>'.$code);
https://3v4l.org/CHkR3
And if you're using double quotes it will parse into the string and again create invalid PHP by missing the quotes.
<?php
$o = "This is just test character";
$code = "<?php echo '$o';";
eval('?>'.$code);
https://3v4l.org/CHkR3
Bottom line, if you don't know how eval works then you should definitely not use it.
You need to put the string in the $code variable between aposthropes and then it'll work. Like this:
$o = "'This is just test character'";
$code = "echo $o;";
eval($code);
Related
Hey i have problem code:
$$videoList[$i]["id"] call variable -> $hello
but i need add one more letter to the end
$$videoList[$i]["id"]+W call varriable -> $helloW
<p>'.$$videoList[$i]["id"].'</p>
I don't advise to do what you are doing.
The code becomes a true hell that nobody can mantain in the long run.
Anyway, if you hate the world, you can achieve with ${$videoList[$i]["id"].'W'}
As for a better understanding, see this example:
<?php
$hello = 'sayHello';
$helloW = 'with W';
$myVar = 'hello';
echo $myVar; //hello
echo $$myVar; //sayHello
echo $$myVar.'W'; //sayHelloW
echo ${$myVar.'W'}; //with W
Could someone point out what I'm mistaking here? :)
<?php
$q = $_GET[q];
$acuman = <<<PARSE
input: (contains: "hello"){
output: "hello";
}
PARSE;
$acuman = str_replace("input: (contains: ", 'if(strpos(', $acuman);
$acuman = str_replace("){", ', $q) !== false) {', $acuman);
$acuman = str_replace("output: ", '$output = ', $acuman);
eval($acuman);
?>
I'm attempting to execute the string $acuman, a heredoc which has been altered by various str_replace functions. However, it is not doing what I intend it to do, and I am confused as of what to do as I've tried many different things.
Since many people seemed confused: My intention is for the code in the string $acuman to be executed as code properly. I just want the eval function to work. I know that eval is evil, please, stop: I'm just asking for help for solving the problem at hand.
Edit: When I echo the string $acuman, this is what I get:
if(strpos("hello", $q) !== false) { $output = "hello"; }
You have the arguments in the wrong order:
if(strpos($q, "hello") !== false) { $output = "hello"; }
strpos() takes the "haystack" (string being searched) as the first argument and the "needle" (string to find as within the "haystack") as the second argument.
Ok, so... $acuman appears to contain the following:
if(strpos("hello", $q) !== false) {
echo "hello";
}
Which indicates that $q needs to contain a portion of "hello" to echo the string "hello".
I don't see any problem here, EXCEPT that $q = $_GET[q]; won't work with any modern version because q is treated like a constant, not a variable nor a string literal array index. See this PHP documentation on the subject.
Upon changing to $q = $_GET['q']; instead (note the quotes), it seems like this code actually works. It will output "hello" whenever passing any portion of "hello" to the URL parameter (which gets passed to the PHP code).
Needless to say: Do not use this code for production. The code as it is is very vulnerable and allows a user to pass raw PHP code through to your script to execute. The function of this code can be completely re-written in a much safer manner, but you have expressed the desire to continue using eval(); so please be careful.
Enjoy.
I would like to know if there is a way to bind PHP function inside a regexp.
Example:
$path_str = '/basket.php?nocache={rand(0,10000)}';
$pattern = ? // something i have no idea
$replacement = ? // something i have no idea
$path = preg_replace($pattern, $replacement, $path_str);
Then :
echo "'$path'";
would produce something like
'/basket.php?nocache=123'
A expression not limited to the 'rand' function would be even more appreciated.
Thanks
You could do the following. Strip out the stuff in between the {} and then run an eval on it and set it to a variable. Then use the new variable. Ex:
$str = "/basket.php?nocache={rand(0,10000)}";
$thing = "rand(0,10000)";
eval("\$test = $thing;");
echo $test;
$thing would be what's in the {} which a simple substr can give you. $test the becomes the value of executing $thing. When you echo test, you get a random number.
Don't, whatever you do, store PHP logic in a string. You'll end up having to use eval(), and if your server doesn't shoot you for it, your colleagues will.
Anywhoo, down to business.
Your case is rather simple, where you need to append a value to the end of a string. Something like this would be sufficient
$stored = '/basket.php?nocache=';
$path = $stored . rand(0,10000);
If, however, you need to place a value somewhere in the middle of a string, or possibly in a variable location, you could have a look at sprintf()
$stored = '/basket.php?nocache=%d&foo=bar';
$path = sprintf($stored, rand(0,10000));
I would not try to store functions in a database. Rather store some kind of field that represents the type of function to use for each particular case.
Then inside your crontab you can do something like:
switch ($function)
{
case 'rand':
$path_str = '/basket.php?nocache='. rand(0,10000);
}
e.t.c
I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.
I'm having trouble describing this issue, which is probably why I can't find the answer on google.. so I figured I would try getting help here. If I'm repeating this question, feel free to direct me to a link to the thread.
So basically the issue I'm having is I am trying to pass a variable to a function that contains some php code to be eval'd.
Here's the simplified version of the code:
function senduser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
echo eval($body);
}
}
$body = 'Hello $row[\'user_first_name\'] <br>';
sendUser($body);
--
For some reason, the output isn't putting out what I want. I've gotten a few whitespace errors, and a few times I've gotten the code to output the plain text of the variable $body.
Any help is appreciated. Let me know if I need to clarify the issue further.
I would change it to this:
function sendUser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
echo $body($row);
}
}
And then call it like this (php 5.3+):
$body = function ($row) {
return "Hello ".
htmlspecialchars($row['user_first_name'], ENT_QUOTES, 'UTF-8').
"<br />";
};
sendUser($body);
In php <= 5.2, it's a lot messier:
$body = create_function(
'$row',
'return "Hello ".'.
'htmlspecialchars($row["user_first_name"], ENT_QUOTES, "UTF-8").'.
'"<br />";'
);
sendUser($body);
That isn't now eval works; it returns null unless you explicitly return a value. You're also missing quotes around the string, and a semicolon at the end of the statement.
To get it to echo something, you'd have to pass the echo as part of the code to be evaluated:
$body = 'echo "Hello $row[\'user_first_name\'] <br>";';
or, to get your code working as written, you'd have to return the formatted string:
$body = 'return "Hello $row[\'user_first_name\'] <br>";';
This is a pretty contrived use of eval. You'd be far better off passing in a printf-style format string and using sprintf to substitute values into it, and returning that string for printing. As it stands you seem to be mixing your display logic with your database logic, which is a bad thing.
Your code, as is, will never work. Removing the mysql portion:
<?php
function senduser($body) {
$row['user_first_name'] = 'Fred';
echo eval($body);
}
$body = 'Hello $row[\'user_first_name\'] <br>';
sendUser($body);
Gives me:
PHP Parse error: syntax error, unexpected T_VARIABLE in /home/marc/z.php(5) : eval()'d code on line 1
Anything you pass in to eval() must be raw PHP code. It can't be plaintext with embedded <?php ?> PHP blocks - it has to be actual PHP code. When you fix up $body to account for this:
$body = 'echo "Hello {$row[\'user_first_name\']} <br>";';
Then you get:
Hello Fred <br>
I'm not exactly positive what you're trying to do, but I think your problem is in the definition of $body and your use of eval.
$body = 'Hello $row[\'user_first_name\'] <br>';
is not a valid line of php, and eval won't know what to do with it.
See if this fits what you want:
function senduser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
eval($body);
}
}
$body = 'echo "Hello {$row[\'user_first_name\']} <br>";';
sendUser($body);