Execute php code from template - php

I have the following code in PHP:
if ($maintenance_mode == true)
{
$file = 'maintenance-header.php';
$template = file_get_contents($t_includes_path . $file);
}
else
{
$file = 'main-header.php';
$template = file_get_contents($t_includes_path . $file);
}
require_once($s_system_path . 'templater.php');
And then in templater.php:
$page = str_replace(array(
'{slang}',
'{site_title}',
'{site_desc}',
'{keywords}',
'{t_assets_path}',
'{s_assets_path}',
'{i_assets_path}',
), array(
$slang,
$site_title,
$site_content,
$keywords,
$t_assets_path,
$s_assets_path,
$i_assets_path,
),
$template);
echo $page;
The problem is that if I try to use php code within the template file itself it doesn't get recognized and is parsed as comments/plain text. Example:
if (htmlentities($_GET['lang'], ENT_QUOTES) == 'en')
{
echo 'English';
}
else if (htmlentities($_GET['lang'], ENT_QUOTES) == 'ru')
{
echo 'Russian';
}
else
{
echo 'Other';
}
How to deal with this? I really want to use {site_title} instead of <?php echo $site_title; ?> etc. I want to keep my code as clean as possible.

you have to exectue your php code. if you just 'echo' it, code that is inside your string will not be executed, just printed on the page.
you can use eval() function for example, but be sure that users can't force your web to eval() theirs code.. as mentioned on docs:
http://php.net/manual/en/function.eval.php

Related

If/else in return tag

