How to Protect Upload and Secure PDF Files in Laravel

  1553 views   7 months ago Laravel

In this article, i will apportion with you how to make secure and bulwark your file in laravel and only sanction to access authenticated users. 

As you ken when you work with any web applications then the file uploading functionality is the most consequential part in that application and also you require to ascertain that uploaded files very important to secure from direct access from the URL. so, in this article, we will visually perceive how to forfend and secure files in laravel and only accessible to authenticated users.

You just need to follow the steps.

Step - 1 : Create Controller

First, we need to create a controller by running the following artisan command in your laravel application root directory.

php artisan make:controller FileController

then open /app/Http/Controllers/FileController.php file and add the following code into it.

namespace App\Http\Controllers;

class FileController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function view($id)
    {
        $file = storage_path('app/pdfs/') . $id . '.pdf';

        if (file_exists($file)) {

            $headers = [
                'Content-Type' => 'application/pdf'
            ];

            return response()->download($file, 'Test File', $headers, 'inline');
        } else {
            abort(404, 'File not found!');
        }
    }
}

Step - 2 : Create Route

Route::get('/preview-file/{id}', [FileController::class, 'view']);

i hope you like this small article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]