CakePHP中file_get_contents()的奇怪行为

时间:2015-04-28 09:33:43

标签: php cakephp file-get-contents

我过去使用过file_get_contents()来下载CakePHP的文件,效果很好。

但是,我正在开发一个新站点,当我使用file_get_contents()下载csv或zip文件(还没有尝试过其他文件)时,我会在客户端机器上创建的文件的开头标记奇怪的内容

使用notepad ++看起来好像:

LF TabTabTabSpaceSpaceLF TabTabTabSpaceSpace

正在加入。并且下一行文本似乎是缩进的(但这可能只是记事本++如何解释上面的字符 - 或者可能还有其他字符没有被记事本++显示!)

我看了看我的控制器并查看是否有东西被添加但是我真的看不到任何不幸的事情。

之前有没有人见过这样的行为,如果有的话,你是否发现了导致它的原因?

(我完全理解这可能只是我编写的错误,但我想保留这个简短的问题,而不是包含大量的代码..)

非常感谢

以下是我认为相关的代码片段:

在config / routes.php

Router::parseExtensions('csv');
Router::parseExtensions('pdf');
Router::parseExtensions('zip');
AppController.php中的

class AppController extends Controller {
//...

    public $components = array(
        'Session',
        'Acl',
        'RequestHandler',
        'Paginator'
    );

在相关模型的控制器中:

public function add_download($pass){
//create a record in the database table VisitDownloads
//recording who is downloading what and when

$this->loadModel('JournalArticleDataset');
$this->VisitDownload->create();
$this->VisitDownload->set(array('visit_id' => $this->Session->read('Visit.id'),
'journal_article_dataset_id' => $this->request->params['pass'][0],
'download_time' => date('Y-m-d H:i:s')));
//record is saved to database
$this->VisitDownload->save();
//build filename string to identify fully the resource being downloaded,
// then download
$filename = $this->JournalArticleDataset->get_filename($this->request->params['pass'][0]);
$filestring = "/files/".$filename;
if(substr($filename,-3)=='csv'){
header('Content-Type: text/plain');
header("Content-Disposition: attachment; filename=\"". substr($filename,0,strlen($filename)-4) ."_".date('Y-m-d_H:i:s').".".substr($filename,-3)."\"");
}
if(substr($filename,-3)=='zip'){
header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename=\"". substr($filename,0,strlen($filename)-4) ."_".date('Y-m-d_H:i:s').".".substr($filename,-3)."\"");
}


$filecontent = file_get_contents($filestring);
echo $filecontent;
exit();
}

然后在视图中指向此操作的链接:

echo "<table class='rightmove'>";
foreach($journalArticle['JournalArticleDataset'] as $Datasets) :
$filestring = "/srv/www/actc.lshtm.ac.uk/public/openaccess/webroot/files/" . $Datasets['dataset_resource_name'];
$extension = pathinfo($Datasets['dataset_resource_name'], PATHINFO_EXTENSION);

?>
 <tr>
            <td><?php 

            $filesize = human_filesize(filesize($filestring), $decimals = 2);
            echo $this->Html->image("/fileicons/".$extension .".png", array('url'=>array('controller'=>'VisitDownloads', 'action'=>'add_download',$Datasets['id'])));
            echo "\r\n<small>(". $filesize .")</small>" ;
            ?></td>
            <td><?php echo $Datasets['dataset_resource_description']; ?></td>
            <td><?php echo $Datasets['dataset_resource_name']; ?></td>
            <td><?php echo $Datasets['licence_type']; ?></td>
</tr>
<?php
endforeach;
echo "</table>";

0 个答案:

没有答案