I thought I’d share a handy trick I came across recently. Most people know of the handy Javascript eval(), but PHP has one of its own up its sleeve. My situation involved needing to capture the result of a PHP script for inclusion into content I was rendering in a Smarty plugin. The content I was creating would then be passed back for inclusion into the compiled template. My problem was that I was basically three levels deep in code parsing. What to do? Use the eval() function.
Example:
<?php
//send result of php script back
$num = 3;
eval("include 'http://www.example.com/myScript.php?num=$num';");
?>
I should note that by default the result of eval() is sent directly to the browser. If you want to capture the result, do something like the following:
<?php
//capture results of eval()
$num = 3;
ob_start();
eval("include 'http://www.example.com/myScript.php?num=$num';");
$result = ob_get_contents();
ob_end_clean();
?>
The eval()function can be used in many situations, of course. For one, you might have PHP code stored in a database that is rendered and included dynamically in a script.
Also, be sure that the string you pass contains all valid syntax including semicolons.
1 response so far ↓
1 Brian DeRocher // Aug 8, 2004 at 9:51 pm
You may be initerested in CURL = Client side URL, which can do similar things.