Is there any other method to output variable content in php? - php

I did a setup of scssphp in my framework and made it working with multiple files. Below is the code of how it output itself as text/css.
<?php header('Content-type: text/css');
ob_clean();
function scss_css() {
require "../SCSS-PHP/scss.inc.php";
$import_way = "../styles/scss/";
$compression = "scss_formatter_compressed";
$compiler_script = '#import "demo.scss"';
$scss = new scssc();
$scss->setImportPaths($import_way);
$scss->setFormatter($compression);
echo $scss->compile($compiler_script);
}
scss_css();
die();
?>
The call i used in html is:
<link rel="stylesheet" href="binder/loader.scss.php">
I would like to know if echo is safe for my future working scss setup. Can there be any attack on such a file output and any other suggestions to make it better?

Related

CSS doesn't want to include in file

Im setting up a xampp php website with auto creating css for site (If site named xyz.php/html is created, then a css is created too). Unfortunatelly css doesn't want to include in website using php echo's and html tags. No error.
In style.php:
$arr = explode("/",$_SERVER['PHP_SELF']);
$style = "";
foreach ($arr as $key){
if(strpos($key, ".php")){
$style = str_replace(".php", "style.css", $key);
}
}
if($fp = fopen($_SERVER['DOCUMENT_ROOT']."/TestPHP/".$addr,"wb+")){
fwrite($fp,"body{background-color:#666;}");
fclose($fp);
}
echo $addr = "lib/require/styles/".$style;
echo '<link href="'.$addr.'" rel="stylesheet">';
In index.php:
require_once 'lib/require/php/styles.php';
That's because the only HTML (as i can see in your code) doesn't have anything else than the style, no head, no body... Why don't you directly paste the HTML inside the file instead of making PHP echo it?

using php in css ,substr_count() seach file location

i have some question about php in css
my projet folde
What i'm trying to do : count <li> with php in css
Probleme : cannot find the right location
more information : <link rel="stylesheet" href="./css/style.php"> in my "head.php"
in my style.php
<?php
header("Content-type: text/css; charset: UTF-8");
$menu="../index.php";
$li=substr_count($menu,"<li>");
echo $menu;
?>
i tried "../index.php"; "../inc/menu.php"; "./inc/menu.php";
no one work
you can try something like this
$menu = file_get_contents('../index.php');
$liCount = substr_count($menu,'<li>');
echo $liCount;

Reading a php file from another php file

I currently have a php file that I'm using as a template but I need it to read in data from another php file that I'm using for the page content. I'm doing it this way to save on code and time, however it doesn't appear to be working. I have done a test with shorter amounts of code but it still isn't working. they are both .php files.
Code -
<html>
<head>
<title></title>
</head>
<body>
<?php
$temp = 'test-2.php';
$file = fopen($temp, 'r');
$cont = fread($file, filesize($temp));
print $cont;
fclose($file);
?>
</body>
test-2.php
<?php
echo 'hello world';
?>
just use <?php include('test-2.php'); ?> surely that'll do what you want?

Tool for exporting html as pdf

I have a html document which marks up a report. I have a button on this page "Export as pdf". However I am not sure how to export html into a pdf..Are there any tools out there that anyone recommends for such a task..
EDIT: In more detail:
I have the following php:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
$sectionTwo = array();
$sectionThree = array();
$sectionFour = array();
$sectionFive = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$section = $row['sectionId'];
switch($section){
case '1':
$sectionOne[] = $row;
break;
case '2':
$sectionTwo[] = $row;
break;
case '3':
$sectionThree[] = $row;
break;
case '4':
$sectionFour[] = $row;
break;
case '5':
$sectionFive[] = $row;
break;
default:
break;
}
}
}else{
//error - sql failed
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
Export as PDF
</div>
<h3>Biological Information</h3>
<?php
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
?>
<h3>Fatigue and Recovery</h3>
<?php
foreach($sectionTwo as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Illness and Injury</h3>
<?php
foreach($sectionThree as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Training Sessions</h3>
<?php
foreach($sectionFour as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>General Feedback</h3>
<?php
if(count($sectionFive)>0){
foreach($sectionFive as &$value){
echo($value['question'].' : '.$value['answer']);
}
}else{
echo("User didn't leave any feedback");
}
echo("<br/>");
?>
</body>
</html>
<?php
}
?>
This displays the following:
So if I'm using fpdf, what is the best way to export the following as a pdf? Should I write a fpdf function in the same php file or is it best to write a separate php file which creates and displays the pdf (which means I would have to post all relevant data to this file)...
Use FPDF library for php
check here
The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.
<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:
$pdf=new FPDF('P','mm','A4');
It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).
Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().
To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:
$pdf->SetFont('Arial','B',16);
We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:
$pdf->Cell(40,10,'Hello World !',1);
Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.
I've found this software quite useful: http://code.google.com/p/wkhtmltopdf/
It is true that you'll have to exec() it from your code, but it works very good and uses webkit as the backend engine (allowing javascript also, and many other features to customize the pdf creation), saving a lot of code.
Hope it helps, we're using it here and it works like a charm.
EDIT: try the static binaries. untar and ready to go :)
You may also use an online tool Pdfcrowd API
Its easy to integrate and provides much in its free edition. You may check
PDFCrowd Official Site
require 'pdfcrowd.php';
// create an API client instance
$client = new Pdfcrowd("username", "apikey");
// convert a web page and store the generated PDF into a variable
$pdf = $client->convertURI('http://www.google.com/');
//You can also convert raw HTML code, just use the convertHtml() method instead of convertURI()
$pdf = $client->convertHtml("<body>My HTML Layout</body>");
//Or use convertFile() to convert a local HTML file
$pdf = $client->convertFile("/path/to/MyLayout.html");
// set HTTP response headers
header("Content-Type: application/pdf");
header("Cache-Control: no-cache");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"google_com.pdf\"");
// send the generated PDF
echo $pdf;
Another much easier way is with HTML2FPDF.
HTML2FPDF is a PHP Class library that uses the FPDF class library to convert HTML files to PDF files. This library consist of three classes namely PDF, HTML2FPDF and FPDF (modified FPDF class). The class PDF extends the class HTML2FPDF that extends the class FPDF.
Now let us see, how to convert a sample html page into a PDF file using HTML2FPDF Library. The html page contains a table that lists a few nations with their corresponding national flags. Below is the code for the conversion.
<?
require('html2fpdf.php');
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen("sample.html","r");
$strContent = fread($fp, filesize("sample.html"));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output("sample.pdf");
echo "PDF file is generated successfully!";
?>
First, we need to include the html2fpdf.php file that contains the HTML2FPDF class and an object is created using the constructor HTML2FPDF(). Then a new page is added to the pdf document using the function AddPage(). The html contents are read from the sample.html file using file functions. Then the html contents are written in to the pdf format using WriteHTML() function. To view the html file, click here and to view the generated pdf, click here. The above sample code with the sample html file and images and the html2fpdf class libraries can be downloaded here.
The HTML2FPDF class library will be working best with the XHTML 1.0. Also the class does not support all the features available with HTML. To know the supported HTML tags and other features, Please refer http://html2fpdf.sourceforge.net.
I recommend you to use this since it's much easier and friendly.

