3

I have a page that allows users to download files stored in a database. This page simply uses a GET variable to find the corresponding ID in the database table and return the file as an attachment in the header of the file.

header("Content-length: $objFile->size");
header("Content-type: $objFile->type");
header("Content-Disposition: attachment; filename=".($objFile->name));

The issue I have is if the file uploaded into the database contains a space in the name, for instance "3 Year Spending Analysis.pdf", then when the file is returned for download the file name comes up as just "3" due to the space in the name.

I've tried urlencode, rawurlencode and others but not getting the expected results of the full file name.

1
  • urlencode should do the trick. Can you edit your post and show ur attempt to use urlencode? Commented Sep 14, 2011 at 14:36

1 Answer 1

5

Put it inside quotes:

header('Content-Disposition: attachment; filename="'.($objFile->name).'"');

Here is the relevant part of the HTTP specification.

Update: Technically, this should read

str_replace('"', '\\"', $objFile->name)

because the HTTP spec states that a double quote character inside a quoted-string must be escaped with a backslash. In practice you don't expect filenames with double quotes in them (I 'm not even sure which filesystems allow it), but for 100% guaranteed compliance the str_replace is needed.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I tried quotes but I used single quotes around the name of the file not double quotes. And thanks for the note on the str_replace to catch any strange files names. I'll consider that a bonus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.