image protection in codeigniter

2020-02-16 05:18发布

I am using the following code in my controller:

//function to protect images from being accessed directly.
function getImage($img_id){


      //code to authenticate user goes here then...
$url = $this->data['base_url'].'system/application/images/c/thumbs/';

$filepath = $url.$img_id;

    header("Content-type: image/jpeg");
  if(file_exists($filepath)){
    echo "we are here";
        $img_handle = imagecreatefromjpeg($filepath) or die("");
    echo $img_handle;
        ImageJpeg($img_handle);
    }



    }

In my view to fetch the images, I have used the following code:

<img src='<?php echo base_url(); ?>index.php/Controller/getImage/obama.jpg' width="100px"> 

Now even though it is going into the controller, it is not displaying the image. The Obama file is in the correct directory. I have no idea why.

2条回答
我只想做你的唯一
2楼-- · 2020-02-16 05:20

you sure the image can be accessed via $this->data['base_url'].'system/application/images/c/thumbs/obama.jpg , you tried accessing it on browser, right?

Also, avoid printing text before rendering the image, it may corrupt the image.

If still doesn't work, let us know the error page screenshot, whats its saying.

查看更多
够拽才男人
3楼-- · 2020-02-16 05:43

Your problem is that you are outputing text to the browser, and then the image. The browser will try to render the image but it will be corrupted.

header("Content-type: image/jpeg");
if(file_exists($filepath)){
    echo "we are here";
    $img_handle = imagecreatefromjpeg($filepath) or die("");
    echo $img_handle;
    ImageJpeg($img_handle);
}

Also, if you want to do an echo you can't send an header saying "hey, this is a jpeg image".

查看更多
登录 后发表回答