Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with private images in laravel 5?

I am new to Laravel and trying to store private images so that only authenticated users can access them. Firstly I stored images in Public/UserImages folder. But here all the pictures are accessible to unauthenticated users as well by going to Inspect Element of chrome and then changing the user IDs. Kindly help out me...

like image 730
Hassan Saqib Avatar asked Feb 17 '15 13:02

Hassan Saqib


1 Answers

Following is how I solved the problem of storing images in Laravel 5 such that only authenticated users can view the images. People who are not authenticated will be directed to a login page. My server is a Ubuntu/Apache2 server.

  1. Create the directory /var/www/YOURWEBSITE/app/Assets/Images

  2. Add route to app/Http/routes.php.

    Route::get('/images/{file}','ImageController@getImage');

  3. Create a controller app/Http/Controllers/ImageController.php

    <?php
    namespace App\Http\Controllers;
    
    use App\Http\Requests;
    
    use App\Http\Controllers\Controller;
    
    use Illuminate\Http\Request;
    
    use Auth;
    
    class ImageController extends Controller {
    
        public function __construct()
       {
            $this->middleware('auth');
       } 
        public function getImage($filename) {
           $path = '/var/www/YOURWEBSITE/app/Assets/Images/'.$filename;
           $type = "image/jpeg";
           header('Content-Type:'.$type);
           header('Content-Length: ' . filesize($path));
           readfile($path);
    
        }
    
     }
    
  4. In your view you have img tags which have:

    src="{{ url('/images/test.jpg') }}"
    

This of course assumes test.jpg is a file in /var/www/YOURWEBSITE/app/Assets/Images/

You can of course add more logic such as not hardcoding the path of the images, etc. This is just a simple example to enforce authentication. Note the use of middleware('auth') in the controller constructor.

like image 149
ken koehler Avatar answered Oct 13 '22 22:10

ken koehler