Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the images in Codeigniter but restricting URL to non users

I have images on my server that are uploaded by users within a group. I want to restrict the access to these images publicly by typing the absolute URL to the image. Access to these images should only be granted if the user is logged in to the system.

I am using CodeIgniter as a framework, and would like the restriction to be on the controller rather than the view. Right now I could not fetch these images on the view.

Here is my structure:

      application
                - <images_folder>
      system

1 Answers

  1. Place all your photos in a folder outside the applications folder

application
assets
assets > images_folder 
system

  1. Create a .htaccess file on this folder and type Deny from all

  2. Create a controller to access these images


<?php

class Preview extends CI_Controller {

    function show_image($image_filename) {

       $img_path = <path_to_your_img_folder> . $image_filename;

       $fp = fopen($img_path,'rb');
          header('Content-Type: image/png');
          header('Content-length: ' . filesize($img_path));
         fpassthru($fp);
    }
}
  1. Create the proper restrictions on the function mentioned above ie: check for a user session etc.
  2. Access the images through the controller. eg on your view write:

<img src="<?=base_url(preview/show_image/img.png)?>" />

Hope this helps

like image 105
Elymentree Avatar answered Dec 09 '25 22:12

Elymentree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!