RuntimeException laravel 5.8 RuntimeException This driver does not support creating temporary URLs - laravel-5.8

RuntimeException This driver does not support creating temporary URLs.
I am trying to generating Temp Url for every request Laravel version 5.8 below code trying showing an error.
This driver does not support creating temporary URLs.
$url = "66.jpeg";
$url = Storage::disk('public')->url($url);
$url = Storage::disk('public')->temporaryUrl(
'66.jpeg', now()->addMinutes(5)
);

From my knowledge, temporaryUrl is a method used on a drivers such as s3 to create a temporary url for a privately stored asset.
If you would like to set a temporary url for a file, it may help to use Cache to temporarily store the path.
Cache can set a key/value for a set amount of time. A url can be create which links to an endpoint. Then endpoint can then be created which returns the contents of that file:
// Creating temp file index in cache
$image = '66.jpg';
Cache::put('/temp/' . $image, 300); // 5 minutes
Now in, for example, TempController.php (visiting http://example.com/temp/66.jpg):
public function show($image)
{
if (Cache::get('/temp/' . $image) && ! Storage::disk('public')->exists($image)) {
// not in cache or do not exist, maybe redirect...
};
return Storage::disk('public')->get($image);
}
This is a proof of concept however I hope this helps.

Related

Adding Image PHPWord in Laravel

So I want to add an header image to my document in PHPWord in Laravel.
So this is my code
public function generateDocx()
{
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$headerLogo = 'http://127.0.0.1:8000/img/logoAnevBulanan.png';
$section->addImage($headerLogo);
// Bunch of line to download the docx
}
And I got Maximum execution time of 60 seconds exceeded, when I try the other method from the documentation, I still got the same error. I try to use asset() helper from laravel and still did not work
Try getting your image using local path instead of URL
$source = file_get_contents('/path/to/my/images/earth.jpg');
$textrun->addImage($source);
Refer to documentation : https://phpword.readthedocs.io/en/latest/elements.html#images

How get cloudinary file url/other properties by public_id?

Saving images under cloudinary( with cloudinary-laravel 1.0) I keep public_id in my database
and I want to get url(http or https), size, dimaentainal of this file by public_id
At reading this
/**
* You can also retrieve a url if you have a public id
*/
$url = Storage::disk('cloudinary')->url($publicId);
at
https://github.com/cloudinary-labs/cloudinary-laravel
I got ERROR:
Disk [CLOUDINARY] does not have a configured driver.
But I save images to cloudinary with storeOnCloudinaryAs method and in my .env I have
CLOUDINARY_URL=cloudinary://NNNNNNNNNNNN:AErjB_-XXXXXXXXX
CLOUDINARY_UPLOAD_PRESET=ml_default
and default file config/cloudinary.php
My config/filesystems.php has no any cloudinary parameters and can it be reason of my error?
Also it seems very strange for me that Storage::was used in this case, but I did not
find how get file url/other properties by public_id ?
Edited 1:
I added line
...
CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider::class,
...
in 'providers' block of ny config/app.php and cleared cach.
But still got
"Disk [CLOUDINARY] does not have a configured driver."
error.
applying changes into .env and clearing cache I try to debug from which line error is triggered in file vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemManager.php as :
protected function resolve($name)
{
$config = $this->getConfig($name);
\Log::info( varDump($name, ' -1 $name resolve::') ); // IT HAS ‘CLOUDINARY’ value
if (empty($config['driver'])) {
throw new InvalidArgumentException("Disk [{$name}] does not have a configured driver.");
}
But what is source for $config in this file?
config/filesystems.php ? In this file I have no any CLOUDINARY block. maybe I need to add it? But in which format ?
Thanks in advance!
Setting driver to lowercase
$cloudinaryUrl = Storage::disk(strtolower($imagesUploadSource))
fixed this error.

Downloading files which were stored using the storage facade in laravel 5.4

I've noticed that the method Storage::download($path) is not available until Laravel 5.6. I would rather not create symbolic links since this appears to me to defeat the purpose of using the storage facade, might as well save the file in the assets folder (not sure how correct I am in saying this).
My question is, how can I download a file that I have saved using the storage facade and not make the file publicly visible through a URL link?
I use this:
$path = "/path/to/file/";
$filename = "my_file.pdf"
return response(Storage::disk('local')->get($path.$filename), 200)
->header('Content-Type', Storage::disk('local')
->mimeType($path.$filename)
);
Edit:
If to store you use:
$path=$request->file('file')->store('file');
that's going to store the file in the storage/app/file folder, with a name created by laravel. For example:
storage/app/file/7K5gIZvRVWbdBedRXEyVm5X1Ubz61vJZguFmERlT.jpeg
(Make sure the file has been stored).
And in DB you must save (I do not know how you're doing this, but it's the 'file' folder and the file name created by laravel):
file/7K5gIZvRVWbdBedRXEyVm5X1Ubz61vJZguFmERlT.jpeg
So, to download you have to make a route:
Route::get('/download', 'DownloadController#downloadFile')->name('download-file');
And a Controller method:
public function downloadFile()
{
     $path = // get the DB field
     return response(Storage::get($path), 200)
         ->header( 'Content-Type', Storage::mimeType($path) );
}
And you can add a link in a view:
<a href="{!! route('download-file') !!}" download>Download the file</a>

I can't find the implementation for Storage Facade in laravel

I'm new with laravel and I'm working in fileststem on laravel
(I want to do usual fileststem process like -make dir - copy - put -delete -ect)
I'm using laravel "Storage" Facade
but when i type
i referenced the class above like this in my code
use Illuminate\Support\Facades\Storage;
for example below :
if (file_exists(public_path($oldImage))) {
Storage::delete($oldImage);
}
nothing happens ,and when i refer to the class code i found this :
namespace Illuminate\Support\Facades;
/**
* #see \Illuminate\Filesystem\FilesystemManager
*/
class Storage extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'filesystem';
}
}
so where is the implementation and if you have alternative way to deal with
filesystem process rather than "Storage" facade ??
Storage is a facade and accesses the class Filesystem located here: vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php
As you can see in the official filesystem documentation the code snippets use Storage.
UPDATE:
You should add use Storage; to be able to use the Storage facade.
I recommend reading the Laravel 8.X docs to get an initial heads up: https://laravel.com/docs/8.x/filesystem
NOTE: Before you get too carried away, make sure you understand the difference between local and public.
For starters, you should make your first goal to upload a file and acquire the UploadedFile type.
You can access a single file via something like $request->file('name'), or an array of images via something like:
// $request->input('images')
foreach ($images as $image) {
\Log::debug($image->getClientOriginalName());
}
If your file upload can be single and/or multiple, I recommend going with the array approach because a single file wrapped in an array allows you to use the same syntax for single and multi uploads (ie: that foreach loop works fine with one image, no extra code).
Here's an example:
use Illuminate\Support\Facades\Storage;
$slug = 'davids-sandwich-photos';
foreach ($images as $image) {
Storage::putFileAs(
'images' .'/'. $slug,
$image,
$image->getClientOriginalName()
);
}
Storage::putFileAs() can take 3 parameters: directory, content, filename. You can see above in the code that I interpolated a mix of static and derived directory name. You could do something like 'images' .'/'. $slug .'/'. Auth::user()->id to save the file in /images/davids-sandwich-photos/11.
Then, check in your repo directory: /storage/app/ and look for the images directory.
You can manually delete the folders while testing to get your bearings straight.
That should be enough to get most people started.
To avoid using the Storage facade, you can use:
foreach ($images as $image) {
$image->storeAs(
'examples' .'/'. $slug,
$image->getClientOriginalName(),
'public'
);
}
--
Check out config/filesystems.php under the disks section if you want to start manipulating the drivers, but I'm not a DB admin expert here.
I also saved this along my journey: https://medium.com/#shafiya.ariff23/how-to-store-uploaded-images-in-public-folder-in-laravel-5-8-and-display-them-on-shared-hosting-e31c7f37a737. You might need that if you get stuck with something like symlinking.
<img
v-for="image in example.images"
:key="image.filename"
:src="`/storage/examples/${example.slug}/${image.filename}`"
>
NOTE: The important part with Vue JS is to use <img src="/storage/examples/slug/filename.jpg"> if your file is located in your repository as /storage/app/public/examples/slug/filename.jpg Pay close attention to every character.
The public_path function returns the fully qualified path to the public directory ie public directory inside the laravel application. When using Storage, the path is set to the storage/app directory.
if (file_exists(public_path($oldImage))) {
//public_path($oldImage) will check for file in public directory
Storage::delete($oldImage); //Will delete file in storage/app directory
}
The modified code should be
if(Storage::has($oldImage)){
Storage::delete($oldImage);
}

