<?php
// // $bin = pack("S", 65535);
// // $ray = unpack("S", $bin);
// $ray = pack("H*hex", $data);
// print_r($ray);die();
// echo "UNSIGNED SHORT VAL = ", $ray[1], "\n";
$file = file_get_contents("C:\\Users\\qwerty\Downloads\\image001.jpg", true);
// $file = file_get_contents("C:\\Users\\qwerty\\Downloads\\request.pdf", true);
$data = '0x'.unpack('H*hex', $file)['hex'];
header('Content-Description: File Transfer');
header("Content-Transfer-Encoding: Binary");
// header('Content-Disposition: attachment; filename="request.pdf');
header('Content-Disposition: attachment; filename="image001.jpg');
header('Cache-Control: must-revalidate');
header('Content-Length: 80685');
echo $data;
?>
I want am trying to create File from unpacking the same file. I am recreating this from my other function that unpacks a file stores the data in database and recreate the file again using the data. The above is my sample demo for the bigger function. What it does is unpack file content then echo again. Problem is the downloaded file (image or pdf) cant be opened. Any idea is appreciated
I think I saw the problem when I opened the file in notepad it has a newline before the image data how can I make sure there will be no new line in before the data?
Related
when i download a CSV file on Firefox browser then detect it is Zip file (must be CSV)
I want to it is CSV file.
this is my the code
<?php
$filename = 'example.csv';
header('Cache-Control: public');
header('Pragma: public');
header('Content-Type: application/csv; name="' . $filename. '"');
header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename));
$th = array();
$th[] = "名前";
mb_convert_variables('SJIS','UTF-8',$th);
$out = fopen('php://output', 'w');
fputcsv($out, $th);
fclose($out);
ob_get_contents();
ob_flush();
flush();
According to RFC7111, the correct MIME type for CSV file is "text/csv". Also, you don't usually need to flush the output buffer.
To give browser full information, you can try writing the CSV into buffer, calculate the buffer size for content-length, then output the buffer content.
If your file encoding is in UTF-8, this should be sufficient:
<?php
// Use output buffer to prevent any warning or error from
// polluting the CSV output.
ob_start();
// CSV contents
$data = [
['名前', '電話番号'],
['David', '12345678'],
['John', '23456789'],
];
// write to buffer
$buffer = fopen('php://temp', 'w');
foreach ($data as $row) {
fputcsv($buffer, $row);
}
rewind($buffer);
$size = fstat($buffer)['size'] ?? 0;
// drop the output buffer content
// leave the $buffer content (CSV body) alone
ob_end_clean();
// Send HTTP header and content
// for the CSV response.
$filename = 'example.csv';
header('Cache-Control: public');
header('Pragma: public');
header('Content-Type: text/csv; name="' . $filename. '"');
header('Content-Length: ' . $size);
header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename));
echo stream_get_contents($buffer);
References:
I/O Streams
"php://" stream wrapper
exit();
When I add the above command at the end of the file code, then it works normally again.
But I don't understand yet why adding exit() has this working properly
This "error" is related to your computer file open configuration. Maybe you checked the option to assign .csv files to this zip software, but, is easy to change the software and set another one.
I'm trying to download a .rar file from a cloud (for sake of simplicity I'm using my google drive storage), the file is downloading perfectly, but once i want to open the .rar file , it says that "the archive is either unknown format or damaged" , tried all methods even cURL ,but it didnt want to work,
Im just wondering what I'm missing in my code, thank you
<?php
$filename = 'stu.rar';
if ( file_put_contents( $filename,file_get_contents("mygoogleDriveLink/search?q=stu.rar"))) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//header('Content-Length: '.filesize($filename));
readfile($filename);
//print_r("this is ".$id);
exit();
}
else{
echo "err";
}
You may use file_put_contents to save the file to the server first, before you stream it to your browser.
if you do not need to stream to user's web browser, then you may remove the codes from start streaming to end streaming.
Please try the following:
<?php
// Initialize a file URL to the variable
$url = 'http://www.xxxxxxxxxxx.com/xxxxx.rar';
// Use basename() function to return the base name of file
$file_name = basename($url);
// Use file_get_contents() function to get the file
// from url and use file_put_contents() function to
// save the file by using base name
if(file_put_contents( $file_name,file_get_contents($url))) {
// File successfully saved in the server
// start streaming . The following is to stream and save to browser
$file_name = $file_name;
$file_url = $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_url);
exit;
/// end streaming
}
else {
echo "File downloading failed.";
}
?>
everybody, im running in some issue right now, see for internal situations with the server that i cant control or anything right now i cant use base64 encoded files directly over the website cause when the server delivers content to the browser it has a limit of characters for those tasks and it directly affects base64 encoded files cause of the lenght of those strings, so i made for one system a php script that delivers an already existing base64 pdf files to the client as a downloadable file, and it worked just like this:
$reg = File::find($args->string('id')); //querying the file from database
$filename = $reg->filename; //the original file name
$base64 = $reg->file; //the base64 encoded file
$meta_type = explode(',', $base64) [0]; //getting the meta type of the file
$meta_type = str_replace('data:', '', $meta_type);
$meta_type = str_replace(';base64', '', $meta_type);
$file = explode(',', $base64) [1];
$file = base64_decode($base64); //decoding the base64 string
header('Content-Description: File Transfer');
header('Content-Type: ' . $meta_type);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . (strlen($file)));
echo $file;
this worked just fine when i use pdf files but when i try to use it on some 'xlsx' files it seem to work, it download the file, the filesize and all seem to match the original, but excel cant open the file, does anybody have an idea of what im i missing here?? :)
I am pretty sure, its happening, because you are not exiting your function and it continues to fill up buffers. You have to stop the script immediatelly after your stream is ready, clean the buffer and exit.
If its a valid Excel file, all you have to do is:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Cache-Control: must-revalidate');
header('Expires: 0');
header('Pragma: public');
header('Content-Disposition: attachment; filename="' . $filename . '"');
if (ob_get_contents() || ob_get_length()) {
ob_end_clean(); //or ob_end_flush();
}
exit();
I have text file contains Sample of CSV file format, I want my users can download that file on a link click.
This file resides in this folder stucture:
assets->csv->Sample-CSV-Format.txt
This is the code that I have tried to far:
<?php
$file_name = "Sample-CSV-Format.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.') + 1);
header('Content-disposition: attachment; filename=' . $file_name);
if (strtolower($ext) == "txt") {
// works for txt only
header('Content-type: text/plain');
} else {
// works for all
header('Content-type: application/' . $ext);extensions except txt
}
readfile($decrypted_file_path);
?>
<p class="text-center">Download the Sample file HERE It has a sample of one entry</p>
This code is downloading the file on page load instead of link click. Also, it is downloading the whole html structure of the page I want only the text what I have written in text file.
Please guide where is the issue?
You can do this simply in by HTML5 download atrribute . Just add this line in your downloading link .
HERE
You can do it like this, it won't redirect you and also works good for larger files.
In your controller "Controller.php"
function downloadFile(){
$yourFile = "Sample-CSV-Format.txt";
$file = #fopen($yourFile, "rb");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=TheNameYouWant.txt');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($yourFile));
while (!feof($file)) {
print(#fread($file, 1024 * 8));
ob_flush();
flush();
}
}
In your view "view.php"
Download
make it like this
someother_file.php
<?php
$file_name = "Sample-CSV-Format.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);
header('Content-disposition: attachment; filename='.$file_name);
if(strtolower($ext) == "txt")
{
header('Content-type: text/plain'); // works for txt only
}
else
{
header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);
?>
some_html_page.html
<p class="text-center">Download the Sample file HERE It has a sample of one entry</p>
To my view its better to have the download code to the client side, than to have a controller-method written for this.
you can use this ref
public function getTxt()
{
$this->load->helper('download');
$dataFile = "NOTE87";
$dataContent = array();
$dt = "Date :23/07/2021";
$dataContent= array(
"\n",
"\t\t\tUTI AMC Limited\n",
"\t\tDepartment of Fund Accounts\n",
"\n",
"\tReissue of Non Sale Remittance - Axis Bank Cases\n",
"\n",
"\t\t\t\tDate :".$dt."\n",
"\n",
);
force_download($dataFile,implode($dataContent));
}
I'm trying to use PHPWord to generate word documents. And the document can be generated successfully. But there is a problem where my generated word document will be saved on the server. How can I make it available to download straight away?
Sample:
$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
$document->save('php://output'); //it auto save into my 'doc' directory.
How can i link to the header to download it as follows:
header("Content-Disposition: attachment; filename='php://output'"); //not sure how to link this filename to the php://output..
Kindly advise.
php://output is a write-only stream, that writes to your screen (like echo).
So, $document->save('php://output'); will not save the file anywhere on the server, it will just echo it out.
Seems, $document->save, doesn't support stream wrappers, so it literally made a file called "php://output". Try using another file name (I suggest a temp file, as you just want to echo it out).
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);
In the header, the filename field is what PHP tells the browser the file is named, it doesn't have to be a name of a file on the server. It's just the name the browser will save it as.
header("Content-Disposition: attachment; filename='myFile.docx'");
So, putting it all together:
$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
// // save as a random file in temp file
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);
// Your browser will name the file "myFile.docx"
// regardless of what it's named on the server
header("Content-Disposition: attachment; filename='myFile.docx'");
readfile($temp_file); // or echo file_get_contents($temp_file);
unlink($temp_file); // remove temp file
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$filename = 'MyFile.docx';
$objWriter->save($filename);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
exit;
This is work for me:
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007', $download = true);
header("Content-Disposition: attachment; filename='File.docx'");
$objWriter->save("php://output");
now whit Ver 0.13.0
https://github.com/PHPOffice/PHPWord
<?
require_once "../include/PHPWord-develop/bootstrap.php";
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
$templateProcessor->setValue('var01', 'Sun');
$templateProcessor->setValue('var02', 'Mercury');
//#####################################################
// Save File
//#####################################################
//#####################################################
header("Content-Disposition: attachment; filename='output01.docx'");
$templateProcessor->saveAs('php://output');
//#####################################################
//#####################################################
?>
A simple solution for Laravel based on #user3214824 answer.
// ...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$doc_name = 'fileName.docx';
$objWriter->save($doc_name); // saving in the public path just for testing
return response()->download(public_path($doc_name))->deleteFileAfterSend(true);
Sorry this came in later. I stumbled on this while trying to solve the same problem. I was able to get it working on Laravel 5 using below:
$file_dir = $template_upload_dir.DIRECTORY_SEPARATOR.'filename.docx';
$tags = array();
if (file_exists($file_dir)) {
$templateProcessor = new TemplateProcessor($file_dir);
$tags = $templateProcessor->getVariables();
$replace = array('');
$templateProcessor->setValue($tags, $replace);
$save_file_name = $fullname.'-'.$inv_code.'-'.date('YmdHis').'.docx';
$templateProcessor->saveAs($save_file_name);
return response()->download($save_file_name)->deleteFileAfterSend(true);
}
Hope it helps someone!!!
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
header("Content-Disposition: attachment; filename='myFile.docx'");
$objWriter->save("php://output");