使用PHP开始下载,但不显示文件URL
我希望ta使用PHP开始下载,但我不希望用户知道正在下载的文件的URL 我在StackOverflow中读了很多答案,但我所找到的只是显示下载文件的URL 下面是我想做的,例如: 这是PHP文件,用户将看到此URL:使用PHP开始下载,但不显示文件URL,php,url,download,Php,Url,Download,我希望ta使用PHP开始下载,但我不希望用户知道正在下载的文件的URL 我在StackOverflow中读了很多答案,但我所找到的只是显示下载文件的URL 下面是我想做的,例如: 这是PHP文件,用户将看到此URL:http://website.com/download.php 这是下载文件的URL,我不希望用户看到此URL:http://website.com/file.zip 有什么方法可以做到这一点吗?这取决于你想隐藏什么。URL将永远显示给用户,但如果您不想让用户知道发送哪些参数(或值)
http://website.com/download.php
这是下载文件的URL,我不希望用户看到此URL:http://website.com/file.zip
有什么方法可以做到这一点吗?这取决于你想隐藏什么。URL将永远显示给用户,但如果您不想让用户知道发送哪些参数(或值),您可以对它们进行编码,并通过AJAX通过POST请求发送它们。尝试以下操作:
$file = './file.zip';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"'); //<<< Note the " " surrounding the file name
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
$file='./file.zip';
标题(“内容描述:文件传输”);
标题(“内容类型:应用程序/八位字节流”);
标题('Content-Disposition:attachment;filename=“”.basename($file)。“”)// 在呈现页面之前,请将下载url存储到somwhere(例如在会话中),并生成一些唯一的哈希,稍后您可以使用这些哈希来标识应下载的文件:
$SESSION['file_download']['hash'] = md5(time) . '_' . $userId; // lets say it equals to 23afg67_3425
$SESSION['file_download']['file_location'] = 'real/path/to/file';
渲染时,向用户显示以下下载url:
http://yourdomain.com/download_file.php?hash=23afg67_3425
如果用户单击它,则将文件发送给用户,但只允许此操作一次或在当前会话期间执行。我的意思是,您应该创建名为download_file.php的新源文件,其中包含以下内容:
if ($_GET['hash'] == $SESSION['file_download']['hash']) {
// send file to user by outputing the file data to browser
$file = $SESSION['file_download']['file_location'];
header('Content-Description: File Transfer')
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
// optionaly reset $SESSION['file_hash'] so that user can not download again during current session, otherwise the download with generated link will be valid until user session expires (user closes the browser)
} else {
// display error message or something
}
可能重复我试图开始下载一个视频(MP4)文件,它开始下载,但立即完成。它下载一个0字节的文件。如果您尝试直接下载,它是否正常下载/Yes。如果我转到视频并单击“另存为”,下载将正常开始。