1

Look at my code. This code store and read file from non-public dir but if I copied img url.

$filename = date('YmdHi') . self::setUser()->id . rand(1, 99999999);

$img = Image::make($file)
            ->encode($extension, 100)
            ->resize($width, $height, function ($constraint) {
                $constraint->aspectRatio();
            })
            ->stream();

$storage_path = storage_path('app/uploads/' . $path);
if(!Storage::exists($storage_path)){
    Storage::makeDirectory($storage_path, 0755, true, true);
}
file_put_contents($storage_path . '/' . $filename . '.' . $extension, $img);

$filename = $filename . '.' . $extension;

//read the file
$path = 'uploads/photo';
$image_path = storage_path('app/' . $path . '/' . $filename);
if (file_exists($image_path)) {
    $file = Storage::get($path . '/' . $filename);
    $type = mime_content_type($image_path);
    $base64 = base64_encode($file);
    $img = "<img src='data:{$type};base64,{$base64}'>";
    echo $img;
    exit;
}

I need to protect my file becouse user need to permission to display particular photo. Currently any user can copy this url and any guest without permission could display that. How can I protect my photos? I tested that in local (sail).

wtsuport
  • 315
  • 1
  • 3
  • 9
  • 1
    You'll need to check to make sure that `Auth::user()` matches the user ID of the photo's owner. However, right now you don't have an easy way to check. `2023032715391225312` -- Does this belong to user 1, 12, 122, 1225, or 12253?. – aynber Mar 27 '23 at 19:39
  • 1
    Don't store the files inside the site's docroot at all. Use a PHP script to serve them and you can check authentication/authorization there. – Sammitch Mar 27 '23 at 19:41
  • 1
    @Sammitch Being Laravel, `storage_path()` wouldn't be in docroot, unless they've misconfigured their .htaccess. – aynber Mar 27 '23 at 19:42
  • @Sammitch I don't understand you. I store file on Storage/app/photo. Could you show nie na example? – wtsuport Mar 27 '23 at 19:50
  • https://docstore.mik.ua/orelly/webprog/pcook/ch15_09.htm, https://stackoverflow.com/questions/21647750/how-to-view-images-from-protected-folder-with-php – Sergey Ligus Mar 27 '23 at 19:59

0 Answers0