3

I have a button. By clicking the button, I want to export some data shown on the webpage to a file for downloading.

I am doing this in this way: I have a export.php. I send the data as the parameter to PHP file (another parameter is filename), and PHP server create a file and write the data, and then send file. Code is like:

$filename = $_GET['filename'] . '.csv';
$export = $_GET['export'];
$writer = fopen($filename, 'w') or die('cannot create');
fwrite($writer, $export . "\n");
fclose($writer);

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($filename));
readfile($filename);
unlink($filename);

exit();

For cases that the data are short, it works fine. But if the data are long, since the data are passed as part of the URL, I will get "Request-URI Too Large" error.

Is there any alternative way to do that? Is it possible to directly write data using JavaScript?

DrXCheng
  • 3,992
  • 11
  • 49
  • 72
  • My good friend google found you [*this example*](http://www.finalwebsites.com/forums/topic/php-file-download). – Nir Alfasi Jul 19 '12 at 21:54
  • @alfasin The problem is: there is no existing file. I need to create this file first on the server, and I need to pass the data to the server. – DrXCheng Jul 19 '12 at 21:58
  • so replace the while-loop that contains: `$buffer = fread($fd, 2048);` with reading from the source you want. – Nir Alfasi Jul 19 '12 at 22:42

3 Answers3

4

It sounds like you are sending to export.php with a GET, when you should be using a POST. GET is limited to 2048 characters, while a POST is not limited.

Aaron Dougherty
  • 727
  • 6
  • 9
2

You'll need to POST the data to the server. Change the METHOD in your FORM tag to POST (in your html not your php code).

Each browser limits the size of the query string / length of the URL and the limit is browser dependent. You can POST a very large amount of data to the server however. The only limit is how fast is the user's upstream bandwidth and their patience.

Community
  • 1
  • 1
Andy Jones
  • 6,205
  • 4
  • 31
  • 47
1

Instead of passing the data as a query string, use javascript to create an iframe and build a form which then posts to the php file.

IF your using jquery there's a good tutorial http://tutorialzine.com/2011/05/generating-files-javascript-php/

aron.duby
  • 2,072
  • 2
  • 15
  • 21