PHP pass HTML string to create ZIP archive - php

So I am trying to create a Zip file from 2 strings. 1 is a html string, the other is plain text. So far I only seem to get the text string to work correctly but the file thats supposed to be HTML is just a blank file. Any idea why?
$string1 = $_POST["html_string"];
$string2 = "Some data Some data Some data Some data Some data Some data";
$filename = "test.zip";
$zip = new ZipArchive();
if ($zip->open($filename, ZIPARCHIVE::CREATE)==TRUE) {
$zip->addFromString("string1.html", $string1);
$zip->addFromString("string2.txt", $string2);
$zip->close();
}
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
//clearstatcache();
header("Content-Length: ".filesize($filename));
readfile($filename);
unlink($filename);
Thanks for any help.

Tryed your code replacing
$string1 = $_POST["html_string"];
with
$string1 = '<html>
<title></title>
</html>';
and worked.
Are you sure $_POST["html_string"] is not empty? Add var_dump($_POST); to see if there is some data or update your code adding a check at the begining.
if (empty($_POST["html_string"]))
{
echo 'html_string is empty';
exit;
}

Related

Save formated xml to file in PHP

I know that there are a ton of questions about this here but every answer i tried didn't fixed my problem
Problem
I have xml saved on a string and i want so save it to a file but don't want the xml to be in a single line i want to write to the file in pritty print
Also there is a bigger problem with this the instead of the this " it shows this " since this file will be loaded in a diferent website i can't have "
Note that the $content variable has " not "
I know that \n doesn't matter but to make it easier to analize the generated xml file i need the xml to be formated
this is what i am using
$dirname = "temp/" . uniqid();
mkdir($dirname);
$filename = $dirname . "/gen.xml";
$doc = new DomDocument($content);
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->save($filename);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=gen.xml");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
readfile($filename);
$fh = fopen($filename, 'a');
fclose($fh);
unlink($filename);
rmdir($dirname);
I also tried
header("Content-type: text/xml");
and
file_put_contents
DomDocument's constructor does not accept an xml string - rather, an optional version and encoding.
What you probably want is to load your $content xml string instead:
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->loadXML($content);
$doc->save($filename);

How to create a text file through PHP and download the text file in user computer

I have tried several option but the text file saves in root server correctly but I want user to download the text file and save in his computer. I have got the download result by using
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename={$file}");
It downloads the whole script in user computer instead of only "text" result $textToWrite, which I want to download. Code I have tried are as follows:
$textToWrite = "$cdacode"."$cda_name"."$subofcode"."$subofname"."$name_payee"."$acno2"."$ifsc"."$micr_cd"."$act_type"."$pay_amt"."00"."DV NO"."$pmt_ref_no"."$paybydate"."$vendcode"."$vend_add"."$bill_num"."$billdate"."$narration"."$emailid"."$mob_num"."$addn_field";
$file= "$cmpno.txt" ;
$current .= "$textToWrite";
file_put_contents($file, $current);
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename={$file}");
Try this:
$textToWrite = "$cdacode"."$cda_name"."$subofcode"."$subofname"."$name_payee"."$acno2"."$ifsc"."$micr_cd"."$act_type"."$pay_amt"."00"."DV NO"."$pmt_ref_no"."$paybydate"."$vendcode"."$vend_add"."$bill_num"."$billdate"."$narration"."$emailid"."$mob_num"."$addn_field";
$file= "$cmpno.txt" ;
$current .= "$textToWrite";
file_put_contents($file, $current);
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename={$file}");
readfile($file);
As per my comments: as far as I can see, there are two issues with the code:
You have no opening PHP tag, and I wonder if you are just serving this script as text
You're pointlessly writing a file and then doing nothing with it
Try this code:
<?php
// #todo This rather needs tidying up
$textToWrite = "$cdacode"."$cda_name"."$subofcode"."$subofname".
"$name_payee"."$acno2"."$ifsc"."$micr_cd"."$act_type".
"$pay_amt"."00"."DV NO"."$pmt_ref_no"."$paybydate"."$vendcode".
"$vend_add"."$bill_num"."$billdate"."$narration".
"$emailid"."$mob_num"."$addn_field";
$file= "$cmpno.txt";
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename={$file}");
echo $textToWrite;
As per my comments the string is in a bit of a mess - try this first to see if we're on the right track, and if this broadly works, I'll show you how to tidy it up.

Send an array to an Excel file using PHP

I want to send an array to Excel file, this is an array containing different categories.
Each categories should go into one column. The code I have written was sending all the values to one field on Excel. Where am I getting it wrong?
$shop['id']=$id_array;
$shop['name']=$name_array;
$shop['cat1'] = $cat1;
$shop['cat2'] = $cat2;
$shop['cat3'] = $cat3;
$id_excel=implode(",",$shop['id']);
$name_excel=implode(",",$shop['name']);
$cat1_excel=implode(",",$shop['cat1']);
$cat2_excel=implode(",",$shop['cat2']);
$cat3_excel=implode(",",$shop['cat3']);
}
$filename ="cat.xls";
$contents = "$id_excel \t $name_excel \t $cat1_excel \t $cat2_excel \t $cat3_excel \t \n";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.$filename);
echo $contents;
Try to use this nice plugin: PHPExel
With this plugin it's simple
Please try to return a CSV file instead of Excel. Here is the code:
<? $shop['id']=$id_array;
$shop['name']=$name_array;
$shop['cat1'] = $cat1;
$shop['cat2'] = $cat2;
$shop['cat3'] = $cat3;
$id_excel[]=implode(",",$shop);
$filename ="cat.csv";
$contents = implode("\n",$id_excel);
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $contents;
?>

