alidi's avatar
Level 1

check if the user own the file before show it

Hi I trying to make a middleware that shows the file for who only have the privilege to show it

I mean that is the user upload file, he only can show the file, if he sends the link for anyone else the file will not open

is anyone can help me by giving me the idea for do it?

thank you

0 likes
6 replies
Cronix's avatar

In conjunction with a policy (mentioned above), you'd have to have the images located in non public storage (so it's not accessible by going to yoursite.com/images/image-name.jpg), and they'd have to go through a controller. So instead of

<img src="/images/image-name.jpg">

You'd have a route set up and serve them like

<img src="{{ route('images', 'image-name.jpg') }}">

And you'd check in the controller whether the person has access to the image (owns it). If so, you'd just output the image from the non-public Storage.

1 like
jlrdw's avatar

I use this:

<?php
$basedir = '/your/folder/upload';
$imagedir = $_GET['dir'];
$image = $_GET['img'];

$file = $basedir.'/'.$imagedir.'/'.$image;
$fallback = $basedir.'/fallback.gif';
$size = filesize($file); // File size
$length = $size;
//DETERMINE TYPE
$ext = array_pop(explode ('.', $file));
$allowed['gif'] = 'image/gif';
$allowed['png'] = 'image/png';
$allowed['jpg'] = 'image/jpeg';
$allowed['jpeg'] = 'image/jpeg';

if(file_exists($file) && $ext != '' && isset($allowed[strToLower($ext)])) {
    $type = $allowed[strToLower($ext)];
} else {
    $file = $fallback;
    $type = 'image/gif';
}

header("Accept-Ranges: bytes");
header("Cache-Control: public");
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $length);
//header('Content-Disposition: inline; filename="' . $image . '"');
header("Content-Disposition: inline; filename=\"".$image."\";");
header("Last-Modified: " . date('r', filemtime($file)));

ob_clean();
readfile($file);
exit(0);

?> 

Usage

<img src="<?= 'http://somesite/laravel55/pthru.php?dir=imgdogs&img=' .  $row->dogpic; ?>" alt="" class="image">

Snapey also gave a good answer a while back, sorry I did not save link.

mironmg's avatar

Do you store the image paths in the database? If not, maybe you should consider storing them under a /images/USER_ID/ folder. And check whether the user_id from the path matches the auth()->user()->id

Otherwise, if the images are stored in the DB and there's a relationship between the image & user, add a policy.

alidi's avatar
Level 1

@CRONIX - hi

one question

how I can show the image from non-public storage

thank you

Please or to participate in this conversation.