Including dynamic HTML with PHP - php

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>>>

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.

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;
}

$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>

Related

Output buffering and calling ECHO on an HTML string also containing ECHO

I have a template file that contains html with inlined PHP echo statements. For example, the template may look like:
<div class="<?php echo $classes ?>">
<div class="uk-container uk-container-center">
<section class="uk-grid uk-grid-match" data-uk-grid-match="{target:'> div > .uk-panel'}" data-uk-grid-margin>
<?php echo $content ?>
</section>
</div>
</div>
The template is read in the script using file_get_contents(). I then turn on output buffering. The variables $classes and $content are in scope at the time ob_start() is called.
ob_start();
echo $htmlTemplateString;
$resolvedMarkup = ob_get_clean();
Unfortunately, $resolvedMarkup contains the original string read from the template file and the inlined echo statements are still present and not resolved to the values of the referenced variables.
My question is, am I interpreting this usage correctly? Should I be getting back a fully resolved string?
Normally, I could use include to achieve this sort of thing but on this occasion, despite the brevity of the example code, there are numerous reasons why the templates are brought into memory (mostly because each template may be in a hierarchy of templates that need to be resolved into each other, altering the original template structure).
At this stage, I am trying to avoid using temporary files.
I hope this question is clear and would appreciate any advice/thoughts as to whether my approach should work and if so, what I might be doing wrong.
Here's your problem:
The template is read in the script using file_get_contents().
file_get_contents() is pretty much the equivalent of fopen(); fread(); fclose(). It simply sucks bytes from a file into a variable. Those bytes are NOT executed, so any PHP code blocks which maybe in that file remain as <, ?, p, etc... characters - they're not executed/replaced.
You need to use include() instead. That will execute any PHP code in the byte stream.
Just echo does not actually parse any PHP. What you need is eval.
Here I have to convert my template into text that can be parsed by php.
<?php
$str1 = " this is <?php echo \$i;?> now\n";
$i=99;
echo eval('?>' . $str1 . '<?php ');

PHP output in HTML file

Ay guys,
I do know two possibilites to display PHP in HTML:
<?php function(); ?> or the shorter method <?= function(); ?>
But I often see something like {METHOD} or {OUTPUT} in the HTML part of bigger scripts f.e.:
<div class="test">{OUTPUT}</div>
In my opinion this is a way tidier. Could somebody tell me more about this?
I have used php to generate html using the echo function and have used php inside html too.(If this clarifies your doubt in anyway)
echo $projectname; inside html file tags
echo the html file
Cheers :)
When echoing data in HTML without a template engine, short tags are preferred as they look cleaner, and are easier to read. They're great when using control structures too: http://php.net/manual/en/control-structures.alternative-syntax.php
For short tags to work short_open_tag needs to be enabled.
The example you shown with the curly brackets is usually specific to a template engine such as Twig.
you can use this method only with the function ECHO with double quotes :
1 - this works
$name = 'Mark';
echo "<div>GoodMorning {$name}</div>";
2 - this does not work
$name = 'Mark';
echo '<div>GoodMorning {$name}</div>';

PHP: php variable in html link (<a>)

