サンプル集  >  PHP  >  ダウンロードC
ダウンロードC
2009/06/19

php でファイルをダウンロードすることはできました。

◆環境
OS Windows XP Professional Version 2002 Service Pack 2
PHP 5.2.4
WebServer AN HTTP Daemon 1.42p

実際に使用する場合、ダウンロードphp 本体はどこか1箇所に置いてパラメータでファイル名を渡すようにしたいと思います。

DocumentRoot
+ tool
| + download2.php      ・・・ダウンロードphp
|
+ YMWPHP
  + P0
    + W4
      + P046
        + dltest.html  ・・・ダウンロードページ
        |
        + src
          + out.php    ・・・ダウンロードしたいファイル

ダウンロードページこんな感じです。

dltest.html
1: 
2: 
3: 
4: 
5: 
6: 
7: 
<html>
<body>
<a href="/tool/download2.php?fileName=src/out.php">
out.phpをダウンロードする
</a>
</body>
</html>

ダウンロードしたいファイル out.php を、ダウンロードするページ dltest.html から相対パスで指定してみました。 ダウンロードphp は DocumentRoot/tool 配下にあるので絶対パスで指定します。

ブラウザで、「http://127.0.0.1/YMWPHP/P0/W4/P046/dltest.html」へアクセスします。

ダウンロードを押下したらエラーが出ました。

Warning: filesize() [function.filesize]: stat failed for src/out.php in
 C:\public_html\tool\download2.php on line 3

Warning: Cannot modify header information - headers already sent by (ou
tput started at C:\public_html\tool\download2.php:3) in C:\public_htm
l\tool\download2.php on line 6

Warning: Cannot modify header information - headers already sent by (ou
tput started at C:\public_html\tool\download2.php:3) in C:\public_htm
l\tool\download2.php on line 7

Warning: Cannot modify header information - headers already sent by (ou
tput started at C:\public_html\tool\download2.php:3) in C:\public_htm
l\tool\download2.php on line 8

Warning: readfile(src/out.php) [function.readfile]: failed to open stre
am: No such file or directory in C:\public_html\tool\download2.php on
 line 10

src/out.php の stat に失敗しています。 ファイルがみつからない模様ですね。 カレントディレクトリは download2.php があるフォルダになっているのでしょうか?

試しに、tool 配下に src フォルダを作り、out.php を入れて再度やってみます。

できました!

ダウンロードしたいファイルを絶対パスで指定したらどうなるでしょうか。

dltest2.html
1: 
2: 
3: 

4: 
5: 
6: 
7: 
<html>
<body>
<a href="/tool/download2.php?fileName=/YMWPHP/P0/W4/P046/src/out.p
hp"
>
out.phpをダウンロードする
</a>
</body>
</html>

同じエラーがでました。。。 物理的な絶対パスにしてみます・・・

dltest3.html
1: 
2: 
3: 

4: 
5: 
6: 
7: 
<html>
<body>
<a href="/tool/download2.php?fileName=c:/public_html/YMWPHP/P0/W4/
P046/src/out.php"
>
out.phpをダウンロードする
</a>
</body>
</html>

ダウンロードできました! ただフルパスを毎回書くのはナンセンスですね。

カレントディレクトリを取得するメソッドがあったので、これを使えば上手くいくかもしれません。 phpのメソッドgetcwd()を使いますので、拡張子をphpに変えます。

dltest4.php
1: 
2: 
3: 

4: 
5: 
6: 
7: 
<html>
<body>
<a href="/tool/download2.php?fileName=<?php echo getcwd(); ?>/src/
out.php"
>
out.phpをダウンロードする
</a>
</body>
</html>

上手くいきました。

▲ PageTop  ■ Home


Copyright (C) 2012 ymlib.com