Images Object is empty after CURL Request

I load images via CURL into my Kirby instance. This works also wonderfully. Strangely the image is saved, but $page->files() remains empty. Only after a refresh the image is displayed. Does anyone happen to have an explanation for this?

$filename = uniqid(rand(), true);
$saveto = $kirby->root('content') . '/test/' . $filename . '.jpg';
$url = 'https://example.com/image.jpg';

$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw = curl_exec($ch);
curl_close ($ch);
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);

dump($page->files());

That’s because at the time the script runs, the new files are not yet part of the files object. You would have to add the file to the files object first, or reload the page.

Ahh ok! So you mean I should integrate: new File() | Kirby CMS? Could that work? Or should I use File::create() | Kirby CMS?

Ok, not very elegant but it works for now. Is there a way to overwrite the file with File::create()? Just adding a number and then deleting the old file isn’t exactly the best way I think, is it?

$filename = uniqid(rand(), true);
$saveto = $kirby->root('content') . '/test/' . $filename . '.jpg';
$url = 'https://example.com/image.jpg';

$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw = curl_exec($ch);
curl_close ($ch);
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);

$kirby = kirby();
$kirby->impersonate('kirby');
File::create([
  'source' => $saveto,
  'parent' => $page,
  'filename'   => $filename . '2.jpg',
  'template' => 'default'
]);
unlink($saveto);