Create file object from remote file

Is it possible to create a file object using File::create() from an image in a remote server? I have tried passing the remote url as “source” in File::create() but I get an error message that: ‘The file could not be created’.

Creating/updating etc. of stuff is only possible with authentication, have you tried that?

// authenticate as almighty
kirby()->impersonate('kirby');

you can download the file using remote::get() (see source)

after impersonating a user you can create file for page.

1 Like

Ok, done! I was trying to download the image and create a file object in one step using File::create().
For future reference you need to first get the file with Remote::get, then save it with File::write and then create the object with File::create.
thanks a lot!

Any chance I can see what that would look on paper…

<?php 
$remote_img = "https://google.com/images/kitty.jpg";
...

What do you mean?

Sorry. I was requesting an example of what this would look like when coding it out. I have a variable that holds a path to a remote image. It’s huge. I want to turn that image into a file object then use Kirby’s resize helper on it. Just looking for an example to better understand.

I know I’m late to the party, but … as @Cuboctaedro wrote:

For future reference you need to first get the file with Remote::get, then save it with File::write and then create the object with File::create.

Simple as that!

@S1SYPHOS, Thanks for sharin’ your insight on this.

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.