tags:

views:

81

answers:

3

I have PHP variables to place within an included HTML file. What's the best way of executing this?

//contents of file1.php
$variable1 = "text 1";
$variable2 = "text 2"
$newContent = include('file2.php');
echo $newContent;

//contents of file2.php
<p>standard HTML with PHP... <strong><?=$variable1?></strong></p>
<p><?=$variable2?></p>

This general method is considered OK but the actual code here doesn't work. Do I use file_get_contents() or include(), how do I execute the PHP within the includes file to output the correct contents?

Should I be using something like HTML>>>

+4  A: 

What you're doing is fine, and you'll find that most people use the same exact method. I personally wouldn't use PHP short tags (some hosts don't enable it), but that's a matter of preference.

Edit: As per your edit, it seems like you don't have short tags enabled. Check your ini (http://php.net/manual/en/ini.core.php). But you really shouldn't be using short tags, because as clownbaby mentions, PHP 6 will deprecate them. Even if you don't care about future proofing your code, they're still troublesome (which is evident because your code isn't working). Switch to <?php echo $variable1; ?> and you'll be fine.

Arms
Agreed - short tags are being deprecated in PHP 6.
clownbaby
+2  A: 

I think your code is fine, even most frameworks use it...

regarding the use of short tags, some servers do not allow it, so here is a workaround I use:

if ((bool) @ini_get('short_open_tag') === FALSE){
   echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents("path/to/file2.php"))));
}else{
   $newContent = include("path/to/file2.php");
   echo $newContent;
}
pǝlɐɥʞ
+2  A: 
$newContent = include('file2.php');
echo $newContent;

You shouldn't need to echo anything here. Just including the PHP file should execute any code inside it and spit out the interpolated template to the page. Whilst there is such a thing as returning a value from include, it's a rarely used feature you can generally ignore.

As ekhaled said, you may need to enable short tags or replace them with the always-supported <?php ... ?> processing-instruction-style syntax.

However, it's important to htmlspecialchars every text string when including it in HTML, or you've got a potential XSS security hole.

<?php
    function h($text) {
        echo(htmlspecialchars($text, ENT_QUOTES));
    }
?>
...

<p>standard HTML with PHP... <strong><?php h($variable1) ?></strong></p>
<p><?php h($variable2) ?></p>
bobince