2

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.

Iburidu
  • 450
  • 2
  • 5
  • 15

2 Answers2

3

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;
}
Pankaj Khairnar
  • 3,028
  • 3
  • 25
  • 34
  • but is it hex-based? cuz' i have to replace the bytes. – Iburidu Dec 01 '12 at 15:49
  • you have an exe now, that you read and make it downloadable, BUT i have to get hexadecimal content from the exe and exchange 100-200 bytes in it with ANOTHER hexadecimal content somehow. – Iburidu Dec 01 '12 at 15:55
  • you can use file_get_contents to read file contents and can replace some from it. I've never tried this but it seems possible by using this. – Pankaj Khairnar Dec 01 '12 at 16:00
1

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);
piotrekkr
  • 2,785
  • 2
  • 21
  • 35
  • and isnt it possible to read all of the hexadecimal datas from my database (not from the exe) and i create a string and flush it to exe? – Iburidu Dec 01 '12 at 16:11
  • Php substr() is binary safe and operates on bytes not on characters. String in php are also a sequences of bytes. So it does not matter from where you have your data if it's a php string. It can be from database, $_POST, xml, whatever. I don't really get what do you mean by "hexadecimal data". Can you explain more? – piotrekkr Dec 02 '12 at 11:15