Please help me with this problem.
<?php echo $userRow2['description']; ?>
It seems that the PHP variable is incompatible with html link :(
so I want to know what is the proper method.
TIA...
echo those variables there like the following.
<?php echo $userRow2['description']; ?>
Please use a template engine for these kinds of things...
Use one of:
smarty
twig
mustache
php-view
These will brighten up your day and remove the complexity out of your html files
You can also pass all your GET params in an associative array, and use:
http_build_query($params)
so:
or in your way:
<?php echo $userRow2['description']; ?>
You can also build html/php mix with heredoc:
http://www.hackingwithphp.com/2/6/3/heredoc
it seems that the php variable is incompatible with html link
Well, PHP runs server-side. HTML is client-side. So there's no way for client-side code to interpret PHP variables.
You need to enclose server-side code in <?php ?> tags in order for it to execute on the server (like you already do elsewhere). Otherwise the server just treats it as any other HTML and returns it to the browser. Something like this:
<?php echo $userRow2['description']; ?>
As you can see, that gets a bit messy. But you can put the whole thing in one echo statement:
echo "$userRow2[description]";
Notice how the double-quotes needed to be escaped in that one, but since the whole thing was a double-quoted string the variables contained therein would expand to their values.
There are readability pros and cons either way, so it's up to you how you want to present it.
you should use this
<?php echo $userRow2['description']; ?>
or
<?=$userRow2['description']?>
You can also use Here Doc Syntax
<?php
//test variables
$inst_id = 1;
$description = "Test 1";
$eof = <<<EOF
$description
EOF;
//test output
echo $eof;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Are there any restrictions on when you can mix HTML and PHP?

I was surprised to find that you can break out of a PHP function into raw HTML and back. I knew that you could do this sort of thing with loops and conditionals, but this was a surprise to me. Is it an accident or is this well-defined behavior? (I couldn't find any explicit discussion of the function case in the manual.)
[NOTE: The following code doesn't give a good example of when I would use this behavior, but I kept it simple for demonstration purposes.]
<?php
$i = 0;
while($i++ < 3) {
?><p>I am in a while loop.</p><?php
}
// this part surprised me
function actSkeptical($adjective) {
?><p>Is it <?= $adjective ?> that this works?.</p><?php
}
actSkeptical("weird");
?>
Output:
I am in a while loop.
I am in a while loop.
I am in a while loop.
Is it weird that this works?
I know some people absolutely hate mixing PHP and HTML like this, but I can't do OOP/templating (for reasons I won't go into here) and I do like seeing as much raw HTML as possible.
Also, I don't quite understand the semantics of how the short open/close tag above (outputting $adjective) works in conjunction with the surrounding code. Does PHP just treat raw HTML like it was an echo statement? And then the <?= $adjective ?> is just like including a variable within a string?
I can't seem to find any documentation relating to the exiting of PHP tags within blocks. However, there's really only a few places escaping to HTML will work.
Normal Usage
<?php
php_related_code();
?>
//html/css/js/etc
Within blocks, such as while, for, functions, etc
<?php
for ($i = 0; $i < 5; $i++) {
?>
hello world
<?php
}
$i = 5;
while ($i-- > 0) {
?> hello there <?php
}
function myFunc() {
?>
hello universe
<?php
}
myFunc();
You can think of ?>stuff<?php similar to an echo or print command found in PHP, because you can escape to HTML in the same places you can echo. So you can echo within the main script, in for loops, and you can echo in functions. But you can't echo in an array, for example:
<?php
$array = array(echo "here"); //not allowed
$array = array(?>here<?php); //also not allowed
So you can think of escaping the same as echoing in which it can tell you where you can use it, but you can't do the same thing when you're thinking about what it does.
They act differently and are processed by PHP differently as well. But your question is only asking about any restrictions so I won't go into what are the differences between ?><?php and echo.
I forgot to mention, <?=$variable?> is just short tag for <?php echo $variable; ?> if you have this feature enabled.
This is called a spaghetti code. DO NOT USE IT.
If you really want to separate code, logic and markup start using MVC; YII is great.
http://www.yiiframework.com/
Also check this out: https://www.youtube.com/watch?v=mhwfFgSzg7U

php echo php to browser, not showing up, security issue?

What happen if i use the following?
<?php echo "<?php echo date('Y'); ?>"; ?>
i could not find an answer anywhere, and when i try it myself, i get:
<?php echo date('Y'); ?></td></tr></table>
However, it does not show up on front browser, only source.
So my question is, does this affect the html/browser/server in any way?
as i do not want to end up creating a security issue should user post their
own php code in a html only format, like a bio page etc.
It's because of the chevrons ('<' and '>'), because the browser interprets them as tags.
There are 2 ways you could get round this.
Either use the codes for special characters, so you would do:
<?php echo "<?php echo date('Y'); ?>"; ?>
Or, an easier way, use the htmlspecialchars() function:
<?php echo htmlspecialchars("<?php echo 'hi'; ?>"); ?>
More info on the htmlspecialchars() function can be found at http://www.php.net//manual/en/function.htmlspecialchars.php
It is not a security problem and will not have any effects on browser or server, at least not because of PHP code. Even if the string contains PHP code it will just be sent to the client which will not attempt to execute it.
The real problem when echoing user-defined HTML is the risk of attacks such as XSS. Users could include arbitrary scripts or images or scramble the rest of the page by inserting arbitrary tags. In other words: Users could modify the whole page with a single line of HTML.
In general, it's a bad practice to allow such arbitrary input. Have a look at strip_tags which provides a very basic level of protection.

Categories