PHP readfile() returning corrupted data

In my function I am saving an image decoded from a base64 string:
function saveImage(){
//magic...
define('UPLOAD_DIR', '../webroot/img/');
$base64string = str_replace('data:image/png;base64,', '', $base64string);
$base64string = str_replace(' ', '+', $base64string);
$data = base64_decode($base64string);
$id = uniqid();
$file = UPLOAD_DIR.$id.'.png';
$success = file_put_contents($file, $data);
}
The above function works properly and the images are saved and not corrupted in the specified folder.
In the next function I am now trying to force download the image to a user:
function getChart($uniqid= null){
if($uniqid){
$this->layout = null;
header("Content-type: image/png");
header("Content-Disposition:attachment;filename='".$uniqid.".png'");
readfile('../webroot/img/'.$uniqid.'.png');
exit;
} else exit;
}
Image downloaded from the server is corrupted and cant be displayed. After opening the downloaded file in a text editor I noticed that a new line character is added at the very top. After deleting the character and saving the file it opens properly and is being displayed properly.
How can I fix this?
What you describe can have multiple issues that are hidden until you actually open the downloaded file.
Instead make your code more robust and check pre-conditions, here if headers have been send already and to clean any possible existing output buffer and give error if that is not possible:
function getChart ($uniqid = null) {
if (!$uniqid) exit;
$this->layout = null;
if (headers_sent()) throw new Exception('Headers sent.');
while (ob_get_level() && ob_end_clean());
if (ob_get_level()) throw new Exception('Buffering is still active.');
header("Content-type: image/png");
header("Content-Disposition:attachment;filename='".$uniqid.".png'");
readfile('../webroot/img/'.$uniqid.'.png');
exit;
}
header("Content-length: $file_size")
This header tells the browser how large the file is. Some browser need it to be able to download the file properly. Anyway it's a good manner telling how big the file is. That way anyone who download the file can predict how long the download will take.
header("Content-type: $file_type")
This header tells the browser what kind of file it tries to download.
header("Content-Disposition: attachment; filename=$file_name");
This tells the browser to save this downloaded file under the specified name. If you don't send this header the browser will try to save the file using the script's name.
BUT you need to flush buffer, with flush(); or in your case with ob_flush(); right above first exit;
check if you are outputing something before calling readfile:
// add ob_start() at the very top of your script
function getChart($uniqid= null){
echo strlen(ob_get_clean()); die(); // if it's not 0 then you are definetly echoing something
if($uniqid){
$this->layout = null;
header("Content-type: image/png");
header("Content-Disposition:attachment;filename='".$uniqid.".png'");
readfile('../webroot/img/'.$uniqid.'.png');
exit;
} else exit;
}
EDIT (to force download):
function getChart($uniqid= null){
if($uniqid){
$image = $uniqid;
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=" . $image);
header("Content-Type: image/jpg");
header("Content-Transfer-Encoding: binary");
readfile($image);
} else exit;
}
getChart("060620121945.jpg");
Try this (just to render image):
function getChart($uniqid= null){
if($uniqid){
$mime_type = "image/png";
$content = file_get_contents('../webroot/img/'.$uniqid.'.png');
$base64 = base64_encode($content);
return ('data:' . $mime_type . ';base64,' . $base64);
} else exit;
}
I have had this problem several times. Here's the solution that I used:
Almost always it turned out that I had forgotten to turn off unicode BOM encoding in my download.php file which adds something to the front of the downloaded file and therefore corrupts it.
So the solution is to turn off unicode BOM in download.php.
Just use ob_clean(); before readfile()

How to echo raw post data in PHP?

My goal is to simply echo $_POST['imageVar']; back with content headers as a quick and dirty means to "export" an image from a flash application. I saw an example of this as follows, but it does not work with my php version/config:
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=".$_GET['name']);
echo $jpg;
}
So as a work around I created a script that saves the image to the server, reads the image and echos it back, then deletes the image. I don't like this approach as I need to have a directory that is writable by the apache user (im on a shared server). Is there a way to accomplish what I am doing here without hte need to use the temp file?
<?
$fileName = basename( $_FILES['uploadedfile']['name']);
$tempFile = "uploads/" . $fileName;
$fileSize = $HTTP_POST_FILES['uploadedfile']['size'];
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $tempFile)) {
        $fh = fopen($tempFile, 'r');
        $fileContents = fread($fh, $fileSize);
        header('Content-Type: image/jpeg');
        header("Content-Disposition: attachment; filename=$fileName");
        echo $fileContents;
        fclose($fh);
        unlink($tempFile);
} else {
        echo "upload fail";
}
?>
Any input or ideas greatly appreciated! Thanks for looking
You can just use:
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=$fileName")
readfile($_FILES['uploadedfile']['tmp_name']);
No need to move it if you're not going to keep it.
On a side note, regarding the first solution you were looking at, does an echo file_get_contents('php://input'); not work?
$s = file_get_contents('php://input');
// add headers for download dialog-box
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=".$_GET['name']);
echo $s;
What about that?

Categories