2016-09-07 90 views
2
<?php 
// Make sure an ID was passed 
include('include/function.php'); 
if(isset($_GET['id'])) { 
// Get the ID 
    $id = intval($_GET['id']); 

    // Make sure the ID is in fact a valid ID 
    if($id <= 0) { 
     die('The ID is invalid!'); 
    } 
    else { 
     // Connect to the database 
     $dbLink = new mysqli('localhost', 'root', 'jio', 'jio'); 
     if(mysqli_connect_errno()) { 
      die("MySQL connection failed: ". mysqli_connect_error()); 
     } 

     // Fetch the file information 
     $query = " 
      SELECT `id`,`date`,`expected_date`,`comname`,`type`,`name`,`path`,`mime`, `size`, `data`,`other_detail`,`remark`,`username` 
      FROM `depository` 
      WHERE `id` = {$id}"; 
     $result = $dbLink->query($query); 

     if($result) { 
      // Make sure the result is valid 
      if($result->num_rows == 1) { 
      // Get the row 
       $row = mysqli_fetch_assoc($result); 

       // Print headers 

       header("Content-Type: ". $row['mime']); 
       header("Content-Length: ". $row['size']); 
       header("Content-Disposition: attachment; filename=". $row['name']); 


      } 
      else { 
       echo 'Error! No image exists with that ID.'; 
      } 

      // Free the mysqli resources 
      mysqli_free_result($result); 
     } 
     else { 
      echo "Error! Query failed: <pre>{$dbLink->error}</pre>"; 
     } 
     mysqli_close($dbLink); 
    } 
} 
else { 
    echo 'Error! No ID was passed.'; 
} 
?> 

我試圖從路徑位置(doc根目錄)下載文件,但得到空文件下載或損壞的文件下載。任何人都可以建議我在上面的代碼中出錯或使用其他任何東西。無法在Linux下使用php下載文件

+2

您正在發送標題,但您要在哪裏發送文件的實際內容? – jeroen

+0

打印數據 echo $ row ['path']; –

+0

檢查是否沒有其他輸出,如文件內容之前發送到輸出緩衝區的警告或字符。這會弄亂事情並使文件損壞。 – jannej

回答

0

在發送標題之後,您需要讀取文件內容併發送該數據 - 以下內容未經過測試,但是或多或少都是您需要執行的操作。您可能需要根據sql結果中$row['path']的內容調整$filepath變量。

if($result->num_rows == 1) { 
    $row = mysqli_fetch_assoc($result); 

    header("Content-Type: ". $row['mime']); 
    header("Content-Length: ". $row['size']); 
    header("Content-Disposition: attachment; filename=". $row['name']); 

    /* you need to actually read the file and send it */ 

    $filepath=$row['path'] . '/' . $row['name']; 
    if(!realpath($filepath)) exit('Filepath '.$filepath.' is incorrect'); 

    if($file = fopen($filepath, 'rb')) { 
     while(!feof($file) and (connection_status()==0)) { 
      print(fread($file, 1024*8)); 
      flush(); 
     } 
     fclose($file); 
    } 

} 
+0

已解決@RamRider –