How to protect image from public view in Laravel 5?

I have installed Laravel 5.0 and have made Authentication. Everything is working just fine.
My web site is only open for Authenticated members. The content inside is protected to Authenticated members only, but the images inside the site is not protected for public view.
Any one writes the image URL directly can see the image, even if the person is not logged in to the system.
http://www.somedomainname.net/images/users/userImage.jpg
My Question: is it possible to protect images (the above URL example) from public view, in other Word if a URL of the image send to any person, the individual must be member and login to be able to see the image.
Is that possible and how?
It is possible to protect images from public view in Laravel 5.x folder.
Create images folder under storage folder (I have chosen storage folder because it has write permission already that I can use when I upload images to it) in Laravel like storage/app/images.
Move the images you want to protect from public folder to the new created images folder. You could also chose other location to create images folder but not inside the public folder, but with in Laravel folder structure but still a logical location example not inside controller folder. Next you need to create a route and image controller.
Create Route
Route::get('images/users/{user_id}/{slug}', [
'as' => 'images.show',
'uses' => 'ImagesController#show',
'middleware' => 'auth',
]);
The route will forward all image request access to Authentication page if person is not logged in.
Create ImagesController
class ImagesController extends Controller {
public function show($user_id, $slug)
{
$storagePath = storage_path('app/images/users/' . $user_id . '/' . $slug);
return Image::make($storagePath)->response();
}
}
EDIT (NOTE)
For those who use Laravel 5.2 and newer. Laravel introduces new and better way to serve files that has less overhead (This way does not regenerate the file as mentioned in the answer):
File Responses
The file method can be used to display a file, such as an image or
PDF, directly in the user's browser instead of initiating a download.
This method accepts the path to the file as its first argument and an
array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
You can modify your storage path and file/folder structure as you wish to fit your requirement, this is just to demonstrate how I did it and how it works.
You can also added condition to show the images only for specific members in the controller.
It is also possible to hash the file name with file name, time stamp and other variables in addition.
Addition: some asked if this method can be used as alternative to public folder upload, YES it is possible but it is not recommended practice as explained in this answer. So the same method can be also used to upload images in storage path even if you do not intend to protect them, just follow the same process but remove 'middleware' => 'auth',. That way you won't give 777 permission in your public folder and still have a safe uploading environment. The same mentioned answer also explain how to use this method with out authentication in case some one would use it or giving alternative solution as well.
In a previous project I protected the uploads by doing the following:
Created Storage Disk:
config/filesystems.php
'myDisk' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'private',
],
This will upload the files to \storage\app\uploads\ which is not available to public viewing.
To save files on your controller:
Storage::disk('myDisk')->put('/ANY FOLDER NAME/' . $file, $data);
In order for users to view the files and to protect the uploads from unauthorized access. First check if the file exist on the disk:
public function returnFile($file)
{
//This method will look for the file and get it from drive
$path = storage_path('app/uploads/ANY FOLDER NAME/' . $file);
try {
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
} catch (FileNotFoundException $exception) {
abort(404);
}
}
Serve the file if the user have the right access:
public function licenceFileShow($file)
{
/**
*Make sure the #param $file has a dot
* Then check if the user has Admin Role. If true serve else
*/
if (strpos($file, '.') !== false) {
if (Auth::user()->hasAnyRole(['Admin'])) {
/** Serve the file for the Admin*/
return $this->returnFile($file);
} else {
/**Logic to check if the request is from file owner**/
return $this->returnFile($file);
}
} else {
//Invalid file name given
return redirect()->route('home');
}
}
Finally on Web.php routes:
Route::get('uploads/user-files/{filename}', 'MiscController#licenceFileShow');
I haven't actually tried this but I found Nginx auth_request module that allows you to check the authentication from Laravel, but still send the file using Nginx.
It sends an internal request to given url and checks the http code for success (2xx) or failure (4xx) and on success, lets the user download the file.
Edit: Another option is something I've tried and it seemed to work fine. You can use X-Accel-Redirect -header to serve the file from Nginx. The request goes through PHP, but instead of sending the whole file through, it just sends the file location to Nginx which then serves it to the client.
if I am understanding you it's like !
Route::post('/download/{id}', function(Request $request , $id){
{
if(\Auth::user()->id == $id) {
return \Storage::download($request->f);
}
else {
\Session::flash('error' , 'Access deny');
return back();
}
}
})->name('download')->middleware('auth:owner,admin,web');
Every file inside the public folder is accessible in the browser. Anyone easily gets that file if they find out the file name and storage path.
So better option is to store the file outside the public folder eg: /storage/app/private
Now do following steps:
create a route (eg: private/{file_name})
Route::get('/private/{file_name}', [App\Http\Controllers\FileController::class, 'view'])->middleware(['auth'])->name('view.file');
create a function in a controller that returns a file path. to create a controller run the command php artisan make:controller FileController
and paste the view function in FileController
public function view($file)
{
$filePath = "notes/{$file}";
if(Storage::exists($filePath)){
return Storage::response($filePath);
}
abort(404);
}
then, paste use Illuminate\Support\Facades\Storage; in FileController for Storage
And don't forget to assign middleware (in route or controller) as your requirement(eg: auth)
And now, only those who have access to that middleware can access that file through a route name called view.file

Resources