重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

電子書籍の厳選無料作品が豊富!

普通(パスワード化されていない)のPDFをサーバーのあるディレクトリに保管しておきます。

CGIを使ってダウンロードさせたいのですが、
その際にそのPDFに毎回違う閲覧用パスワードをかけたいのです。
そんなことは可能でしょうか?

ちなみにPerl5.8で考えております。
CPANなどであればいいのですが・・

上記情報で不足している点などございましたらご指摘下さい。

A 回答 (2件)

ああ、なるほど。

使ったことないですけど、コマンドラインでパスワードを設定できるqpdfとかを使って、パスワード付きのpdfを一時ファイルとして作って、それを前で書いてあるようにバイナリ出力すればいいかもです。
    • good
    • 0

適当。

表示がずれるので空白2文字の全角空白にしていることに注意。

#!/usr/bin/perl -T
use strict;
use warnings;
use utf8;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Pretty;
use Encode;

use constant DOWNLOAD_DIR => '/tmp';
use constant BUFFER_SIZE => '100_000';

# file /tmp/aaa.txt requires password AAA
# file /tmp/bbb.txt requires password BBB
my %pass_of = ( 'aaa.txt' => 'AAA', 'bbb.txt' => 'BBB' );

my $q  = CGI->new();
my $file = decode( "utf8", $q->param('file') );
my $pass = decode( "utf8", $q->param('pass') );

if ( defined $file ) {
  if ( !exists $pass_of{$file} ) {
    print_download_page( $q, 'No such file' );
  }
  elsif ( $pass_of{$file} eq $pass ) {
    download_file( $q, $file );
  }
  else {
    print_download_page( $q, 'Password mismatch' );
  }
}
else {
  print_download_page($q);
}

sub download_file {
  my $q = shift;
  my $file = shift || '';

  my $file_with_full_path = DOWNLOAD_DIR . '/' . $file;
  if ( -r $file_with_full_path ) {
    print $q->header(
      -type    => 'application/octet-stream',
      -attachment => encode( "utf8", $file )
    );

    open( my $fh, '<', encode( "utf8", $file_with_full_path ) )
      or croak "$file: $!";
    binmode $fh;
    my $buffer = '';
    while ( read $fh, $buffer, BUFFER_SIZE ) {
      print $buffer;
    }
    close $fh or croak "$file: $!";
  }
  else {
    print_download_page( $q, "$file not found or readable" );
  }
}

sub print_download_page {
  my $q    = shift;
  my $message = shift;
  my $html  = << "END_HTML";
<!DOCTYPE html
 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitio …
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
 <head>
 <title> download test </title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 </head>
 <body>
  <form method="POST" action="" enctype="multipart/form-data">
   <input type="radio" name="file" value="aaa.txt" />Download aaa.txt
   <br />
   <input type="radio" name="file" value="bbb.txt" />Download bbb.txt
   <br />
   Password :
   <input type="password" name="pass" size="50" maxlength="80" /><br />
   <input type="submit" name="Download" value="Download" />
  </form>
  <hr />
  <p>$message</p>
 </body>
</html>
END_HTML

  print $q->header( -charset => 'UTF-8' ), $html;
}
    • good
    • 0
この回答へのお礼

さっそくのご回答ありがとうございます。

スクリプトを確認しました。
このコードはダウンロードする際にパスワードを入力させてダウンロードを可能にするという
ものですよね?

言葉足らずだったかもしれません。

ダウンロードする際のパスワードではなく、ダウンロード後PDFを開く際にに求められる
パスワードです。

お礼日時:2011/10/18 21:46

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!