如何验证 HTTP 文件下载?
在我的网站中,我有一个 php 脚本,它启动文件下载而不显示文件的完整路径,代码如下所示:
$path = '../examples/test.zip';
$type = "application/zip";
header("Expires: 0");
header("Pragma: no-cache");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header("Content-Description: File Transfer");
header("Content-Type: " . $type);
header("Content-Length: " .(string)(filesize($path)) );
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Transfer-Encoding: binary\n");
readfile($path); // outputs the content of the file
exit();
有一种方法可以在启动下载之前添加 HTTP 身份验证吗?
提前致谢!
编辑1: 感谢 André Hoffmann,我已经通过使用 HTTP 基本身份验证解决了这个问题! 但是如果我想使用如下所示的 HTTP 摘要身份验证,我该怎么办? 我尝试在以下行之后编写上面的代码:“echo '您的登录方式为:'。$data['username'];” ...但我收到一条错误消息,说我不能两次修改标题!
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response){
die('Wrong Credentials!');
}
// ok, valid username & password
echo 'Your are logged in as: ' . $data['username'];
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>
解决方案:
感谢安德烈和安东尼,我可以编写解决方案:
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response){
die('Wrong Credentials!');
}
// ok, valid username & password ... start the download
$path = '../examples/test.zip';
$type = "application/zip";
header("Expires: 0");
header("Pragma: no-cache");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header("Content-Description: File Transfer");
header("Content-Type: " . $type);
header("Content-Length: " .(string)(filesize($path)) );
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Transfer-Encoding: binary\n");
readfile($path); // outputs the content of the file
exit();
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>
In my website I've a php script that launches a file download without showing the full path of the file, the code look like this:
$path = '../examples/test.zip';
$type = "application/zip";
header("Expires: 0");
header("Pragma: no-cache");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header("Content-Description: File Transfer");
header("Content-Type: " . $type);
header("Content-Length: " .(string)(filesize($path)) );
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Transfer-Encoding: binary\n");
readfile($path); // outputs the content of the file
exit();
There is a way to add an HTTP authentication before to launch the download?
Thanks in advance!
EDIT 1:
Thanks to André Hoffmann, I've solved the problem by using an HTTP Basic Authentication!
But If I would like to use an HTTP Digest Authentication like the following, how can I do?
I've tried to write the code above, after the line: "echo 'Your are logged in as: ' . $data['username'];" ... but I get an error saying that I can not modify the header twice!
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response){
die('Wrong Credentials!');
}
// ok, valid username & password
echo 'Your are logged in as: ' . $data['username'];
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>
SOLUTION:
Thanks to André and Anthony, I can write the solution:
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response){
die('Wrong Credentials!');
}
// ok, valid username & password ... start the download
$path = '../examples/test.zip';
$type = "application/zip";
header("Expires: 0");
header("Pragma: no-cache");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header("Content-Description: File Transfer");
header("Content-Type: " . $type);
header("Content-Length: " .(string)(filesize($path)) );
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Transfer-Encoding: binary\n");
readfile($path); // outputs the content of the file
exit();
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,请参阅手册。
更新:
基于 .htaccess 的身份验证实际上允许多个用户使用。
将其放入您的 .htaccess 中:
可以使用 apache 附带的
htpasswd
工具创建包含密码的文件 passwords.file。文件 groups.file 应该与此类似:
在这里,您基本上只列出应该有权访问该目录的用户。
另请参阅此教程。
Sure see the manual for this.
UPDATE:
A .htaccess based authentication acutally allows to be used by more than one user.
Put this in your .htaccess:
The file passwords.file containing the passwords can be created using the
htpasswd
tool that came with apache.The file groups.file should like similar to this:
Here you basically just list the users that should have access to the directory.
Please also see this tutorial.
您是否在脚本回显“您已成功登录为...”后尝试启动下载?
将任何内容输出到屏幕后,您无法设置任何标题。一旦您回显或打印或其他什么,您就开始了 HTTP 响应的正文部分,这意味着标头已设置。
顺便说一句,如果您尝试设置标题,然后给出“您已登录”位,则会卡在文件中,而不是输出到屏幕。
您想要做的是让脚本输出“您已登录”并重定向到发送下载标头的脚本。用户将看不到第二页,因为标题设置为“附件”。这就是典型的“您的下载将立即开始”页面的工作方式。
Are you trying to initiate the download after having the script echos "You have successfully logged in as ..."?
You can't set any headers after you have output anything to screen. As soon as you echo or print or what-have-you, you have started the body part of the HTTP response, which means the headers have been set.
By the way, if you try setting the headers and THEN giving the "you've logged in" bit, that will get stuck in the file, not output to screen.
What you want to do is have the script output "you are logged in" and the redirect to the script that sends the download headers. The user won't see that second page, as the header is set to "Attachment". This is how your typical "Your download will begin momentarily" pages work.