File_get_contents():无法打开流:连接被拒绝

时间:2021-03-15 15:00:02

标签: php codeigniter download downloadfile

我正在尝试在 php codeigniter 中下载以前上传的文件、表单数据库和上传文件夹。我正在使用下面的代码,但下载的是空文件。

控制器.php

  public function downloadFile($incidents_id)
  {
  
   $file = $this->incidents_model->getfile($incidents_id);
  //echo $file; die;
  $this->load->helper('download');
  $path = file_get_contents(base_url()."uploads/".$file); //(the error shows on this line)
 // echo $path; die;
  $name = $file; // new name for your file
  // echo $name ; die;
   force_download($name, $path); // start download`
  
   }

事件_model.php

 function getfile($Incident_id )
 {
   $file = $this->db->select('file');
           $this->db->from('incidents');
           $this->db->where('incidents_id' , $Incident_id );
   $query =  $this->db->get();
  //  return $query->row();
  if ($query->num_rows() > 0) {
     return $query->row()->file;
 }
 return false;
  
 }

view.php

<div class="form-group col-md-4">
              <a href="<?=base_url('admin/incidents/downloadFile/' .$incidents->incidents_id)?>">Download file </a>
 </div>

因此运行此代码下载一个空文件。

<块引用>

echo $file;死;显示保存在db和uploads文件夹中的文件名

<块引用>

echo $path;死;产生一个错误: 严重性:警告

留言: file_get_contents(http://localhost:8080/ticketing_tool_v2/uploads/Screenshot 2021-03-04 at 5.59.38 PM.png):无法打开流:连接 拒绝

文件名:admin/Incidents.php

行号:380

2 个答案:

答案 0 :(得分:0)

查看 file_get_contents 的文档,您会发现可以通过多种不同的方式使用它。为了您的目的,您需要允许到文件系统的入站连接。

为了更好的未来证明而这样做的另一种方法是使用 CodeIgniter 文件助手 - https://codeigniter.com/userguide3/helpers/file_helper.html

答案 1 :(得分:0)

在从路径读取文件之前,请检查路径是否指向有效文件。

public function downloadFile($incidents_id) {

try {
    $this->load->helper('download');

    $file = $this->incidents_model->getfile($incidents_id);
     
    $data = file_get_contents(base_url("uploads/" . $file));

    $name = $file; // new name for your file
        
    force_download($name, $data); // start download`
     
} catch (Exception $e) {
    //exception handling code goes here
    print_r($e);
}

}
相关问题