PHP下载文件已损坏(从ftp服务器下载时)

时间:2016-05-09 09:12:25

标签: php upload

我从特定文件夹下载文件(php)时遇到问题。

当我下载并打开文件时,它表示您的文件已损坏。

当我检查上传文件和下载文件的大小时,它是相同的,但对于zip文件大小,它是不同的。

没有文件正在打开。

任何人都可以说我错了吗?

if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) {
  $filename = $_GET['file'];
} 
else
{
  $filename = NULL;
}

$err = 'Sorry, the file you are requesting is unavailable.';
if (!$filename) {
// if variable $filename is NULL or false display the message
  echo $err;
} 
else 
{
// define the path to your download folder plus assign the file name
  $path = '/public_html/wp-content/uploads/'.$filename;
// check that file exists and is readable
  if (file_exists($path) && is_readable($path)) {
// get the file size and send the http headers
    $size = filesize($path);
    header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.$size);
    header('Content-Disposition: attachment;filename="'.basename($filename).'"');
    header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error messages if the file can´t be opened
    $file = @ fopen($path, 'rb');
    if ($file) {
// stream the file and exit the script when complete
      fpassthru($file);
      exit;
    } else {
      echo $err;
    }
  } else {
    echo $err;
  }

  exit;

}

插入表格:

 echo "<tr><td><a href='?file=" . $row["FileupName"]. "'>".$row["FileupName"]."</td></tr>";

我很高兴该文件已下载但未打开。

.txt文件正在打开。

还用标题检查过。

我尝试过:

ob_clean();
flush();
readfile($file);

1 个答案:

答案 0 :(得分:1)

if (file_exists($path)) {

                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename=' . basename($path));
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($path));
                ob_clean();
                flush();
                readfile($path);
                exit;
            }