We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Protect image so that only auth user can access image - help!

When a user logs in they can view images they have uploaded (these images are not in a public folder), a user cannot see another users images.

In procedural php i can use something like this (i'll also check whether the user can have access to the image):

$file_path ='my-private-folder/avatar.jpg';
header("Content-Type: image/jpeg");
readfile($file_path);
exit();

and then I would call it by <img src="image.php">

The problem i'm having is:

  1. The above would display a blank page and just the image, but I need this to be accessible so I can place the image in a table (ie. place the image in full web template wherever I want).

  2. I need to do the above in oop in phalcon, so how do I access the image from the view?

Thanks

You can do the same with Phalcon:

class ImageController extends \Phalcon\Mvc\Controller
{
    const IMAGE_MISSING = __DIR__ . '/../../../../../web/assets/image-missing.png';

    public function serveAction($id)
    {
        $this->view->disable();
        $image = Image::findFirstById($id);
        $path = self::IMAGE_MISSING;
        if ($image) {
            if ($image->isLocal()) {
                $path = $this->config->application->imgDir . $image->getPath();
                if (!is_readable($path)) {
                    $path = self::IMAGE_MISSING;
                }
            } else {
                $path = $image->getPath();
            }
        }
        $mime = mime_content_type($path);
        $baseName = basename($path);
        $disposition = 'inline';
        if ($this->request->hasQuery('download')) {
            $disposition = 'attachment';
        }
        $this->response->setFileToSend($path);
        $this->response->setHeader('Content-Type', $mime);
        $this->response->setHeader('Content-Disposition', $disposition . "; filename=" . $baseName . "");
        $this->response->send();
        exit;
    }
}

In case it's not clear to everyone, Lajos' code would be referenced in Volt like this:

<img src = "{{ url('/image/serve/23') }}" />