2

I find myself in the situation where I need to call a PHP function stored as a string from another PHP function.

<?php
$phpcodestring = "<?php echo 'Hello World!' ?>";
echo $phpcodestring;
?>

How can I get Hello World to render to screen with the above structure?

6 Answers 6

2

Back up a few steps - why do you need to do that?

99.9% of the time there is a better way than eval().

Or you could use create_function() which internally uses something like eval() so isn't much better, especially when you are not defining the function body directly with a string literal so you can be sure there and then there is nothing potentially dangerous.

Sign up to request clarification or add additional context in comments.

3 Comments

I have PHP piece of code that exists in a WordPress theme options panel setting. I need to get this code into the interpreter and make it run.
@trnsrmr Ah WordPress, I should have known! Just hope there are no SQL injection holes.
I'd rather not doing anything that makes my theme more un secure. Will try and figure out a better way.
0

You can use the infamous eval() if you thoroughly trust the source of the string. How the hell did you find yourself in that situation?

1 Comment

The PHP code I'm trying to run is stored as a string in a WordPress theme options panel.
0

Sounds like a case of eval().

eval("echo 'Hello world!';");

You should always consider whether it's a good idea or not, though. Security considerations of eval() can be daunting.

G

3 Comments

I'd rather not create any security issues.
You just need to handle the inputs to eval carefully. It really, really is a last resort type of approach, though. Perhaps save the options panel setting as a file and include it?
Hmmm, will try and think of a better way.
0

You can use the eval() function: http://php.net/manual/en/function.eval.php

Comments

0

eval($phpcodestring);

2 Comments

This did not work. Here is my code: <?php $phpcodestring = "<?php echo 'Hello World!' ?>"; echo eval($phpcodestring); ?> Here is the error: Parse error: syntax error, unexpected '<' in /Users/jc/Sites/test.php(3) : eval()'d code on line 1
you musst strip the <?php and ?> in the code string and attach a semicolon at the end of the string like $phpcodestring = "echo 'Hello World!';";
0

An alternative approach would be to use create_function method, which is a poor implementation of lambda-style functions in PHP.

2 Comments

Doesn't create_function have the same security flaws as eval?
@trnsfrmr it is, but the solution is a bit more 'elegant' IMO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.