PHP : insert executable php code in HTML - php

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!

Related

Can I edit a script to rerun based on url/field input?

I have a script that gets a streams link based on the external html page.
Is there a way to have one script and a resourced page with links to all the external links or do I need to have an individual page per request?
In other words, can I do this
example.com/videos.php?v=1234
or must I use
example.com/eachVideoPage.php
Here is the script I use to get the link.
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/xmpegURL");
?>
<?php
ob_start(); // ensures anything dumped out will be caught
$html = file_get_contents("http://example.com/aVideoPage.html");
preg_match_all(
'/(http:\/\/[^"].*?\.mp4)[",].*?/s',
$html,
$posts, // will contain the article data
PREG_SET_ORDER // formats data into an array of posts
);
foreach ($posts as $post) {
$link = $post[1];
// clear out the output buffer
while (ob_get_status())
{
ob_end_clean();
}
// no redirect
header("Location: $link");
}
?>
Assuming all you want to do is change the file_get_contents() URL It should be as simple as:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/xmpegURL");
$vid = htmlspecialchars($_GET["v"]);
ob_start(); // ensures anything dumped out will be caught
$html = file_get_contents("http://example.com/$vid/aVideoPage.html");
preg_match_all(
'/(http:\/\/[^"].*?\.mp4)[",].*?/s',
$html,
$posts, // will contain the article data
PREG_SET_ORDER // formats data into an array of posts
);
foreach ($posts as $post) {
$link = $post[1];
// clear out the output buffer
while (ob_get_status())
{
ob_end_clean();
}
// no redirect
header("Location: $link");
}
?>
Updates:
$vid = htmlspecialchars($_GET["v"]);
Using _GET will take the URL Query parameters and do whatever you want with them. In this case a basic value assignment looking for ?v=123 in the URL. ($vid === '123')
It is worth mentioning that you should add some code to handle cases where ?v does not exists, or contains malicious input (depending on who uses it)
Then just reuse the value in the URL you want to call:
$html = file_get_contents("http://example.com/$vid/aVideoPage.html");
Update after comments
In order to call another site with a query string you can simply append it to the URL:
$html = file_get_contents("http://example.com/aVideoPage.html?v=$vid");
This will depend entirely on the remote site you are calling however. .html files usually won't do anything with query strings unless there is JavaScript in the code that uses it. But generally if you can browse to the remote URL with ?v=1234 in the URL and it selects the right video, then the above should also work.

Is it possible to change original html text in php?

I am trying to make "manner friendly" website. We use different declination dependent on gender and other factors. For example:
You did = robili
It did = robilo
She did = robila
Linguisticaly this is very simplified (and unlucky) example! I would like to change html text in php file where appropriate. For example
<? php
something
?>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^</div>
<? php something ?>
Now I would like to replace all occurences of different tokens ^characters|characters|characters^ and replace them by one of their internal values according to "gender".
It is easy in javascript on the client side, but you will see all this weird "tokenizing" before javascript replace it.
Here I do not know the elegant solution.
Or do you have better idea?
Thanks for advice.
You can add these scripts before and after the HTML:
<?php
// start output buffering
ob_start();
?>
<html>
<body>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^, but also vital^si|sa|ste^, borko^mal|mala|malo^ </div>
</body>
</html>
<?php
$use = 1; // indicate which declination to use (0,1 or 2)
// get buffered html
$html = ob_get_contents();
ob_end_clean();
// match anything between '^' than's not a control chr or '^', min 5 and max 20 chrs.
if (preg_match_all('/\^[^[:cntrl:]\^]{3,20}\^/',$html,$matches))
{
// replace all
foreach (array_unique($matches[0]) as $match)
{
$choices = explode('|',trim($match,'^'));
$html = str_replace($match,$choices[$use],$html);
}
}
echo $html;
This returns:
html text of the page and somewhere is the word "robil" we tried to
robilo, but also vitalsa, borkomala

insert file containing php code into a variable as string

