Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading a file cause error when it contains spaces - PHP

Tags:

php

Consider that i am uploading a file with following names:

  1. test.pdf
  2. test file.pdf

When i download the test.pdf it's working fine..

But when i download test file.pdf it doesn't. The case is the space between the file name.

Unfortunately i should not change the file name when i upload (If i can i will set "_" using str_replace between spaces and resolve this issue).

Now how should i download the file ?

My code is given below:

header('Content-disposition: attachment; filename=test file.pdf');
header('Content-type: application/pdf');
readfile('test file.pdf');

Thanks in advance...

like image 466
Fero Avatar asked Jul 22 '11 07:07

Fero


2 Answers

The case is the space between the file name.

Put it in double quotes to fix the issue. With an example:

header('Content-disposition: attachment; filename="test file.pdf"');
header('Content-type: application/pdf');
readfile('test file.pdf');

This should work. I've just tried using readfile on a file with a space, and that seems to cause no issues.

like image 74
Berry Langerak Avatar answered Oct 11 '22 16:10

Berry Langerak


The content-disposition header is not part of HTTP (but popular to use with HTTP requests), see in RFC 2616.

The documentation of it is part of RFC 2183 which is in the MIME domain. It's specified as filename-param of which the filename is actually the value part. That value is defined in RFC 2045 Appendix A -- Collected Grammar as:

value := token / quoted-string
token := 1*<any (US-ASCII) CHAR except SPACE, CTLs,
             or tspecials>
tspecials :=  "(" / ")" / "<" / ">" / "@" /
              "," / ";" / ":" / "\" / <">
              "/" / "[" / "]" / "?" / "="
              ; Must be in quoted-string,
              ; to use within parameter values

See as well RFC 2616, 2.2 Basic Rules.

It's all US-ASCII and I assume the space needs escaping, e.g. multiple words in double-quotes (other chars work as well for that quoted string, token is a single word):

header('Content-disposition: attachment; filename="test file.pdf"');

Keep in mind that other chars need other escaping/encoding, see RFC 2047 and this pear ticket.

But in the end you need to test with every browser. I think it's easier if you replace the space with a _ or - inside the filename to be more stable:

header('Content-disposition: attachment; filename=test-file.pdf');

Hope this is helpful to understand your issue.

like image 44
hakre Avatar answered Oct 11 '22 18:10

hakre