How to insert txt file content into twig template - php

Triyng to start opencart shop at first time
At the root of the site I have the file "file.ssi"
How to insert its contents into a twig template? (header.twig)
Why is it important that the file must be at the root and called file.ssi -- I have a script that periodically changes the contents of this file at many of my sites, and on static html sites or wordpress I print content of file.ssi into template with SSI, and how to do it on twig I don't understand
I tried write in header.twig
{{ bla_bla }}
then in catalog\controller\common\header.php
$data['bla_bla'] = sprintf($this->language->get('text_bla_bla'), $this->config->get('config_name'), date('Y', time()));
then in catalog\language\ru-ru\common\header.php
$_['text_bla_bla'] = 'my html code 1';
and this html code prints on the right place.
But when I tried to do something like this
$_['text_bla_bla'] = 'my html code 1' . $bla_bla_bla = file_get_contents('/file.ssi');
echo $bla_bla_bla; . 'my html code 2';
site doesn't even open
I understand the pure php error and my modest knowledge (or rather un-knowledge) php is not enough to get in $ _ ['text_bla_bla'] a couple of pieces of html and the contents of the file between them.
In general, I need to insert something in header.twig, or to solve it somehow with php, I myself do not understand where it was wrong.

This works!
in controller
$data['mydata'] = file_get_contents($path);
in template
{{ mydata }}

It would look like this:
Controller:
$text = file_get_contents($path);
return $this->render('page.html.twig', [
'text' => $text,
]);
Then in your twig template:
{{ text }}

bad syntax:
$_['text_bla_bla'] = 'my html code 1' . $bla_bla_bla = file_get_contents('/file.ssi');
echo $bla_bla_bla; . 'my html code 2';
If you need to use sprinf so in language file you can get this data $this->config->get('config_name'), date('Y', time() using %s %d
$_['text_bla_bla'] = 'my html code 1 %s %d';

Related

PHP : insert executable php code in HTML

I got simple caching script which is saving php code into HTML. Everything works fine, but I need to add dynamic tracking code into every saved HTML by including a script from another file with include() statement
....
$s_getdata = http_build_query( array(
'cat' => 'CAT1',
'buffit'=>'TRUE',
)
);
$s_page = file_get_contents('http://example.com/buffer.php?'.$s_getdata);
ob_start();
echo $s_page;
file_put_contents('./index.html', ob_get_contents());
ob_end_clean();
I tried to add this code before ob_start, but it just add code as simple text in string (not working) :
$s_page .= '<?php include("./tr/in.php"); ?>';
Any idea how to do it ? Thanks!
You can do this by 2 ways,
Option 1: return value as a function from the in.php file,
your in.php file code,
function dynatrack() {
// your dynamic tracking code generation here
return $code; // where $code is your dynamic tracking code
}
Your original file,
$s_page = file_get_contents('http://example.com/buffer.php?'.$s_getdata);
include("./tr/in.php");
$s_page .= dynatrack();
Option 2: Get the contents of the in.php file by using file_get_contents again,
$s_page = file_get_contents('http://example.com/buffer.php?'.$s_getdata);
$s_page .= file_get_contents('./tr/in.php');
I hope this helps!

Retrieve HTML from database, and format it as html instead of plain text

I have a database query that returns the raw HTML for a page, but if I use it on my page, it gets shown as plain text (of course). How would I format it as HTML so that it uses the tags and such.
An example of what I have in my database:
<div class="test">SOME TEXT HERE</div>
But it is also displayed like that. I would like it to format the text as if it was HTML. So it would just display:
SOME TEXT HERE
But that it would also be in a div with the class: "test"
What would be the best approach to reach this goal?
Im using Twig in the MVC model to render the page. So the page renderer is like this
public function renderArticle() {
$twig = new TwigHelper();
$args['title'] = "Artikel $this->articleId";
$args['blogHTML'] = BlogController::retrieveBlogHTML($this->articleId);
echo $twig->render('article.twig', $args);
}
And the "BlogController::retrieveBlogHTML" goes like this:
public static function retrieveBlogHTML($id) {
$db = DatabaseHelper::get();
$st = $db->prepare("SELECT PageHTML FROM T_Blog WHERE BlogId = :BlogId");
$st->execute([
':BlogId' => $id,
]);
if ($st->errorCode() !== \PDO::ERR_NONE) {
return null;
}
return $st->fetchAll();
}
This means that I will not be able to use JavaScript at this point in time, if that will be the only way to fix the problem i'll have to build a workaround.
So I dont know if I accidently escape too or something along those lines, but im not using any headers.
You need to escape the html characters (so < becomes < for example).
In javascript you can use the HE library or theres this function, which is generally fine, but doesn't cover all possible cases that the HE library does
var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
If your using php you can use htmlentities, other languages will have a similar function either inbuilt or provided via a library.

how to pass multiple variable to html template Using PhpMailer?

I want to pass multiple variable to Mail template page and echo to that page using phpmailer library.
I have two variables to pass welcome.php page and echo there.
$name = 'example';
$email = 'example#mail.com';
I have use this code
$mail->MsgHTML(str_replace('[emailhere]', $email, file_get_contents('welcome.php')), dirname(__FILE__));
You can send arrays to str_replace to replace multiple values.
For example:
$message = str_replace(
array(
'[emailhere]',
'[namehere]'
),
array(
$email,
$name
),
file_get_contents('welcome.php')
);
By the way, you should probably not give your template a php extension as it will parse any php if you call or include it directly. So that could be a security risk if users can modify templates.
You may use output buffering.
Echo variables on your template file ($template):
for ex:
<p><?=$name?></p>
Then include it and pass through output buffering
ob_start(); //Start output buffering
include('welcome.php'); //include your template file
$template = ob_get_clean(); //Get current buffer contents and delete current output buffer
$mail->msgHTML($template); // Add html content into your PHP MAILER class

How to replace code between the specific tags and apply php eval on it

I have a variable which calls content from database, sample is below
$content = '<div><h1>content here</h1>
<img src = 'image.jpg' /><br />
[code]echo 'welcome';[/code]
<h2>some content here</h2>
<p> some large content here</p>
[code]echo 'Click Here';[/code]
Thank you.';
echo 'headers here' .$content . 'footers here';
how can i execute PHP for the content in between [code] and [/code] tags?
remaining text would written as html execpt the codes used in [code] some php code [/code] tags
If this is for a templateting type of system for your site I would suggest to go a different route.
First your above code would change so that the portion between you code would look like:
[code]{{msg}}}[/code]
Now, you can still store your stuff in the database as php code if you want, but it makes more sense to eval it before you put it into the database, but I strongly suggest otherwise and go with a find/replace system.
Now, you would want to have a function that would do the following:
function output_template( $name, $data ) {
$template_string = get_template_from_db( $name );
for( $data as $k )
{
$template_string = str_replace( $k, $data[$k], $template_string );
}
return $template_string;
}
Then you can echo out the return value of this function. If you think you need to use eval, rethink what you are doing, especially for what appears to be a templating system.