I have this:
ob_start(); ?>
<div class="" id="loading">
<?php echo file_get_contents($page["texto"]) ?>
</div> <?php
$content = ob_get_clean();
But I would like to have that template html in a separate file, just like:
$content = file_get_contents('cms/template.php');
Now this won't work because it has php tags inside and when retrieving the string it gets as
how can I achieve this without using a dirty hack like:
$pre = file_get_contents('part1');
$var = file_get_contents($page["texto"]);
$post = file_get_contents('part2');
And adding all them...
It's still hack, but unless you use a templating system like Twig you have no choice:
ob_start();
include 'cms/template.php';
$content = ob_get_clean();
echo $content;
ob_start enables output buffering so nothing gets sent to the browser. We then include the file which will execute PHP normally. We then use ob_get_clean to get the contents of the output buffer (which is your template file). and disable the output buffer, discarding it's contents, as we have the contents in $content.

Save the contents of manipulated div to a variable and pass to php file

I have tried to use AJAX, but nothing I come up with seems to work correctly. I am creating a menu editor. I echo part of a file using php and manipulate it using javascript/jquery/ajax (I found the code for that here: http://www.prodevtips.com/2010/03/07/jquery-drag-and-drop-to-sort-tree/). Now I need to get the edited contents of the div (which has an unordered list in it) I am echoing and save it to a variable so I can write it to the file again. I couldn't get that resource's code to work so I'm trying to come up with another solution.
If there is a code I can put into the $("#save").click(function(){ }); part of the javascript file, that would work, but the .post doesn't seem to want to work for me. If there is a way to initiate a php preg_match in an onclick, that would be the easiest.
Any help would be greatly appreciated.
The code to get the file contents.
<button id="save">Save</button>
<div id="printOut"></div>
<?php
$header = file_get_contents('../../../yardworks/content_pages/header.html');
preg_match('/<div id="nav">(.*?)<\/div>/si', $header, $list);
$tree = $list[0];
echo $tree;
?>
The code to process the new div and send to php file.
$("#save").click(function(){
$.post('edit-menu-process.php',
{tree: $('#nav').html()},
function(data){$("#printOut").html(data);}
);
});
Everything is working EXCEPT something about my encoding of the passed data is making it not read as html and just plaintext. How do I turn this back into html?
EDIT: I was able to get this to work correctly. I'll make an attempt to switch this over to DOMDocument.
$path = '../../../yardworks/content_pages/header.html';
$menu = htmlentities(stripslashes(utf8_encode($_POST['tree'])), ENT_QUOTES);
$menu = str_replace("<", "<", $menu);
$menu = str_replace(">", ">", $menu);
$divmenu = '<div id="nav">'.$menu.'</div>';
/* Search for div contents in $menu and save to variable */
preg_match('/<div id="nav">(.*?)<\/div>/si', $divmenu, $newmenu);
$savemenu = $newmenu[0];
/* Get file contents */
$header = file_get_contents($path);
/* Find placeholder div in user content and insert slider contents */
$final = preg_replace('/<div id="nav">(.*?)<\/div>/si', $savemenu, $header);
/* Save content to original file */
file_put_contents($path, $final);
?>
Menu has been saved.
To post the contents of a div with ajax:
$.post('/path/to/php', {
my_html: $('#my_div').html()
}, function(data) {
console.log(data);
});
If that's not what you need, then please post some code with your question. It is very vague.
Also, you mention preg_match and html in the same question. I see where this is going and I don't like it. You can't parse [X]HTML with regex. Use a parser instead. Like this: http://php.net/manual/en/class.domdocument.php

TCPDF ERROR: Some data has already been output, can't send PDF file

I keep receiving this error when trying to add my own array into the code.
Here is my array;
$array = array();
while (odbc_fetch_row($rs))
{
$array[] = odbc_result($rs,'Product Name');
}
$test = print_r($array);
The original code is here. I'm using an example page to try it because I know the example page works fine.
http://www.tcpdf.org/examples/example_001.phps
This code is before the $html variable and when it is set I just add the $test variable into the $html variable. The odbc connection works fine and the example works fine before I add any code but when I run the script I get this error;
Array ( [0] => Test1 [1] => Test2 ) TCPDF ERROR: Some data has already been output, can't send PDF file
And there is also more than 2 items in the Array. Any ideas?
Add the function ob_end_clean(); before call the Output function.
It worked for me within a custom Wordpress function!
ob_end_clean();
$pdf->Output($pdf_name, 'I');
Just use ob_start(); at the top of the page.
Add the function ob_end_clean() before call the Output function.
I just want to add that I was getting this error, and nothing would fix it until I changed the Output destination parameter from F to FI.
In other words, I have to output to both file and inline.
Output('doc.pdf', 'I')
to
Output('doc.pdf', 'FI')
I have no idea why this made the difference, but it fixed the error for me...
This problem means you have headers. Deletes tags
?>
at the end of your code and make sure not to have whitespace at the beginning.
The tcpdf file that causes the "data has already been output" is in the tcpdf folder called tcpdf.php. You can modify it:
add the line ob_end_clean(); as below (3rd last line):
public function Output($name='doc.pdf', $dest='I') {
//LOTS OF CODE HERE....}
switch($dest) {
case 'I': {
// Send PDF to the standard output
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
//some code here....}
case 'D': { // download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
break;}
case 'F':
case 'FI':
case 'FD': {
// save PDF to a local file
//LOTS OF CODE HERE..... break;}
case 'E': {
// return PDF as base64 mime email attachment)
case 'S': {
// returns PDF as a string
return $this->getBuffer();
}
default: {
$this->Error('Incorrect output destination: '.$dest);
}
}
ob_end_clean(); //add this line here
return '';
}
Now lets look at your code.
I see you have $rs and $sql mixed up. These are 2 different things working together.
$conn=odbc_connect('northwind','****','*****');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT * FROM products"; //is products your table name?
$rs=odbc_exec($conn,$sql);
if (!$rs) {
exit("Error in SQL");
}
while (odbc_fetch_row($rs)) {
$prodname=odbc_result($rs,"Product Name"); //but preferably never use spaces for table names.
$prodid=odbc_result($rs,"ProdID"); //prodID is assumed attribute
echo "$prodname";
echo "$prodid";
}
odbc_close($conn);
now you can use the $prodname and output it to the TCPDF output.
and I assume your are connecting to a MS access database.
Use ob_start(); at the beginning of your code.
for my case Footer method was having malformed html code (missing td) causing error on osx.
public function Footer() {
$this->SetY(-40);
$html = <<<EOD
<table>
<tr>
Test Data
</tr>
</table>
EOD;
$this->writeHTML($html);
}
I had this but unlike the OP I couldn't see any output before the TCPDF error message.
Turns out there was a UTF8 BOM (byte-order-mark) at the very start of my script, before the <?php tag so before I had any chance to call ob_start(). And there was also a UTF8 BOM before the TCPDF error message.
I had this weird error
and the culprit is a white space on the beginning of the PHP open tag
even without the ob_flush and ob_end_clean
Just make sure there are no extra white spaces on or after any <?php ?> block
use
ob_end_clean();
$pdf->Output($file, 'I');
to open pdf.
It works for me
I had the same error but finally I solved it by suppressing PHP errors
Just put this code error_reporting(0); at the top of your print page
<?php
error_reporting(0); //hide php errors
if( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tohtml/tcpdf/tcpdf.php';
.... //continue
The error of "Some data has already been output, can't send PDF file" refers to the output buffer of PHP.
so you need to clean any content of the output buffer before sending output.
ob_end_clean(); // Clean any content of the output buffer
then
$pdf->Output('example_001.pdf', 'I'); // Send the PDF !
This problem is when apache/php show errors.
This data(html) destroy pdf output.
You must off display errors in php.ini.
For those who are still facing this issue try adding:
libxml_use_internal_errors(true);
before the loadHtml call and add
libxml_use_internal_errors(false);
after the call.
This solved it for me.

Categories