How to fix Laravel 403 forbidden storage error
If you keep getting 403 forbidden error on your Laravel storage files and you want to know how to fix this, you have landed on the right site.
403 forbidden error is typically when you do not have enough permission to read a file and it happens mostly on live servers (on production).
I was working on a Laravel project that allows users to upload and share files. To manage all user’s files, I am creating a sub-folder for each user with his ID. For example, if the user ID is 2, a folder named “2” will be created inside the storage sub-folder “files”. So the complete path to that folder will be: “storage/app/public/files/2”. I got this error due to permission of sub-folder “2”. I managed to fix it after a few hours, so I thought I might share the solution with others and it might help someone.
Note: The project I was working on was the Multi-purpose platform.
If you are seeing this error on your localhost, try running the following command:
php artisan storage:link
The solution that works for me is to set the permission of the parent folder as soon as the file is uploaded.
$file_path = "folder_name/" . $file->getClientOriginalName(); // storage/app/public/folder_name/file.png
$file->storeAs("/public", $file_path);
// Get the full path to the folder
$full_path = storage_path('app/public/folder_name');
// Set permissions using PHP's chmod function
chmod($full_path, 0775);
This will ensure to give the read, write, and execute permission to the folder, not the files inside it. If you give the execute permission to the file, then a hacker can put a malicious file in it and execute it.
You might need to delete the folder “folder_name” and try again, it should work fine now. So that’s how you can fix the 403 forbidden error on your Laravel storage files. If you face any problem in following this, kindly do let me know.