Create file object from remote file

I was struggling with this topic recently, so for the benefit of any future readers:

Based on that plugin, I came up with this pattern for my Kirby 5 project:

//  Fetch the remote file
$url = ''; // the url to some remote image
$response = Remote::get($url);
if ($response->code() !== 200) throw new Exception('...'); // handle error

//  Get the content
$fileContent = $response->content();

//  Write to temporary file
$tempRoot = ''; // maybe a `$page->root()`
$tempSlug = ''; // memorable identifier
$tempFile = "$tempRoot/$tempSlug";
F::write($tempFile, $fileContent);

//  Determine file extension (if you don’t know already)
$mime = F::mime($tempFile);
$fileExtension = F::mimeToExtension($mime);

//  Create the file in the correct place
$filename = '';
$file = File::create([
  'parent' => $page, /* or somewhere else */
  'source' => $tempFile,
  'filename' => "$filename.$fileExtension",
  'template' => 'image', /* or another file template */
], true);

//  Get the file UUID
//  You could use this to update a `files` field
$fileUuid = $file->uuid()->toString();

The plugin does a much more thorough job at handling errors and edge cases, so I’d recommend checking out the source if not using it directly.