Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP readfile returns zero length file

Tags:

php

readfile

This is weird.

I have a script which sends local zip files to the user via browser. The script has worked fine so far without any problems. Today my colleague notified me about the script is sending zero-length files.

Some background info:

  • Server settings has not been modified before the script went wrong
  • Different browsers tested (same on Chrome/Firefox)
  • Previous zip files (which worked fine before) are zero-length too
  • Script founds the files on the server
  • File size (when echoed for debugging) is correct
  • Tried to tweak server settings and script as adviced here with no success.

UPDATES:

  • is_readable() returns 1
  • file sizes may vary between 5Mb and 100Mb (not specific)
  • $zip_file holds the file path
  • $zip_name holds the zip name
  • file is really zero-length (opened in text-editor it doesn't contain a single byte)
  • error_reporting is On (E_ALL) shows nothing
  • without headers the browser displays the zip 'source' correctly
  • Safari says: '0 bytes of? cannot decode raw data' first useful(?) symptom

Snippet in question:

if (file_exists($zip_file)) {
    header('Content-type: application/zip');
    header('Content-disposition: filename="' . $zip_name . '"');
    header("Content-length: " . filesize($zip_file));
    readfile($zip_file);
    exit();
}

How can i debug this easily?

Thanks in advance, fabrik

like image 314
fabrik Avatar asked Mar 21 '11 08:03

fabrik


2 Answers

http://www.php.net/manual/en/function.readfile.php#102137 :

It should be noted that in the example:

header('Content-Length: ' . filesize($file));

$file should really be the full path to the file. Otherwise content length will not always be set, often resulting in the dreaded "0 byte file" problem.

like image 199
Thom Wiggers Avatar answered Sep 28 '22 02:09

Thom Wiggers


The biggest issue here I think is the way your sending the file, have you tried sending in within chunks:

if (file_exists($zip_file))
{
    header('Content-type: application/zip');
    header('Content-disposition: filename="' . $zip_name . '"');
    header("Content-length: " . filesize($zip_file));

    $resource = fopen($zip_file,'r');
    while(!feof($resource))
    {
         $chunk = fread($resource,4096);
         //....
         echo $chunk;
    }

    exit();
}
like image 40
RobertPitt Avatar answered Sep 28 '22 03:09

RobertPitt