简体   繁体   中英

View file via controller, not via direct access. htaccess?

In my view I have a link that allow the user to view a file in a new window:

<li>
  <a href="/files/fileview/<?php echo $files_selectallrow->fileid; ?>" target="_blank">
    <i class=" icon-file-eye"></i>
    View this file
  </a>
</li>                                           

This loads the file via the controller, which displays the file in a view:

Controller:

//Load model
$this->load->model('files/files_model');        

//Lookup file
$file = $this->files_model->findfilebyid($fileid);

//Get data      
$data['file'] = base_url(). '' . $file->filenamepath."/".$file->filename.".".$file->filetype ;
$data['header'] = $file->filetypeheader;

//Load view
$this->load->view('portal/files/fileview_view', $data); 

View:

// Let the browser know what file is coming.
header("Content-type: ".$header);
header("Content-Length: " . filesize($file));

// Send the file to the browser.
readfile($file);

This works perfect, as it should. Now of course, by default, you could be able to view the file, by accessing it via the direct url, for instance: http://www.example.com/filestorage/myfile.pdf

I wanted to prevent this by adding a .htaccess file with a Deny from all rule. However, this also blocks the view for viewing my file...

I am kind of lost how I should approach this. Should I keep the Deny from all .htaccess rule, and display my file another way, or, should I adapt the .htaccess file so it denies all, except from my view?

Thanks

This is because you're still accessing the file using its URL, your should use the actual filepath to read the file.

Normally that's instead of base_url() you'd use './' which means it will start from the location where you put your index.php file.

And You don't need a view here, You should put that code in your controller; having a view here serves no purpose at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM