File::create problem

I’m trying to create 2 files into a subpage like this (code below). But only the first image is created.

When i start with a fixed array like this:
$images=[“‎⁨159847_744⁩.jpg”,“‎⁨159977_887⁩.jpg”];
then the two images are created.

Anyone an idea why this doesn’t work.

<?php
	$subpage = page("subpage");
	$strimgs="‎⁨159977_887⁩.jpg,159847_744⁩.jpg";
	$images=explode(",",$strimgs);
	//$images=["‎⁨159847_744⁩.jpg","‎⁨159977_887⁩.jpg"]; // this works, 2 files created
	foreach($images as $img){
            echo $img; // the echo is correct in both cases
		try{
			$file = File::create([
			   'source'     => kirby()->root('assets').'/images/'.$img,
			   'parent'     => $subpage,
			   'filename'   => $img,
			   'template' => 'image',
			   'content' =>[
			  		'caption' => '',
			  		'alt' =>''
			  ]
			]);
		}
		catch (Exception $error) { 
			echo $error; 
		}  
	}
?>

Try this: https://getkirby.com/docs/cookbook/forms/file-uploads#the-upload-controller

Hi Texnixe,
that’s not exactly what i need. I need to import data from a database in Kirby. The client should manage the site from now on in Kirby. So i have a .json file whith the content and the images are in the json-file like {“images”:“image1.jpg,image2.jpg”} and i have those files temporarely stored in my assets folder. I create the pages with page::create and i want to create the images with the function i mentioned above. But sometimes it works, sometimes it fails with the same content… I’m struggeling a time now with this. It’s always a hard one to get data in Kirby from a database.

