我想用PHP开始下载,但我不想让用户知道正在下载的文件的URL。
我在StackOverflow中读了很多答案,但我发现的都是下载文件的URL。
以下是我想做的事情,例如:
这是PHP文件,用户会看到这个URL:http://website.com/download.php
这是下载文件的URL,我不希望用户看到这个URL:http://website.com/file.zip
有办法做到这一点吗?
在渲染页面之前,存储下载url somhwhere(例如在会话中)并生成一些唯一的哈希,稍后您可以使用它来确定应该下载的文件:
$SESSION['file_download']['hash'] = md5(time) . '_' . $userId; // lets say it equals to 23afg67_3425
$SESSION['file_download']['file_location'] = 'real/path/to/file';
当渲染显示用户以下下载网址:
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
}
这取决于您想要隐藏什么。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));