我有一个简单但关键的问题(对我的应用程序至关重要)
我将有一个文件网址:
a/b.jpg a/b.zip http:// a。 com / b.mp3 <或任何有效的文件>当用户点击我网站上任何特定文件的下载链接,b,用户将看到url为
b/?f=1我不希望用户看到原始URL,其次,想强制下载文件, p>
我知道我可以使用readfile来实现这一点(请参阅 php/manual/en/function.readfile.php ),但我不知道filesize和mimetype,我怎么能得到保证文件将正确下载?
请帮助别人
解决方案我想你可以使用cURL触发对目标网址的HEAD请求。这将使托管目标的Web服务器具有文件的mimetype和内容长度。
$ url ='http:// www.example/path/somefile.ext'; $ ch = curl_init(); curl_setopt($ ch,CURLOPT_HEADER,true); curl_setopt($ ch,CURLOPT_NOBODY,true); // make it一个HEAD请求 curl_setopt($ ch,CURLOPT_FOLLOWLOCATION,true); curl_setopt($ ch,CURLOPT_URL,$ url); curl_setopt($ ch,CURLOPT_RETURNTRANSFER,TRUE); $ head = curl_exec($ ch); $ mimeType = curl_getinfo($ ch,CURLINFO_CONTENT_TYPE); $ size = curl_getinfo($ ch,CURLINFO_CONTENT_LENGTH_DOWNLOAD); $ path = parse_url($ url,PHP_URL_PATH); $ filename = substr($ path,strrpos($ path,'/')+ 1); curl_close($ ch);然后,您可以将这些头文件写回到您的脚本上的HTTP请求: header('Content-Type:'。$ mimeType); header('Content-Disposition:attachment; filename ='。$ filename。'';'); header('Content-Length:'。$ size);然后你按照文件内容。
readfile($ url);
I have a simple, yet critical question (critical for my application)
I will have a file url as:
a/b.jpg a/b.zip a/b.mp3 <or any valid file>When user will click on download link for any specific file (say b.jpg) on my site i.e., b, user will see url as
b/?f=1I don't want user to see original URL and secondly, want to force download of file, irrespective of filetype
I know that I can achieve this using readfile (Check Example1 at php/manual/en/function.readfile.php), but I don't know filesize and mimetype, how can I get assurance that file will be downloaded properly?
Please help guys
解决方案I suppose you can use cURL to fire off a HEAD request for the target URL. This will let the web server hosting the target the mimetype and content length of the file.
$url = 'www.example/path/somefile.ext'; $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); // make it a HEAD request curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $head = curl_exec($ch); $mimeType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD); $path = parse_url($url, PHP_URL_PATH); $filename = substr($path, strrpos($path, '/') + 1); curl_close($ch);Then, you can write back these headers to the HTTP request made on your script:
header('Content-Type: '.$mimeType); header('Content-Disposition: attachment; filename="'.$filename. '";' ); header('Content-Length: '.$size);And then you follow this up with the file contents.
readfile($url);
更多推荐
将服务文件托管在另一个服务器上作为下载
发布评论