Welcome Guest, Not a member yet? Register   Sign In
How to access images under writable folder
#15

(This post was last modified: 09-16-2023, 10:15 AM by dgvirtual.)

This might be useful to some, so here is how to properly keep image files (or other files) not in public dir but in writable dir, still loadable in html (but also, if needed, restricting public access to them):


1. Place image files in writable/uploads/img

(e.g., I have there an image named profile-9.jpg and another image placeholder.jpg )


2. Make a special controller method to access those files. Here is mine (controller class name, lets say, is Files):
PHP Code:
    public function profile(int $id) {
        $path WRITEPATH 'uploads/img/';
        $name 'profile-' $id '.jpg';

        if (!file_exists($path $name)) {
            $name 'placeholder.jpg';
        }
        return $this->response->download($path $namenull);
    

(more on the usage of the response::download method - here in the docs)


3. Use the route /files/profile/9 to access the image in the html src property, for example like this:

Code:
<img src="<?=base_url('files/profile/' . $id) ?>" />
The added bonus in my case is that, if the expected image is not there, the placeholder image is loaded instead. But that is a matter of implementation.
==

Donatas G.
Reply


Messages In This Thread
RE: How to access images under writable folder - by dgvirtual - 09-16-2023, 10:12 AM



Theme © iAndrew 2016 - Forum software by © MyBB