PHP File Transfer - How does this work?

后端 未结 1 1269
北海茫月
北海茫月 2021-01-26 17:10

So, in another QUESTION, I got this answer:

$filename=\"filetodownload.xyz\";
$cf = realpath(\"/non-webaccessible-folder/\".$filename);
$file=$cf;

header(\'Cont         


        
相关标签:
1条回答
  • 2021-01-26 17:58

    Is the purpose of using basename() simply to strip the path from the filename?

    Yes, this header is what is used by the browser to present to the user a filename to save the downloaded file as. You wouldn't want to offer the user a full filepath, just the filename, and I'm not sure the browser would even present a full filepath to the user.

    What is the purpose of realpath()? In my usage, it seems to make no difference whatsoever. Based on what I've found, it seems to just 'standardize' filepath inputs. Is that correct?

    It resolves relative and symbolic links to their absolute paths, which is probably what you mean by 'standardizing'. If you only ever supply it absolute paths, it'll do nothing.

    I don't seem to need the last three lines to make this work:

    header("Content-Length: " . filesize($cf));

    header("Content-Type: application/octet-stream");

    readfile(realpath($cf));

    Do I need them? What do they do? I should note that I'm testing just using localhost, in case that makes a difference.

    You should keep them all. The first two headers tell the browser how big the file is and what type of file it is. Right now you're using a generic media type, but if you were to send, say a PDF file, you could use the more-specific PDF media type and the browser would let the user know they're downloading a PDF.

    I also don't think downloading would work without the last line... That's what's actually reading the file by PHP and sending it to your browser. If you omit it, you'll probably end up downloading a blank file.

    0 讨论(0)
提交回复
热议问题