It’s early in the morning and I’m just not getting this:
The following code works, and file is placed on the server:
$filename = $ioid . "_" . time();
$fp = fopen("$filename.csv", "w+");
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
But this doesn’t work straight after (file is 105k):
$fp2 = fopen("$filename.csv", "r");
$output = fread($fp2, 1000000000000);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $output;
fclose($fp2);
Nothing is read, and nothing is printed to the page.
What obvious thing am I doing wrong? 🙂
Your problem is that
fread($fp2, 1000000000000)tries to allocate 1 terabyte big buffer to read the file into and obviously hits allowed memory limit, unless you’re on a 32-bit platform where integer overflow occurs. Either way it isn’t working.If you want read a whole file to the output buffer and do that fast, use
readfile()like so:Be sure to check the error log next time.
Also if you don’t plan to store resulting files on disk I recommend you to remake your script to use a safer approach: