Parse PHP variable in html template - php

I know it has been discussed many times, but I can not find any solution to this problem.
I have a PHP file with the following code
if (file_exists("email.html")) {
$message = file_get_contents("email.html");
} else {
echo "No email.html file present";
return;
}
in my file email.html I have something like:
<p>Hello %recipient.UserName%, you receive this Email because you signed up at our site.</p>
variable $UserName is declared in the php file (in array).
When looking at the html file output, I see the variable is not correctly passed and stays as % %
Any suggestion?
thanks!

If you don't have a template engine you can't do it with % % OR other symbol . for your question simple approach is to use it like this :
<p>Hello <? = $recipient['UserName'] ?>, you receive this Email because you signed up at our site.</p>
EDIT
you have to include the file
ob_start();
include "email.html";
$message = ob_get_clean();

Related

Want to use PHP include to place a page header (in Bootstrap 5) based on the file name (and location)

I want to place an image, HTML or simply text as a page header on multiple pages, but it is specific to each page, based on the file name (and folder it is in).
So, for example, domain.com/portfolio/index.php gets one image (or text/HTML/CSS), domain.com/portfolio/about/index.php gets another, domain.com/portfolio/contact/index.php gets another and so on.
Basically, I want to update this common element from one file instead of updating a bunch of files. I will usually use either the same image or the same HTML/CC design with different text and/or image in it, so the code example below includes a simplified version of each, just in case.
I've successfully used this in the past for pageheaders on sites but it no longer seems to work (PHP updated or maybe Bootstrap 5 is mucking things up)... it sits in pageheader.php which is then included in the top.php that is used (included) on each page of the site. (And I am not a programmer :) )
Help is always appreciated - thanks!
<?php
$path = ("/portfolio");
$size = ("WIDTH=525 HEIGHT=41 BORDER=0");
$self = $_SERVER['PHP_SELF'];
if (strstr($PHP_SELF,"$path/about.php")) {echo "<h1>About Page Header HTML/CSS Here!</h1>";}
elseif (strstr($PHP_SELF,"$path/index.php")) {echo "Home Page Header Text Here";}
elseif (strstr($PHP_SELF,"$path/design/index.php")) print ("<IMG SRC=$path/images/header_design.jpg $size>");
elseif (strstr($PHP_SELF,"$path/articles/index.php")) print ("<IMG SRC=$path/images/header_articles.jpg $size>");
else {echo "<h1>Hello World.</h1>";}
?>
Note : $PHP_SELF in (strstr($PHP_SELF,"$path/about.php"))
Shouldn't it be $self, e.g. (strstr($self,"$path/about.php"))
<?php
$path = ("/portfolio");
$size = ("WIDTH=525 HEIGHT=41 BORDER=0");
$self = $_SERVER['PHP_SELF'];
if (strstr($self ,"$path/about.php")) {echo "<h1>About Page Header HTML/CSS Here!</h1>";}
elseif (strstr($self ,"$path/index.php")) {echo "Home Page Header Text Here";}
elseif (strstr($self ,"$path/design/index.php")) print ("<IMG SRC=$path/images/header_design.jpg $size>");
elseif (strstr($self ,"$path/articles/index.php")) print ("<IMG SRC=$path/images/header_articles.jpg $size>");
else {echo "<h1>Hello World.</h1>";}
?>

Echo php with echoed html php

I currently have a php which echo my html template.
However in that HTML template there is another echo which calls from another php script.
Just wondering how do I do that? Because once I echo my html template the other it doesn't seems to echo my content from the other php script.
HTML TEMPLATE
<php? $html = '<span>name:<?php echo $name; ?></span><span>email:<?php echo $email; ?></span>' ?>
CONTACT TEMPLATE
<php? $name = "hello world"; $email = "hello#world.com"; ?>
I can see what you're trying to do, and it's a simple error. You can't escape php like that whilst inside setting a variable.
Also, I must add that you are declaring php incorrectly.
This is preferred
<?php
not
<php?
So make sure for your contact template you use the correct tag.
Also to include a file you have to call it/require it.
Back to the original question - Here is your method
<php? $html = '<span>name:<?php echo $name; ?></span><span>email:<?php echo $email; ?></span>' ?>
Here is the correct method
<?php
require('contact.php');
$html = '<span>name:'.$name.'</span><span>email:'.$email.'</span>';
echo $html;
?>
First I created the variable. And when doing so I insert the existing variables by escaping the php. Only once this final variable is created do I echo it.
Hope this helps you on your way.
Try to use include. The include statement includes and evaluates the specified file, in this case - your template.
Just Concatenation
<?
$html = '<span>name:'.$name.'</span><span>email:'.$email.'</span>';
?>
Change the tags from <php? ?> to <?php ?> in your script

Order of inclusion and interpretation for php and html

