开发者

PHP File Download

开发者 https://www.devze.com 2023-01-15 19:06 出处:网络
I\'m currently building a script that will allow a user to download a file via a URL without actually seeing the filename or where the file is stored.So far I have everything built out, but I need to

I'm currently building a script that will allow a user to download a file via a URL without actually seeing the filename or where the file is stored. So far I have everything built out, but I need to know how I would go about calling the file to open and download. I currently have a working version (code below), but for some reason the PHP is corrupting the download. Everytime I try to open a file that downloads to my desktop I get a corrupt error m开发者_Python百科essage. When I open the same file on the server itself, the file works just fine.

URL Structure:

http://www.example.com/download/file/cjVQv0ng0zr2

Code that initiates the download

    $fullpath = BASE_PATH . '../uploads/brochures/' . $vendors['0']['filename'];

    header("Content-type: application/pdf");
    header('Content-disposition: attachment; filename="' . $fullpath . '"');

Am I doing something wrong that would cause the file to become corrupt? Am I missing a header or two?

Thanks in advance, Jake


You need to call the following line after sending the header.

readfile($fullpath); 

and also adjust in the header like this:

header('Content-disposition: attachment; filename="' . basename($fullpath) . '"');

One thing i am not sure about is the $fullpath .. try to see if the $fullpath you have is correct and you can actually reach the file, this needs to be the full physical path of the file.

I think it would also be a good idea to add the following header as well:

header("Content-Transfer-Encoding: binary"); 


I had a similar issue a while back. Make sure you don't have any extra whitespace in your script file, either before the "<?php" tag or after the "?>" tag. In my case the last character of my script was "\n" instead of the expected ">".


I had faced the same problem sometime back, following worked for me; put a

while( @ob_end_clean() );

just before header functions:

header("Content-Type: ". $row['p_mime']);
header("Content-Length: ". $row['p_size']);
header("Content-Disposition: inline; filename=".$row["p_name"]);

Content-disposition: attachment/inline has to be set according to cases (1. prompt for download / 2. open in browser)

NOTE: Take care that you are not echoing and value before the header function, and being over cautious will not do any harm, silent out all the function before header function which you think would fail or spawn a warning message prefixing "@" symbol to those lines of php code.

all the best :)


Make sure you exit...

(i'm using a blob)

header("Content-Type: " . $response['content_type'] );
header("Cache-Control:  maxage=1");
header("Pragma: public"); //fixes ie bug
echo trim($_data);
exit();     
0

精彩评论

暂无评论...
验证码 换一张
取 消