2014-01-19 86 views
1

我正在製作一個具有文件上傳功能的zend項目,並且客戶端想要在沒有擴展名的情況下加密和上傳文件。我這樣做,完全通過使用下面的代碼:解密文件在Zend框架中上傳下載時

$upload = new Zend_File_Transfer_Adapter_Http(); 
$salt = $upload->getHash('md5', 'file_name'); 
$upload->addFilter('Rename', array('target' => APPLICATION_PATH . '/../../uploads/presentations/'.$salt)); 
$upload->addFilter('Encrypt', array('adapter' => 'mcrypt', 'key' => $constants->encryption_key)); 
$upload->receive(); 

這是工作的罰款,現在我只是下載文件用下面的代碼

$filename = 'example_presentation_file.ppt'; //original name in db. by the way this coming from database 
$hash = '85be69db87a43265a44be1482cc6d819'; //changed file name when uploaded with this 
$mime = 'application/octet-stream'; 
$file_path = APPLICATION_PATH . '/../../uploads/presentations/'.$hash; 
header('Content-Type: "'.$mime.'"'); 
header('Content-Disposition: attachment; filename="'.$filename.'"'); 
header("Content-Transfer-Encoding: binary"); 
header('Expires: 0'); 
header('Pragma: no-cache'); 
$size = filesize($file_path); 

if(isset($_SERVER['HTTP_RANGE'])) 
{ 
    list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2); 
    list($range) = explode(",",$range,2); 
    list($range, $range_end) = explode("-", $range); 
    $range = intval($range); 
    if(!$range_end) { 
     $range_end = $size-1; 
    } 
    else { 
     $range_end = intval($range_end); 
    } 
    $new_length = $range_end-$range+1; 
    header("HTTP/1.1 206 Partial Content"); 
    header("Content-Length: $new_length"); 
    header("Content-Range: bytes $range-$range_end/$size"); 
} 
else { 
    $new_length = $size; 
    header("Content-Length: ".$size); 
} 
@ob_end_clean(); 
$speed = false; 
$chunksize = ($speed?($speed * 1024):(1024 * 1024)) ; 
$bytes_send = 0; 
$buffer = ""; 
if ($file = fopen($file_path, 'r')) { 
    if(isset($_SERVER['HTTP_RANGE'])) { 
     fseek($file, $range); 
    } 
    while(!feof($file) && (!connection_aborted()) && ($bytes_send<$new_length)) { 
     $buffer = fread($file, $chunksize); 
     print($buffer); 
     flush(); 
     if($speed) {  
      if($type!=2) sleep(1); 
     } 
     $bytes_send += strlen($buffer); 
    } 
    fclose($file); 
} 

此代碼工作非常精細和下載文件但是當我用powerpoint打開該文件時,它不會打開它並顯示錯誤。

問題是,如果我禁用文件加密,我打開很好,但它是必要的。我只是想知道如何在運行時解密文件(就在用戶永遠不會下載它時)。

謝謝。

回答

1

我建議以下工作流程:

  1. 臨時解密加密文件並保存到某個地方
  2. 從文件系統發送解密的文件給客戶
  3. 刪除解密文件

例如:

<?php 

/* ... */ 

$options = array(
'adapter' => 'mcrypt', 
'key'  => $constants->encryption_key); 


$decrypt = new Zend_Filter_File_Decrypt($options); 

// temp. decrypt file and save it on the disc 
$decrypted_file_path = APPLICATION_PATH . '/../../uploads/presentations/'. $filename; 
$decrypt->setFilename($decrypted_file_path); 

// encrypted file location 
$decrypt->filter($file_path); 

/* your code: Send $decrypted_file_path to the client */ 

// remove decrypted file 
unlink($decrypted_file_path); 
+0

完全如我所想。有沒有其他方法可以做到這一點。順便說一句,謝謝你。 –

+0

@ ManishJangirBlogaddition.com,我懷疑是否有另一種可行的解決方案 –