-1

I am working on a "simple" shopping cart app that allows users to purchase downloadable products. I am interested in creating a link to a digital product without revealing the full URL to the end user. I have searched other solutions here and understand the basics of making a "download.php" file that references the product ID, stored as a HASH type value in the DB, that can then be referenced to get the actual URL of the file.

However, there are some formatting issues that I've bumped into that others might find interesting:

The following link is an example: Download files from server php

It shows the following code as the headers of the downloadable document (Referencing a PHP variable):

header("Content-Disposition: attachment; filename=$file");

Another example of that is here: Start a download with PHP without revealing file URL

readfile($file);

However, if you look at the PHP HEADERS documentation here: PHP - HEADERS Documentation

You'll notice that all of the arguments passed are wrapped in single quotes:

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');

Those who are particularly gifted in attention to detail will also notice that the Content-Disposition argument has the filename wrapped in double quotes . . . with the full argument wrapped in single quotes.

If I followed the code in the above examples (leaving out the single and/or double quotes) the file seems to be corrupted, missing, or just fails to load. So how do I fix this?

D. Yager
  • 29
  • 6

1 Answers1

-1

To get this working in my own code, I needed to wrap my PHP variables in either single or double quotes (and sometimes doubled single quotes) as shown below:

header('Content-Type:'.$ctype.'' ); 
header('Content-Disposition: attachment; filename="'.$fname.'"');
readfile(''.$filepath.'');

When entered this way, I was able to download the files without corruption or issue. Please let me know if you are aware of a better way of doing this.

However, when I used the coded above it also allowed me to NOT use the

            ob_clean();
            ob_end_flush();

commands in my code. In fact if I add them now . . . it seems to corrupt my files too. Weird.

Another potential GOTCHA is that if you attempt to download a TXT file, and you have a PHP "echo" statement anywhere in your "download.php" file, the contents of the ECHO statement will be appended to the TXTY file that's downloaded. So just something to be careful of.

This ECHO statement may also be appended to the headers of other documents types as well, but it didn't seem to affect the ability of the file to open in my limited testing. But again, be careful out there! :)

D. Yager
  • 29
  • 6