Can (should) I use PHP to alter HTML page before serving, based on class attribute values

I'd like an easy way for content contributors with limited coding experience to designate the expiration date for selected content on existing HTML (PHP) pages on our site. I'd prefer to remove the content server-side so it isn't still available in the source code.
Illustration of a potential solution I am mulling over:
<div class="story"> ... </div>
Let's say I'd like the above div and its contents to disappear starting on June 1, 2011. So I would add a value to the class attribute:
<div class="story disappears-20110601"> ... </div>
Then I would have to write some code (xpath?) to locate all elements that have a class value with a pattern like ="... disapears-YYYYMMDD". If the date reference is valid, and that date is today or earlier, the code would remove the entire div and its contents from the DOM, and then serve the page without the expired div.
Before I try to set this up, what do you think of the concept? Is it feasible? If implemented sitewide, would it be a horrible resource hog?
A much better way is to store the content in a database table and assign the expiration date via a DATETIME field. Using a css class for this is a little square-peg.
Here is code for you:
<?php
$content = <<<EOF
<div>
some text 1
<div class="story disappears-20110101"> 20110101 </div>
<div class="story disappears-20110601"> 20110601 </div>
some text 2
</div>
EOF;
$doc = new DOMDocument();
$doc->loadHTML($content);
$xpath = new DOMXPath($doc);
$expired = $xpath->query('//*[contains(#class, \'disappears-\')]');
$remove = array();
foreach ($expired as $n)
if (preg_match('~disappears-(\d{4})(\d{2})(\d{2})~', $n->getAttribute('class'), $m))
if (time() > mktime(0, 0, 0, $m[2], $m[3], $m[1]))
$remove[] = $n;
foreach ($remove as $n)
$n->parentNode->removeChild($n);
echo $doc->saveHTML();
Have a nice day.
Well, you could do that using Regexp, but I assume it /could/ (doesn't meant it will) get a little bit messy. I suggest using a database if you have access to one, if not store the stories into separate files (in one directory) and then load/delete/edit them via file-name.
Doing that through HTML would be unpleasant, in my opinion.
EDIT:
<?php
$html_content = file_get_contents('...');
preg_match('/class="story disappears-(\d*)"/i', $html_content, $match_array)
foreach($match_array as $val) {
if (intval($val) < intval(date('Ymd'))) {
$new_html_content = preg_replace('/(<div class="story disappears-'. $val .'">.*<\/div>)/', '', $html_content);
echo $new_html_content;
}
}
?>
Just a side note, you should try debugging this first, I might've done some mistake since I didn't use php in a while. However, if you stumble upon any errors, let me know in the comments, so I can update the code.
I mean there has to be a database available. Even if the pages are hand-coded, you can have them upload each page to your server, and have the back-end create a database entry that correlates to the uploaded page. this database entry could store info about the uploaded page such as the expire date. This also makes it easier organize/serve the page.
This XPath 1.0 will select the desired elements:
//*[
20110601
>=
substring-before(
substring-after(
concat(
' ',
normalize-space(#class),
' '
),
' disappears-'
),
' '
)
]

Categories