vulpcod3z
vulpcod3z

Reputation: 194

PHP script inside of string?

Is this possible?

What I am trying to accomplish:

Everything but the 2nd step works. I would like to see a php file echo the question being asked, onto the html page, including an echo from another php file.

EXAMPLE

echo "<div id=\"first\"><?php include \'countries.php\'; ?></div>";

I have tried the above, as well as the below:

EXAMPLE

echo "<div id=\"first\">".include 'countries.php'."</div>";

Would this require eval?

Any and all help is appreciated.

Upvotes: 0

Views: 929

Answers (3)

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

You can use a regular expression.

For example, your string could be;

<div id="first">{{countries.php}}</div>

You'd then do;

$string = "<div id='first'>{{test2.php}}</div>";

echo preg_replace_callback("/(\{\{.+\}\})/", function($matches) {
   include_once( str_replace(array("{", "}"), "", $matches[0]));
}, $string);
  • Check the file exists if( file_exists() )
  • Check the file can be included (we don't want to include ../../../../../etc/passwd

Upvotes: 0

ehwas
ehwas

Reputation: 248

You can use

eval()

But it is not a good practice.

Upvotes: 0

emsoff
emsoff

Reputation: 1605

Seems a bit silly, but you could do the following:

echo "<div id=\"first\">" . file_get_contents('countries.php') . "</div>";

Or...

echo "<div id=\"first\">";
include "countries.php";
echo "</div>";

Or...

$externalfile = compileexternal('countries.php');
function compileexternal($file) {
    ob_start();
    require $file;
    return ob_get_clean();
}

echo "<div id=\"first\">" . $externalfile . "</div>";

If none of these are what you need, please update the question. There are a dozen ways.

Upvotes: 2

Related Questions