PHP output buffering (ob_start, ob_flush) - php

I used php output buffering earlier in order to create csv file from database, because i didn't want to create an existing file, just wanted to make content downloadable.
CSV is text-based file, so its easy to create this way, you set the header and flush the text content. But! What if, I want to create an exe from hex data? (The project is: I have an existing exe file and I want that users can write something inside a HTML textbox and I convert that to hex and exchange the old text to the new one)
Thanks.

Use following code to download exe file by reading from hard disk.
<?php
$file = 'test.exe';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

If you want to replace part of binary file, for example from 100th byte to 200th byte you could use substr() and str_pad():
$binFile = file_get_contents('/pathto/exec/file.exec');
$replacedBinFile = substr($binFile, 0, 100) . str_pad(substr($_POST['text'], 0, 100), 100, "\x00") . substr($binFile, 200);
file_put_contents('/pathto/exec/file_replaced.exec', $replacedBinFile);

Related

Convertig excel base64 to downloadable file PHP

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();

Simple PHP script for XZ file download

I'm trying to setup a backup system that will perform a backup, compress the file and make it downloadable from a browser. The file downloads properly but when I try to uncompress it I get:
unxz: backup_2015-08-12.txz: File format not recognized
There is a backup script that will output
/tmp/agribackup.txz
The PHP script is as follows:
<?php
// Create the agribackup.txz file
$e = shell_exec("/usr/local/bin/agribackup.sh");
$file = '/tmp/agribackup.txz';
if(file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/xz');
header('Content-Disposition: attachment; filename=backup_'.date("Y-m-d") . '.txz');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
I think you are using the wrong Content-Type. Refering to 'http://tukaani.org/xz/xz-file-format.txt', the correct MIME-type is 'application/x-xz'.

javascript - Default filename when saving from html2canvas or save as dialogue?

A friend of mine configured h2ml2canvas for me as I don't understand javascript. When saving using h2ml2canvas it generates a random filename e.g.
df0e604b2962492165eb8f2b31578171
Is there a way to specify a filename prefix? e.g. soccer then generate a random 3-4 digit number? Alternatively is there a way to open a save as dialogue instead of downloading an image on click? My download.php file.
<?php
$file = trim($_GET['path']);
// force user to download the image
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename='.basename($file));
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($file));
ob_clean();
flush();
readfile($file);
unlink($file);
exit;
}
else {
echo "error not found";
}
?>
The filename in your case is actually generated (or not) by the PHP server-side, not the JavaScript you've quoted. When it returns the data to send back, it's including a Content-Disposition header, probably one that looks like this:
Content-Disposition: attachment
It's possible to suggest a filename to the browser by adding to that header:
Content-Disposition: attachment; filename=soccer123.xyz
In the PHP somewhere, you should find:
header("Content-Disposition", "attachment");
or similar. You can change it to:
header("Content-Disposition", "attachment; filename=soccer-" . rand(100,999) . ".xyz");
(Probably best to make the .xyz an appropriate extension for the type of image, e.g. .png or .jpg...)
Re your edit, you can replace:
header('Content-Disposition: attachment; filename='.basename($file));
with
header('Content-Disposition: attachment; filename=soccer-'.rand(100,999).'.xyz');
again you'll want a correct extension instead of .xyz.

Download file once - Corrupt file error

What I want to do is to allow only one download per user (one access to a href) For that I have a variable in the user's table, which I do change when the link has been clicked.
I use "download.php?file=file.xxx" for doing that.
download.php
$file= basename($_GET['file']);
$root = "documents/rece/";
$path= $root.$file;
echo $path;
if (is_file($path))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
}
else
echo "File error";
exit();
?>
I also update the DDBB and that works. After that I can show or hide the link. The problem is that the downloaded file is corrupted and can't be opened. I will use it with pdf or doc, maybe zip.
Could it be because of the path?
PDF files, as far as I know, start with something like this:
%PDF-1.4
Yours start with 4 blank lines plus documents/rece/Form.pdf%PDF-1.4. You're obviously printing it yourself somewhere before the code you've posted.

txt file that I download is empty

The code below is for two purposes
1) I save a text file on my server in a folder named "backup_db" its working fine mean when I open that text file it contain all the data
2) At the same time i also make this file downloadable for a user so that he could download it for himself and could save it on his hard disk and according to my wish its downloading but unfortunately the .txt file saved on my hard disk is, when open its empty and i don't know why please help me out
//save file
$handle = fopen('backup_db/db-backup-'.date('d-m-Y_H-i-s').'-'.(md5(implode(',',$tables))).'.txt','w+');
$rr = fwrite($handle,$re);
//fclose($handle);
$ww = "db_backup".$rr.".txt";
//$handle = "";
header('Content-Disposition: attachment; filename=' . urlencode($ww));
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
header('Content-Description: File Transfer');}}
You only set the HTTP header but did not write the file into the response body. Use either fpassthru() or readfile() to write the content of the file directly to the response.
Sample (taken from php.net)
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
flush();
readfile($file);
exit;
}
?>
BTW:
Settings the same header multiple times simply overwrites the value set before unless you set the second parameter of header() to false.
Your code
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
results in the following header:
Content-Type: application/download
Sending a file namein the header just gives the user a suggested filename. Try echoing out the contents of the file.
You should add
header("Content-Length: $size")
where $size is size of yout file in bytes.
Check this
ex :
$filename = urlencode($fileName); //download.txt
header("Content-Disposition: attachment; filename=\"" . $filename. "\";" );

Categories