简体   繁体   中英

Codeigniter : Protect folder from direct access

Hello guys I have a small project connected with a database.I own a function for uploading files into a folder and also save files path to the database. In my index page I read files path from database and output a table with links to these files for downloading. Everything works fine and files are able to be downloaded unless, the problem is that I forgot to secure this folder and yesterday realized that I should protect it somehow because people can download files directly with links and I need to check if user is logged to be able to download it.

So my question is: How to protect the folder with these files from direct access and make only logged users to be able to download files from this folder

My upload path is./uploads/ inside this folder I had htaccess file

order deny,allow
deny from all

In controller I have

public function viewAllPersons() { if($this->ion_auth->logged_in()) { if(;$this->ion_auth->in_group(1)){ show_404(); } else { $data = array(); $data['persons'] = $this->get_persons(); // get all persons from database as array $this->load->view('admin/header_view'), $this->load->view('admin/persons_view';$data); // pass data to the view $this->load->view('admin/footer_view'); } } else { redirect(base_url()); } }

My view file contains this

{

    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
      <h1 class="page-header"><span class="glyphicon glyphicon-th-list"></span> Archive</h1>
      <h2 class="sub-header pull-left">All records db</h2>
     <a href="<?=base_url('dashboard/persons/add');?>" class="add-button pull-right btn btn-success"><span class="glyphicon glyphicon-plus-sign"></span> Add new record</a>

       <form class="navbar-form navbar-right" method="post" action="<?=site_url('dashboard/persons');?>" name="searchform" >
          <div class="form-group">
              <input type="text" id="search" name="search" class="form-control" placeholder="" autocomplete="off"> 
          </div>
          <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
      </form>

      <div class="clearfix"></div>
      <div class="table-responsive">

        <table class="table table-striped">
          <thead>
            <tr>
              <th>#</th>
              <th>Firstname</th>
              <th>Middlename</th>
              <th>Lastname</th>
              <th>ID</th>
              <th>Filename</th>
              <th>Data</th>
              <th>Options</th>
            </tr>
          </thead>
         <tbody>
            <?php 
            $counter = 1;
            foreach($persons as $person) { ?>
            <tr>
              <td><?=$person['person_id'];?></td>
              <td><?=$person['first_name'];?></a></td>
              <td><?=$person['middle_name'];?></td>
              <td><?=$person['last_name'];?></td>
              <td><?=$person['personal_number'];?></td>
              <td><a href="<?php echo base_url('/uploads/'.$person["document_path"]) ; ?>"><?=$person['document_path'];?></a></td> <!-- show links to files for each row !-->
              <td><?=$person['created_on'];?></td>
              <td>
                <a href="<?=base_url('/dashboard/persons/edit/'.$person['person_id'])?>">
                  <span class="glyphicon glyphicon-pencil edit-icon"></span>
                </a>
              </td>
            </tr>
           <?php $counter++; } ?>
          </tbody>
        </table>
        <div class="row">
          <?php if(isset($links)) {
            echo $links;
          }?>
        </div>
      </div>
    </div>
      <?php } ?> }

Here is my problem when I output links to files I need to check if user is logged before to be able to download files using the links saved in database

Example of project -- picture

Because people can download files with direct link Example

http://website.com/uploads/document.docx

Once I have htaccess file I`m unable to download a file need maybe a function to rewrite rules or to give access to logged users somehow

I also tried a download helper from codeigniter but download files only if I remove the htaccess rules If rules exist inside htaccess file download helper is unable to download the file. Thanks in Advance!

You have a few possibilities, the simplest one would be to have control of the access of these folders with a Controller.

You need a file table with minimum: id , path . Let's say user A wants file ABC.jpg (with the id of 1337): Instead of serving him http://example.com/uploads/ABC.jpg , you give him http://example.com/files?id=1337 .

This route calls the index of controller Files and in the index you can do this pseudo-code:

function index() {
    //Check if logged in
    if (!$user->logged()) {
        redirect('/404');
    }
    //Get file from database
    $file = $this->db->query('SELECT * FROM file WHERE id='.$this->input->get("id"))->result();
    //Then serve the file
    header("Content-type: image/jpeg");
    readfile($file->path);
}

EDIT:

I will try to explain it in other terms:

  1. Create a table of uploaded files called file . Something like

    CREATE TABLE file (id INT NOT NULL AUTO_INCREMENT, path VARCHAR(100) NOT NULL, PRIMARY KEY ( id ))

  2. Update your person table so that it doesn't have the document_path but file_id instead. And when you upload a file, you save it's path in the table file then assign the file id to the person (in table person of course).

  3. Instead of <?php echo base_url('/uploads/'.$person["document_path"]);?> , you need to do <?php echo base_url('/file?id='.$pseron['file_id']);?>

  4. This is because we want the user to go to a specific controller that you need to create File.php (the controller).

  5. In this controller, the function index (the default function of the controller File) must do something like I showed you before the edit. It means you retrieve from the database the file path based from the file id, then you serve the file. This is called PHP serving instead of Apache (default) serving of files.

I was facing the same problem because my files were directly accessed by the users. especially uploads files and images. I was working on a PHP framework.

I simply added one line of code in the .htaccess file. and it was done. If you don't have one in your WEBSITE FOLDER then create a.txt file and name it as .htaccess (if you are not using any framework). then open the.htccess file and simply write: Options -Indexes NOTE: DON'T PUT .htaccess file in any folder just simply open your website folder in htdocs and create .htaccess

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