下载时在Zend框架中解密文件上载

时间:2014-01-19 16:22:39

标签: php zend-framework file-io zend-form-element zend-file

我正在制作一个具有文件上传功能的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 个答案:

答案 0 :(得分:1)

我建议采用以下工作流程:

  1. 临时解密加密文件并将其保存在某处
  2. 解密文件发送到客户端
  3. 从文件系统中删除解密文件
  4. 示例:

    <?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);