fabrik
fabrik

Reputation: 14365

PHP readfile returns zero length file

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:

UPDATES:

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

Upvotes: 6

Views: 7551

Answers (4)

fabrik
fabrik

Reputation: 14365

My. Lame. Fault. Sorry for everyone.

Just tweaked the code a week ago and added:

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
    ob_start('ob_gzhandler');
} else {
    ob_start();
}

What caused this anomaly. :(

Upvotes: 0

powtac
powtac

Reputation: 41050

Try to add attachment; and use a different browser.

header('Content-disposition: attachment; filename="' . $zip_name . '"');

Upvotes: 0

RobertPitt
RobertPitt

Reputation: 57268

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

Upvotes: 1

Thom Wiggers
Thom Wiggers

Reputation: 7054

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.

Upvotes: 5

Related Questions