I know it’s a different use case, I was just suggesting to try the other method ($page->createFile() instead of File::create(), the source of the file shouldn’t really make any difference.

no, everytime i get: Kirby\Exception\LogicException: The file could not be created :thinking:

do the images have to meet certain requirements?

Yes, what you set in your image.yml. If you limit sizes, mime types etc., these settings will be used when you try to create files.

On a side note, where do you authenticate?

I have no limits in the image.yml

now i use:
$kirby = kirby();
$kirby->impersonate(‘kirby’);

And still the same problem?

Ok, I read your first post again and if the images are created correctly if you pass a simple string, then there is probably a problem with how you get the array of image strings. How do you get them from your json?

It’s a very strange:
when i start with the a fixed array of images, it works
$images=[“‎⁨169570_16752⁩.jpg”,“‎⁨169590_16795⁩.jpg”];
foreach($images as $img){

when i start with a string and i make an array of it with code, it fails
$strimgs=“‎169570_16752⁩.jpg,169590_16795⁩.jpg”;
$images=explode(",",$strimgs);
foreach($images as $img){

Hm, I tested your code in a Starterkit (put the two images from one of albums into /assets/images, and the code snippet into the home template), like this:

home.php

$strimgs="abba.jpg,bird-reynolds.jpg";
$images=explode(",",$strimgs);
dump($images);
kirby()->impersonate('kirby');
foreach($images as $img){
  echo $img; // the echo is correct in both cases
  try {
      $file = File::create([
      'source'     => kirby()->root('assets').'/images/'.$img,
      'parent'     => page('photography'),
      'filename'   => $img,
      'template' => 'image',
      'content' =>[
        'caption' => '',
        'alt' =>''
      ]
      ]);
  }
  catch (Exception $error) { 
      echo $error; 
  }  
}

And it works without problems.

The only thing strange about your code above are the quotes around the strings, but I assume that’s a copy/paste thing? They are not correct and throw an error when I copy your code.

Do you validate the images before throwing them into the File::create() method?
I am thinking about

  • trim()
  • file_exists()

Did you check the php error logs for any hints?
If the file already exists (in your page) the method will also fail. Something I usually run into when testing with files in a lot of subfolders and I forget to remove all of them.

In case the image already exists, the error message is different, though (Kirby\Exception\LogicException: The file exists and cannot be overwritten…)

Good point.

If you dump($error) instead of echoing it, you should get more information, e.g. if the file has a size etc.

i dumped the error (below the first lines of it). I think there’s something with the images i’m using (protected). I don’t know if i can do something so the images can be written?

Kirby\Exception\LogicException Object
(
    [data:protected] => Array
        (
        )

    [httpCode:protected] => 400
    [details:protected] => Array
        (
        )

    [isTranslated:protected] => 
    [message:protected] => The file could not be created
    [string:Exception:private] => 
    [code:protected] => error.logic
    [file:protected] => /Users/kristofgevaert/Sites/sanderuswebsite/kirby/src/Cms/FileActions.php
    [line:protected] => 184
    [trace:Exception:private] => Array

The context for the error thrown in line 184 is this

  // overwrite the original
            if (F::copy($upload->root(), $file->root(), true) !== true) {
                throw new LogicException('The file could not be created');
            }

I can reproduce this error by providing a filename of a file that does not exist.

Those protected notes don’t mean that the file is protected but the properties of the LogicException object are protected.

Is there any information further down in this object, like size and dimensions?

This is what I get for a non-existing file:

 [0] => Kirby\Cms\File Object
                                (
                                    [root] => /Users/me/public_html/314/content/1_photography/abba.jpg
                                    [hash] => 416c6470189f155e16424b26f8524fc0
                                    [filename] => abba.jpg
                                    [name] => abba
                                    [safeName] => abba
                                    [extension] => jpg
                                    [size] => 0
                                    [niceSize] => 0 kB
                                    [modified] => 
                                    [mime] => image/jpeg
                                    [type] => image
                                    [isWritable] => 1
                                    [isReadable] => 
                                    [dimensions] => Array
                                        (
                                            [width] => 0
                                            [height] => 0
                                            [ratio] => 0
                                            [orientation] => 
                                        )

This is what’s in my error…

 [0] => Kirby\Cms\File Object
                                        (
                                            [root] => /Users/kristofgevaert/Sites/sanderuswebsite/content/3_our-catalogue/1_antique-maps/8_oceans/_drafts/antique-map-of-africa-by-scherer-heinrich/167477-11766.jpg
                                            [hash] => dc76bdd1d3c5bc7aaf93c1102461755e
                                            [filename] => 167477-11766.jpg
                                            [name] => 167477-11766
                                            [safeName] => 167477-11766
                                            [extension] => jpg
                                            [size] => 0
                                            [niceSize] => 0 kB
                                            [modified] => 
                                            [mime] => image/jpeg
                                            [type] => image
                                            [isWritable] => 1
                                            [isReadable] => 
                                            [dimensions] => Array
                                                (
                                                    [width] => 0
                                                    [height] => 0
                                                    [ratio] => 0
                                                    [orientation] => 
                                                )

                                            [exif] => Array
                                                (
                                                    [camera] => Array
                                                        (
                                                            [make] => 
                                                            [model] => 
                                                        )

                                                    [location] => Array
                                                        (
                                                            [lat] => 
                                                            [lng] => 
                                                        )

                                                    [timestamp] => 
                                                    [exposure] => 
                                                    [aperture] => 
                                                    [iso] => 
                                                    [focalLength] => 
                                                    [isColor] => 
                                                )

                                            [id] => our-catalogue/antique-maps/oceans/antique-map-of-africa-by-scherer-heinrich/167477-11766.jpg
                                            [template] => image
                                            [url] => http://localhost:8888/sanderuswebsite/media/pages/our-catalogue/antique-maps/oceans/antique-map-of-africa-by-scherer-heinrich/2548114547-0/167477-11766.jpg
                                            [content] => Kirby\Cms\Content Object
                                                (
                                                    [caption] => 
                                                    [alt] => 
                                                )

                                            [siblings] => Kirby\Cms\Files Object
                                                (
                                                )

                                        )

Before going too deep into possible bugs in the system, I suggest you make sure you have a valid source path for every file.

foreach($images as $img){
  try {

      // if the source file does not exist, echo the faulty path and continue with the next image
      $source = kirby()->root('assets') . '/images/' . trim($img);
      if (!file_exists($source)) {
         echo $source . " does not exist\n";
         continue;
      }

      $file = File::create([
         'source'     => $source,
         'parent'     => page('photography'),
         'filename'   => $img,
         'template' => 'image',
         'content' =>[
           'caption' => '',
           'alt' =>''
         ]
      ]);
  }
  catch (Exception $error) { 
      echo $error; 
  }  
}

ok, thanks, i test this and it seems my file doesn’t exists (i get the error “does not exist”)… although the image is in my assets-folder.
The image i am using is corrupt i presume.

You should be able to copy even a corrupt image…does the path look right?