1

Quite simply, I'm trying to generate and download a CSV file from a CakePHP controller. No problem generating the CSV, and everything works until the response >= 4096 bytes.

The following controller illustrates the problem:

class TestTypeController extends Controller {
  public function csv($size = 100) {
    # set the content type
    Configure::write('debug', 0);
    $this->autoRender = false;
    $this->response->type('csv');
    # send the response
    for ($i = 0; $i < $size; $i++)
      echo 'x';
  }
}

When I call http://baseurl/test_type/csv/4095, I'm prompted to save the file, and the Content-Type header is text/csv. The response headers are:

HTTP/1.1 200 OK
Date: Tue, 05 Jun 2012 14:28:56 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.3.10-1ubuntu3.1
Content-Length: 4095
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Content-Type: text/csv; charset=UTF-8

When I call http://baseurl/test_type/csv/4096, the file is printed to the screen, and the response headers are:

HTTP/1.1 200 OK
Date: Tue, 05 Jun 2012 14:28:53 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.3.10-1ubuntu3.1
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 38
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

Obviously, 4kB is the limit where Content-Encoding starts gzipping the response. I'm not familiar with how the Content-Type is meant to react, but I'd obviously prefer it to remain text/csv.

The same problem occurs using the RequestHandlerComponent to manage the type of the response.

I'm using the CakePHP 2.2.0-RC1, but I've verified the problem exists with stable 2.1.3. Any ideas? Pointers in the right direction?

Ryan Skraba
  • 1,108
  • 9
  • 25
  • I poked around and I don't see anything that Cake does to change the header based on content length. I feel like it might be an apache configuration issue. Check out this link and see if your config is adding/changing the type http://httpd.apache.org/docs/2.0/mod/mod_deflate.html – jeremyharris Jun 05 '12 at 18:20
  • I ran into the same issue when trying to echo a css file inside a controller. As soon as the css exceeded 4095 characters, the content-type would go from text/css to text/html. Did you ever figure out an explanation for this? As you mentioned, the solution was to echo the css inside the view rather than the controller. – Leo Galleguillos Oct 15 '18 at 17:27

1 Answers1

3

The answer was pretty simple -- the controller should be returning the CSV data instead of echoing it.

Ryan Skraba
  • 1,108
  • 9
  • 25