I have this code:
class template
{
public $template,$prefix,$replace;
function __construct($template, $prefix)
{
$this->prefix = $prefix;
$this->template = $template;
}
public function SetValue($name, $replace)
{
$this->replace["#".$name."#"] = $replace;
}
public function Tempclude($found)
{
$file = "styles/main/".$found[1].'.html';
if(!file_exists($file))
exit("the template '" . $found[1] . "' wasn't found.");
return file_get_contents($file);
}
public function finish($stream = "normal")
{
if($stream == "folder")
$code = file_get_contents("../styles/main/".$this->template.".html");
else
$code = file_get_contents("styles/main/".$this->template.".html");
$code = preg_replace_callback("#<pb:include=\"(.*)\">#iuU", array($this, 'Tempclude'), $code);
if(is_array($this->replace))
$code = str_replace(array_keys($this->replace), $this->replace, $code);
$code = str_replace("\r\n", "", $code);
$code = str_replace(" ", "", $code);
echo $code;
}
}
If I type in the Template some simple text, the page turns white with nothing inside.
What is the problem?
it is no the problem.
Try doing this:
$template = new template("index", "");
$template->SetValue("notice", "notice:");
$template->finish();
and index.html:
<pb:include="header">
hhh
#Slider#
<pb:include="footer">
its work.
if you change index.html to:
<pb:include="header">
<div id="hh">
hhh
</div>
#Slider#
it return a white list with somthing inside.
I have found the unquoted constant shows warning (depends on php configuration, WAMP does)
In the edited code that you have problem with errors, only quote the two constants in the begining it should work okay, test it like this:
$template = new template("index", "");
$template->SetValue("notice", "notice:");
$template->finish();
folder structure: styles/main must be provided. These files must be found inside main: index.html, footer.html, header.html must be privided
When everything okay, please try to delete any uneccessary comments or answers.
Thank you!
Related
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
So i am having difficulties trying to generate pdf from URL using mpdf
code :
<form action="generate.php" method="POST">
url: <input type="text" name="url"><br>
<input type="submit">
</form>
generate.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$url = test_input($_POST["url"]);
$pdf=file_get_contents($url);
include('mpdf60/mpdf.php');
$mpdf=new mPDF();
$mpdf->debug = true;
$mpdf->WriteHTML($pdf);
$mpdf->Output();
exit;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Returns no errors , just blank pdf page .
I got same problem with mPDF 5.6. When I used xdebug I found these 2 lines:
$str = #preg_replace('/\&\#([0-9]+)\;/me', "code2utf('\\1',{$lo})",$str);
$str = #preg_replace('/\&\#x([0-9a-fA-F]+)\;/me', "codeHex2utf('\\1',{$lo})",$str);
As you can see there is "#" char that blocking errors output. So if you have php >=7.0 you will never get error about "e" modifier that was deprecated. So all your HTML will be NULL after these lines.
I updated this function:
// mpdf/includes/functions.php
if (!function_exists('strcode2utf')) {
function strcode2utf($str,$lo=true)
{
//converts all the &#nnn; and &#xhhh; in a string to Unicode
if ($lo) { $lo = 1; } else { $lo = 0; }
// Deprecated modifier "E" in preg_replace
//$str = #preg_replace('/\&\#([0-9]+)\;/me', "code2utf('\\1',{$lo})",$str); // blocked errors output!! wtf?
//$str = #preg_replace('/\&\#x([0-9a-fA-F]+)\;/me', "codeHex2utf('\\1',{$lo})",$str);
$str = preg_replace_callback('/\&\#([0-9]+)\;/m',
function($num) use ($lo) {
return code2utf($num, $lo);
}, $str);
$str = preg_replace_callback('/\&\#x([0-9a-fA-F]+)\;/m',
function($num) use ($lo) {
return codeHex2utf($num, $lo);
}, $str);
return $str;
}
}
Yo haven't specified much about the url input that is being given.I hope the url is pointing to the same server.Else mpdf will show error
There is nothing wrong with your code.Please check for any file permission issue.
I'm including a file in one of my class methods, and in that file has html + php code. I return a string in that code. I explicitly wrote {{newsletter}} and then in my method I did the following:
$contactStr = include 'templates/contact.php';
$contactStr = str_replace("{{newsletter}}",$newsletterStr,$contactStr);
However, it's not replacing the string. The only reason I'm doing this is because when I try to pass the variable to the included file it doesn't seem to recognize it.
$newsletterStr = 'some value';
$contactStr = include 'templates/contact.php';
So, how do I implement the string replacement method?
You can use PHP as template engine. No need for {{newsletter}} constructs.
Say you output a variable $newsletter in your template file.
// templates/contact.php
<?= htmlspecialchars($newsletter, ENT_QUOTES); ?>
To replace the variables do the following:
$newsletter = 'Your content to replace';
ob_start();
include('templates/contact.php');
$contactStr = ob_get_clean();
echo $contactStr;
// $newsletter should be replaces by `Your content to replace`
In this way you can build your own template engine.
class Template
{
protected $_file;
protected $_data = array();
public function __construct($file = null)
{
$this->_file = $file;
}
public function set($key, $value)
{
$this->_data[$key] = $value;
return $this;
}
public function render()
{
extract($this->_data);
ob_start();
include($this->_file);
return ob_get_clean();
}
}
// use it
$template = new Template('templates/contact.php');
$template->set('newsletter', 'Your content to replace');
echo $template->render();
The best thing about it: You can use conditional statements and loops (full PHP) in your template right away.
Use this for better readability: https://www.php.net/manual/en/control-structures.alternative-syntax.php
This is a code i'm using for templating, should do the trick
if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
foreach ($m[1] as $i => $varname) {
$template = str_replace($m[0][$i], sprintf('%s', $varname), $template);
}
}
maybe a bit late, but I was looking something like this.
The problem is that include does not return the file content, and easier solution could be to use file_get_contents function.
$template = file_get_contents('test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace("{{nombre}}","Alvaro",$template);
echo $page;
based on #da-hype
<?php
$template = "hello {{name}} world! {{abc}}\n";
$data = ['name' => 'php', 'abc' => 'asodhausdhasudh'];
if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
foreach ($m[1] as $i => $varname) {
$template = str_replace($m[0][$i], sprintf('%s', $data[$varname]), $template);
}
}
echo $template;
?>
Use output_buffers together with PHP-variables. It's far more secure, compatible and reusable.
function template($file, $vars=array()) {
if(file_exists($file)){
// Make variables from the array easily accessible in the view
extract($vars);
// Start collecting output in a buffer
ob_start();
require($file);
// Get the contents of the buffer
$applied_template = ob_get_contents();
// Flush the buffer
ob_end_clean();
return $applied_template;
}
}
$final_newsletter = template('letter.php', array('newsletter'=>'The letter...'));
<?php
//First, define in the template/body the same field names coming from your data source:
$body = "{{greeting}}, {{name}}! Are You {{age}} years old?";
//So fetch the data at the source (here we will create some data to simulate a data source)
$data_source['name'] = 'Philip';
$data_source['age'] = 35;
$data_source['greeting'] = 'hello';
//Replace with field name
foreach ($data_source as $field => $value) {
//$body = str_replace("{{" . $field . "}}", $value, $body);
$body = str_replace("{{{$field}}}", $value, $body);
}
echo $body; //hello, Philip! Are You 35 years old?
Note - An alternative way to do the substitution is to use the commented syntax.
But why does using the three square brackets work?
By default the square brackets allow you to insert a variable inside a string.
As in:
$name = 'James';
echo "His name is {$name}";
So when you use three square brackets around your variable, the innermost square bracket is dedicated to the interpolation of the variables, to display their values:
This {{{$field}}} turns into this {{field}}
Finally the replacement with str_replace function works for two square brackets.
no, don't include for this. include is executing php code. and it's return value is the value the included file returns - or if there is no return: 1.
What you want is file_get_contents():
// Here it is safe to use eval(), but it IS NOT a good practice.
$contactStr = file_get_contents('templates/contact.php');
eval(str_replace("{{newsletter}}", $newsletterStr, $contactStr));
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).
I'm trying to develop a captcha class for my website everything was doing fine until I tried to embed the image generated with PHP GD inside my subscription form!
Here is the code of my class:
<?php
//captcha.php
header("Content-type: image/png");
class Captcha {
// some attributes bla bla
public function __construct($new_string_length,$new_width_picture,
$new_height_picture,$new_string_color) {
$this->string_length = $new_string_length;
$this->width_picture = $new_width_picture;
$this->height_picture = $new_height_picture;
$this->string_color = $new_string_color;
}
public function getString() {
return $this->string;
}
public function generateRandomString() {
$str = "";
$basket = "abcdefghijklmnopqrstuvwxyz0123456789";
$basket_length = strlen($basket);
srand ((double) microtime() * 1000000);
for($i=0;$i<$this->string_length;$i++) {
$generated_pos = rand(0,$basket_length);
$str_substr = substr($basket,$generated_pos-1,1);
if(!is_numeric($str_substr)) {
// if the character picked up isn't numeric
if(rand(0,1)==1) {
// we randomly upper the character
$str_substr = strtoupper($str_substr);
}
}
$str = $str.$str_substr;
}
$this->string = $str;
}
**public function generatePictureFromString($new_string) {
$root_fonts = '../fonts/';
srand ((double) microtime() * 1000000);
$list_fonts = array('ABODE.ttf','acme.ttf','Alcohole.ttf',
'Anarchistica.ttf','AMERIKAA.ttf');
$image = #imagecreatetruecolor($this->width_picture,$this->height_picture);
$noir = imagecolorallocate($image,0,0,0);
$clr = explode('/',$this->string_color);
$clr = imagecolorallocate($image,$clr[0],$clr[1],$clr[2]);
for($i=0;$i<strlen($new_string);$i++) {
imagettftext($image,rand(($this->height_picture/4.3),($this->height_picture)/4.2),
rand(-45,45),($this->width_picture)/(5*$this->string_length)+($this->width_picture)/($this->string_length)*$i,0.6*($this->height_picture),$clr,
$root_fonts.$list_fonts[rand(0,count($list_fonts)-1)],substr($new_string,$i,1));
}
imagepng($image);
imagedestroy($image);
}**
}
I willingly avoided to show some useless part of the class. The class itself works perfectly when I call the generatePictureFromString(..) method like this:
<?php
//testeur_classe.php
require_once '../classes/captcha.php';
$captcha = new Captcha(5,200,80,"255/255/255");
$captcha->generateRandomString();
$str = $captcha->getString();
$captcha->generatePictureFromString($str);
?>
But when I try to insert the picture generated in my form using:
<img src="<?php echo PATH_ROOT.'classes\testeur_classe.php'; ?>"/>
nothing is displayed!
How am I supposed to do that ?
Thank you!
OK: What do you see if you open classes\testeur_classe.php in the browser?
(p.s. the same question as Ryan Graham asked you in question comment)
OK: I think you must set correct headers before picture output like:
header('Content-type: image/png');
p.s.
This code works, just tried it on my machine. You must have bug on <img src="..." or <base href="" if you have one. Could you show us your html output so we can see what could be the problem?
You need to make sure that the image src is a valid URL to the script. Looking at the backslash in there my guess would be that that is in fact a filesystem path.