Methods ob_start and ob_flush don't work, why?

I am using ob_start()/ob_flush() to, hopefully, give me some progress during a long import operation.
Here is a simple outline of what I'm doing:
<?php
ob_start ();
echo "Connecting to download Inventory file.<br>";
$conn = ftp_connect($ftp_site) or die("Could not connect");
echo "Logging into site download Inventory file.<br>";
ftp_login($conn,$ftp_username,$ftp_password) or die("Bad login credentials for ". $ftp_site);
echo "Changing directory on download Inventory file.<br>";
ftp_chdir($conn,"INV") or die("could not change directory to INV");
// connection, local, remote, type, resume
$localname = "INV"."_".date("m")."_".date('d').".csv";
echo "Downloading Inventory file to:".$localname."<br>";
ob_flush();
flush();
sleep(5);
if (ftp_get($conn,$localname,"INV.csv",FTP_ASCII))
{
echo "New Inventory File Downloaded<br>";
$datapath = $localname;
ftp_close($conn);
} else {
ftp_close($conn);
die("There was a problem downloading the Inventory file.");
}
ob_flush();
flush();
sleep(5);
$csvfile = fopen($datapath, "r"); // open csv file
$x = 1;
// skip the header line
$line = fgetcsv($csvfile);
$y = (feof($csvfile) ? 2 : 5);
while ((!$debug) ? (!feof($csvfile)) : $x <= $y) {
$x++;
$line = fgetcsv($csvfile);
// do a lot of import stuff here with $line
ob_flush();
flush();
sleep(1);
}
fclose($csvfile); // important: close the file
ob_end_clean();
However, nothing is being output to the screen at all.
I know the data file is getting downloaded because I watch the directory where it is being placed.
I also know that the import is happening, meaning that it is in the while loop, because I can monitor the DB and records are being inserted.
Any ideas as to why I am not getting output to the screen?
You also need to check the PHP settings
some installs default to 4096, some default to off
output_buffering = Off
output_buffering = 4096
agreed with George but do check the above settings
Make sure that your output buffering doesn't start automatically. Run:
print ob_get_level ();
before ob_start (); if will will see something else then 0 you've got the answer.
Hey man I was also got stuck in this problem
and finally got the correct solution
here it is for you
you have to add content type for your page
you can do that by two ways
1. using html tag
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Ex.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Wp Migration</title>
</head>
<body>
<?php
for($i=0;$i<70;$i++)
{
echo 'printing...<br>';
ob_flush();
flush();
sleep(3);
}
?>
</body>
</html>
using php header function
<?php header( 'Content-type: text/html; charset=utf-8' ); ?>
Ex.
<?php
header( 'Content-type: text/html; charset=utf-8' );
for($i=0;$i<70;$i++)
{
echo 'printing...<br>';
ob_flush();
flush();
sleep(3);
}
?>
All the best
Ob_end_clean() discards the contents of the current output buffer and turns off the buffering.
You should use ob_end_flush() instead.
Add this line
header("X-Accel-Buffering: no");
worked for me.
You can edit it with the .htaccess file
To disable output buffering, modify the line as follows:
php_value output_buffering Off
php_value output_buffering 4096
worked for me. Thank you!
Check this site: Click Here
It's possible that your webserver is doing its own buffering. Probably with something like mod_gzip.
Here is some very simple test code:
<?php
echo 'starting...<br/>';
for($i = 0; $i < 5; $i++) {
print "$i<br/>";
flush();
sleep(2);
}
print 'DONE!<br/>';
If it takes 10 seconds for that page to load, rather than seeing a new line every 2 seconds, then it means that it is being cached by your webserver. For what you are trying to do, there is no need to use ob_start and ob_flush. Just call flush whenever you want to force the content to the browser. However, like I mentioned, if the webserver is waiting for the content to complete before sending, then that won't do anything for you.
Edit: Another possibility is that you're viewing the page from behind a corporate or ISP proxy/firewall that waits for the whole page before serving it (so that it can scan it to see if it looks like pornography, for example).

Categories