Makan
Makan

Reputation: 2736

Private Temporary Storage Directory in Laravel

With Laravel, I assume that the storage/ folder is a good place to unzip some temporary files into. So in the code, I mentioned this path: storage/tempdir. Like the following:

$zip = new ZipArchive();
$zip->open($request->excelFile->path());
$dir = "storage/tempdir";
$zip->extractTo($dir);

But the unzipped files end up in public/storage/tempdir/

This way they are accessible for public, and I don't want that.

How can I refer to storage/tempdir on both my Windows and Linux machines? tnx.

Upvotes: 5

Views: 17606

Answers (3)

Humble Hermit
Humble Hermit

Reputation: 133

The extractTo function would always create a folder in the storage/public directory.

I used William's suggestion but had to prepend the app/ folder to the directory and that did the trick. For this example it would be something like this;

$zip = new ZipArchive();
$zip->open($request->excelFile->path());

$dir = "storage/tempdir";

if (!Storage::disk('local')->exists($dir)) {
    Storage::makeDirectory($dir);
}

$this->zip->extractTo(storage_path('app/' . $dir));
$this->zip->close();

I haven't tested it with multiple concurrent extractions.

Laravel 10.x.

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Use storage_path() helper:

$zip->extractTo(storage_path('tempdir'));

Upvotes: 8

bilogic
bilogic

Reputation: 667

https://github.com/spatie/temporary-directory

This package offers a better solution as it allows multiple concurrent extractions without their files being mixed into the same fixed folder of storage_path('tempdir')

Using a fixed folder may work for simple cases, but once scaled up, the issues it creates are hard to troubleshoot and debug.

Upvotes: 2

Related Questions