I'm quite new to PHP, so this is probably a stupid question.
I have an if/else that I need to use in a return tag, but it doesn't work. How should I structure this?
This is the tag:
return '… <div class="read"><a class="read-more hvr-icon-forward" href="'. get_permalink($post->ID) . '">' . "CODE HERE" . '</a></div>';
This is what I need to output in "CODE HERE"
$status = of_get_option('read_more');
if (empty($status)) {
echo 'Sorry, the page does not exist.';
} else {
_e($status);
}
https://jsfiddle.net/33nv1xpa/1/
Do I get it right, you have a structure like
return *SOME_STRING* SOME CODE WITH ";" *SOME_STRING*
?
I would highly recommend, to create a string var containing the text you want to return and finally only return that string.
$echoCode = result from CODE HERE
$returnText = "<div>blalba</div>" . $echoCode . "<div>blabla</div>";
return $returnText;
You can do it by using the ternary operator, and putting the variable assignment in parenthenses.
return "...". (($status = get_option('status')) ? $status : _e()) ."...";
Otherways, I suggest to put this functionality in a function, or at least in a plain variable.
Coding like this makes the whole thing unreadable.
Also, you're trying to run a wordpess function in an online parser which will undeniably miss these features!
Well you can use the Php eval function (http://php.net/manual/en/function.eval.php). It evaluates a string as Php code. So you can assign the result of eval to a variable called $code_here:
$code_here = "$status = of_get_option('read_more');
if (empty($status)) {
echo 'Sorry, the page does not exist.';
} else {
_e($status);
}";
$code_here = eval($code_here);

can not echo a function content inside file_get_contents

Suppose this code prints Youtube:
<?php ytio_empt(); ?>
I want a dynamic way to echo the content of the above function in the place of 'YouTube' in the following xml data:
$xmlData = file_get_contents( 'http://gdata.youtube.com/feeds/api/users/'. 'YouTube' );
I have tried:
$xmlData = file_get_contents( 'http://gdata.youtube.com/feeds/api/users/'. ytio_empt() );
But in vain, the file_get_contents() always fails to open stream.
P.S: Perhaps using HTML will work: to put <?php ytio_empt(); ?> in the place of ytio_empt() in $xmlData. I just don't know how to end PHP function and resume it later..
So as you posted your function in the comments:
function ytio_empt() {
if(empty(get_option('ytio_username'))) {
echo esc_attr( get_option('ytio_id') );
//^^^^
} else {
echo esc_attr( get_option('ytio_username') );
//^^^^
}
}
You will see you don't return the values you just print them! So in order to return them you simply have to change echo -> return.
And if you want to read more about return values see the manual: http://php.net/manual/en/functions.returning-values.php

Basic Template Engine Fix

I am attempting to make a (very) basic template engine for php. Based on my research I have found that a method that I am using is strongly disliked. I was wondering if anyone knew a great alternative to get the same result so I am not using it. And if anyone sees any other improvements that can be made please share!
the method that is not advised is the eval() method!
Here is the php file
<?php
class Engine {
private $vars = array();
public function assign($key, $value) {
$this->vars[$key] = $value;
}
public function render($file_name) {
$path = $file_name . '.html';
if (file_exists($path)) {
$content = file_get_contents($path);
foreach ($this->vars as $key => $value) {
$content = preg_replace('/\{' . $key . '\}/', $value, $content);
}
eval(' ?>' . $content . '<?php ');
} else {
exit('<h4>Engine Error</h4>');
}
}
}
?>
here is the index.php file
<?php
include_once 'engine.php';
$engine = new Engine;
$engine->assign('username', 'Zach');
$engine->assign('age', 21);
$engine->render('test');
?>
and here is just a test html file to display its basic function
My name is {username} and I am {age} years old!
outputs:
My name is Zach and I am 21 years old!
Many thanks in advance!
If you just want to output some text to the page, just use echo:
echo $content;
This is better than eval('?>' . $content . '<?php') for quite a few reasons: for one, if someone types in <?php phpinfo(); ?>, for example, as their username, it won't execute that code.
I would, however, note that you have some other problems. What if I do this?
$engine = new Engine;
$engine->assign('username', '{age}');
$engine->assign('age', 21);
$engine->render('test');
The {age} in the username value will be replaced with 21. Usually you don't want replacements to be replaced like that, particularly as it's order-dependent (if you assigned username later, it wouldn't happen).

php: simple template engine

I have a function called load_template()
this function has two parameters
$name => the name of the template
$vars => array of key => value variables to be replaced in the template.
the way I want this to work is.
in the template ('test') I want to be able to write
<?php echo $title; ?>
then call
load_template('test', array('title' => 'My Title'));
and have it fill it out.
how can I do this?
Output buffering method.
I have come up with the code below.
I am sure it can be improved.
public static function template($name, $vars = array()) {
if (is_file(TEMPLATE_DIR . $name . '.php')) {
ob_start();
extract($vars);
require(TEMPLATE_DIR . $name . '.php');
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
throw new exception('Could not load template file \'' . $name . '\'');
return false;
}
function load_template($name, $vars)
{
extract($vars);
include $name;
}
Wrap with ob_start and ob_get_clean if you want to capture the output in a variable.
Something like this?
function load_template($name, $vars)
{
include('template/'.$name.'.tpl'); //.tpl, .inc, .php, whatever floats your boat
}
and in template/whatever.tpl you'd have:
...
<title><?php echo $vars['title'] ?></title>
...
...
<?php if (!empty($vars['content'])): //template still needs to know if the content is empty to display the div ?>
<div id="content">
<?php echo $vars['content']; ?>
</div>
<?php endif; ?>
...
Of course, that assumes the output being printed directly.
You could have the tpl file print directly, or produce a string, or buffer the output from the tpl file and return it from load_template

PHP include inside of a variable

I have a function that is controlling the output of my page:
$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class='media-desc'>{$desc}</div>";
I would like to include a file "box.php" inside that html that is defined in the $page variable. I tried this:
$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class="inlinebox">" . include("box.php"); . "</div><div class='media-desc'>{$desc}</div>";
... but it didn't work. How can I put a php include inside of a variable?
from php.net
// put this somewhere in your main file, outside the
// current function that contains $page
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
// put this inside your current function
$string = get_include_contents('box.php');
$page = '<div class="media-title"><h2>{$title}</h2></div>';
$page .= '<div class="media-image">{$image}</div>';
$page .= '<div class="inlinebox">' . $string . '</div>';
$page .= '<div class="media-desc">{$desc}</div>';
How can I put a php include inside of a variable?
# hello.php
<?php
return "Hello, World!";
?>
# file.php
$var = include('hello.php');
echo $var;
I would generally avoid such a thing though.
First, don't use a semicolon from inside the statement.
Second, wrap the include statement in parentheses.
$page = "<div class='media-title'><h2>{$title}</h2></div>
<div class='media-image'>{$image}</div><div class="inlinebox">" .
(include "box.php") . "</div><div class='media-desc'>{$desc}</div>";
Finally: In the "box.php" file, you will need to do the following:
<?php
ob_start();
// your code goes here
return ob_get_clean();
EDIT: Some info about calling return outside of the function contest: PHP Manual - Return.
Edit:
Don't know if this is useful, but i think that including a file to get a piece of HTML, is not a good option. It's not scalable. You could try with something like MVC. You could ask your controller to renderize the content of what you want.
$view = $controler->getElement('box');
$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class="inlinebox">" . $view . "</div><div class='media-desc'>{$desc}</div>";
Try to decouple your code.
I recommend you to take a look to some MVC Framework, in my opinion, the best one is CakePHP.

Categories