1

私のウェブサイトには、ファイルのフルパスを表示せずにファイルのダウンロードを開始する 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 ダイジェスト認証を使用したい場合、どうすればよいですか? 上記のコードを次の行の後に記述しようとしました。...しかし、ヘッダーを2回変更できないというエラーが表示されます!

<?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;
}

?>

解決:

André と Anthony のおかげで、解決策を書くことができます。

<?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;
}

?>
4

2 に答える 2

1

スクリプトに「You have successfully login as ...」というメッセージが表示された後、ダウンロードを開始しようとしていますか?

画面に何かを出力した後は、ヘッダーを設定できません。echo または print または what-have-you を実行するとすぐに、HTTP 応答の本文部分が開始されます。これは、ヘッダーが設定されたことを意味します。

ちなみに、ヘッダーを設定して「ログインしました」ビットを指定しようとすると、画面に出力されずにファイルにスタックします。

あなたがしたいことは、「ログインしています」というスクリプト出力と、ダウンロードヘッダーを送信するスクリプトへのリダイレクトです。ヘッダーが「添付ファイル」に設定されているため、ユーザーにはその 2 番目のページは表示されません。これが、典型的な「ダウンロードがすぐに開始されます」ページのしくみです。

于 2009-10-10T18:38:21.443 に答える
1

これについては、必ずマニュアルを参照してください。

<?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
    }
}

更新

.htaccess ベースの認証は、実際には複数のユーザーによる使用を許可します。これを .htaccess に入れてください:

AuthType Basic
AuthName "Password Required"
AuthUserFile passwords.file
AuthGroupFile groups.file

パスワードを含むファイルpasswords.filehtpasswdは、apache に付属のツールを使用して作成できます。ファイルgroups.fileは次のようになります。

GroupName: rbowen dpitts sungo rshersey

ここでは基本的に、ディレクトリへのアクセス権を持つ必要があるユーザーをリストするだけです。

このチュートリアルも参照してください。

于 2009-10-10T17:44:21.223 に答える