Como autenticar um download de arquivo http?
-
20-09-2019 - |
Pergunta
No meu site, tenho um script PHP que inicia um download de arquivo sem mostrar o caminho completo do arquivo, o código é assim:
$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();
Existe uma maneira de adicionar uma autenticação HTTP antes de iniciar o download?
Desde já, obrigado!
Editar 1:Graças a André Hoffmann, resolvi o problema usando uma autenticação básica HTTP! Mas se eu gostaria de usar uma autenticação HTTP Digest como a seguinte, como posso fazer? Eu tentei escrever o código acima, após a linha: "Echo 'você está conectado como:'. $ Data ['nome de usuário'];" ... Mas recebo um erro dizendo que não posso modificar o cabeçalho duas vezes!
<?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;
}
?>
SOLUÇÃO:
Graças a André e Anthony, posso escrever a solução:
<?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;
}
?>
Solução
Com certeza veja o manual por esta.
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
//check $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']
if ($valid) {
//start 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();
} else {
//show error
}
}
ATUALIZAR:
Uma autenticação baseada em .htaccess permite que seja usado com mais de um usuário. Coloque isso em seu .htaccess:
AuthType Basic
AuthName "Password Required"
AuthUserFile passwords.file
AuthGroupFile groups.file
O arquivo Senha.File contendo as senhas pode ser criado usando o htpasswd
ferramenta que veio com Apache. O arquivo groups.File Deveria gostar a este:
GroupName: rbowen dpitts sungo rshersey
Aqui você basicamente apenas liste os usuários que devem ter acesso ao diretório.
Por favor, veja também isto tutorial.
Outras dicas
Você está tentando iniciar o download depois de ter o script echos "Você fez login com sucesso como ..."?
Você não pode definir cabeçalhos depois de produzir nada para tela. Assim que você ecoa ou imprimiu ou o que você tem, você iniciou a parte do corpo da resposta HTTP, o que significa que os cabeçalhos foram definidos.
A propósito, se você tentar definir os cabeçalhos e, em seguida, fornecer o bit "Você está conectado", que ficará preso no arquivo, não é saída na tela.
O que você quer fazer é ter a saída de script "você está conectado" e o redirecionar para o script que envia os cabeçalhos de download. O usuário não verá a segunda página, pois o cabeçalho está definido como "anexo". É assim que o seu típico "seu download começará momentaneamente" funciona.