I use Laravel Storage::putFile()
when I store uploaded files and I like the convenience of it's automatic unique file name and how it takes care of file extension.
Now I want to get a file from a remote server (file_get_contents($url)
) and store it like I did for uploaded files, but I don't find any equal method in the docs.
In https://laravel.com/docs/5.5/filesystem#storing-files in the put
method, you have to specify the file name.
$filename = uniqid(). '.' .File::extension($file->getClientOriginalName());
//uniqid() is php function to generate uniqid but you can use time() etc.
$path = "Files/Images/"
Storage::disk('local')->put($path.$filename,file_get_contents($file));
If you have an UploadedFile
instance you can also use $file->hashName()
https://laravel.com/api/5.5/Illuminate/Http/UploadedFile.html#method_hashName
https://github.com/laravel/framework/blob/5.5/src/Illuminate/Http/FileHelpers.php#L52
To be sure the filename is unique and to get the extension of your file url, you can do like this :
$ext = pathinfo($url, PATHINFO_EXTENSION);
$filename = bcrypt($url).time().'.'.$ext;
If anynone is looking for the default Laravel unique filename generator, behind the scenes Laravel uses Str::random(40)
to generate a unique filename when you're uploading a new file.
Here is the method store
used on UploadedFile
instance when you store a new file:
namespace Illuminate\Http;
/**
* Store the uploaded file on a filesystem disk.
*
* @param string $path
* @param array|string $options
* @return string|false
*/
public function store($path, $options = [])
{
return $this->storeAs($path, $this->hashName(), $this->parseOptions($options));
}
The hashName()
method came from the Trait FileHelpers.php
namespace Illuminate\Http;
/**
* Get a filename for the file.
*
* @param string|null $path
* @return string
*/
public function hashName($path = null)
{
if ($path) {
$path = rtrim($path, '/').'/';
}
$hash = $this->hashName ?: $this->hashName = Str::random(40);
if ($extension = $this->guessExtension()) {
$extension = '.'.$extension;
}
return $path.$hash.$extension;
}
So if you follow the same logic as Laravel you can basically use Str::random(40)
Laravel's helper to generate a unique filename, for more uniqueness you can append the current datetime to the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With