【发布时间】:2016-04-28 15:49:26
【问题描述】:
我从未编写过 PHP 下载文件脚本,也没有任何经验,我真的不是专业人士。我从另一个网站获得了您可以在下面看到的代码的 sn-p 并尝试使用它。我了解脚本中写的内容,但我只是没有收到错误消息,或者更确切地说,我不知道如何防止这些错误。
这是 download.php 脚本 - 我已将其放入我的主域下方的 /download/ 文件夹中:
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "/downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
现在在 /download/ 文件夹中,其中包含 download.php 我有一个文件夹 /downloads,其中包含应下载的 .pdf。
我在网页上使用的链接是: PHP download file(为什么不显示,包括 4 个空格:
现在点击链接时出现以下错误:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(/downloads/test.pdf): failed to open stream: No such file or directory in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
如果我对 $path 变量使用绝对路径 (https://www.my-domain.de/downloads/),我会收到以下错误:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /var/www/xxx/html/download/download.php on line 12
Warning: fopen(https://www.my-domain.de/downloads/test.pdf): failed to open stream: no suitable wrapper could be found in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
感谢您的任何建议!
【问题讨论】:
-
您正在尝试将您的 php 脚本用作一般 Web 代理,并且在您的 php 配置中禁用了必要的后端支持。您在代码中也没有任何错误处理,因此每当出现故障时,您只会继续犯错,从而导致进一步的错误。例如fopen() 失败,但您认为它永远不会,因此尝试使用 fopen 返回的布尔 FALSE,就好像那是一个有效的文件句柄
-
嗨,Marc B,正如我所说,对于这些下载脚本,我真的不是那么先进;如何在我的 php 配置中启用后端支持,或者如果不作为一般 Web 代理,我该如何使用它?或者我必须咨询我的提供者吗?实际上我只是按照该网站上解释的步骤进行操作..仍然失败:(。感谢您的建议!
-
@Vic 非常感谢!
-
@Franky2207 这意味着你解决了你的第一个问题,然后发现了你的第二个问题 :) 这完全不相关,通常发生在你已经用“echo”输出了一些东西时,或者只是一个空行, 在发送标头之前(例如“Location:”)