I am trying to display different content on a page based on some options.
Also, I am trying to avoid using php echo for all the html output.
I came up with the following solution accidentally, and now I'm confused about how it actually works.
test.php
<?php
function get_content() {
$page = 0;
if($page == 0)
include('page0.php');
else
include('page1.php');
}
?>
<html>
<body>
<?php echo get_content() ?>
</body>
</html>
page0.php
<?php
$link = "http://www.google.ca";
$name = "GOOGLE";
?>
<?= $name ?>
page1.php
<?php
$link = "http://www.yahoo.ca";
$name = "YAHOO";
?>
<?= $name ?>
It seems like the php interpreter would end up including html tags into a <?php ?> block when it reaches the following line, but somehow, this code works, and the outputted html is valid.
include('page0.php');
Can someone explain what exactly is going on here?
When a file is included, parsing drops out of PHP mode and into HTML
mode at the beginning of the target file, and resumes again at the
end. For this reason, any code inside the target file which should be
executed as PHP code must be enclosed within valid PHP start and end
tags.
From PHP manual, include function.

PHP include inside of an existing code?

Here's my code:
<?php
if(isset($_GET['p']))
{
$nshortname = strip_tags($_GET['p']);
$check = mysql_query("SELECT * FROM pages WHERE `shortname` = '$nshortname'");
if(mysql_num_rows($check) == 0)
{
echo '<center><font size="50" style="font-weight:bold;">404</font><br>Appears this page is a dead end</center>';
}
else
{
$h = mysql_fetch_array($check);
//post details
$title = $h["title"];
$content = $h["content"];
$shortname = $h["shortname"];
// Start of page content
echo '
<p>
<font size="5pt">'.$title.'</font><br><hr>
'.$content.'<br>
';
// End of page content
}
}
else
{
echo 'No page has been selected to view';
}
?>
What it does exactly, is it grabs pages from my database and reads them, so for example if I have a page in that table called "test" I can go to it by http://mylink.com/?p=test. Although i've come up with an issue. On one of those pages that come from the database I want to include but when I type it into the database field and go back to the page it shows with nothing.
I went to the source of the page in my browser and found out the code turned into <!--?php include "inc/extra/plugins/header/slideshow.php"?-->
Does anyone know how I can sold it from turning into <!--? and make my include code work.
I would caution against using eval() of unknown content. Basically, the content comes from your database, but that doesn't guarantee it's safe to execute as code! There are a lot of ways it could cause errors or do something malicious.
But you also have other dangerous security gaffes in your code. You should learn about how to defend against SQL injection vulnerabilities and Cross-Site Scripting (XSS) vulnerabilities and File Inclusion vulnerabilities.
Use mysql_real_escape_string() if you are still using the deprecated ext/mysql. But if you can, switch to mysqli or PDO_mysql and use prepared statements with parameters.
Always output dynamic content with htmlspecialchars(). What if the content contains Javascript code? It could cause mischief.
Never eval() arbitrary content as code. You have no control over what that content is, or what it could do when you execute it.
Be as restrictive as possible - if you want to include a file, store the filename separately from content (e.g. in a separate column), and use it only for including files.
Here's an example with some of these problems fixed in your code:
<?php
if(isset($_GET['p']))
{
$nshortname = mysql_real_escape_string($_GET['p']);
$check = mysql_query("SELECT * FROM pages WHERE `shortname` = '$nshortname'");
if(mysql_num_rows($check) == 0)
{
echo '<center><font size="50" style="font-weight:bold;">404</font><br>Appears this page is a dead end</center>';
}
else
{
$h = mysql_fetch_array($check);
//post details
$title = htmlspecialchars($h["title"]);
$content = htmlspecialchars($h["content"]);
$shortname = $h["shortname"];
// Start of page content
echo '
<p>
<font size="5pt">'.$title.'</font><br><hr>
'.$content.'<br>
';
// End of page content
// Start of include
if ($h["include"]) {
// strip out anything like "../../.." etc.
// to make sure this is only a simple filename.
$include = basename($h["include"]);
include "inc/extra/plugins/header/{$include}.php";
}
// End of plugin inclusion
}
}
else
{
echo 'No page has been selected to view';
}
?>
Also check out http://www.sitepoint.com/php-security-blunders/ and http://phpsec.org/projects/phpsecinfo/
Re your comments:
To allow a limited set of basic HTML, the best tool you need to use is http://htmlpurifier.org
I'm not sure what to say about your include displaying code instead of working. I just tested this, and the following two files seem to work exactly as intended:
foo.php:
<?php
echo "<h1>START FOO</h2>";
if ($_GET["include"]) {
$include = basename($_GET["include"]);
include "./{$include}.php";
}
echo "<h1>END FOO</h2>";
bar.php:
<?php
echo "<h2>BAR</h2>";
If you have a variable $content which is html with php, you can use
eval("?>" . $content . "<?php");
This will output $content having processed all the <?php ?> tags.

Changing Text in PHP

I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.

Categories