How to populate nodes with imagefield programmatically? I'm trying to do a mass import of images to drupal nodes in D7 and ended up with lots of funny entries in the table {files_managed}.

This is the code I use:

  chdir('/path/to/drupal/root');
  define('DRUPAL_ROOT', getcwd());
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $node = node_load(123);

  $dir = '/path/to/files';
  if ($handle = opendir($dir)) {

    while (false !== ($file = readdir($handle))) {
      $file_ext = pathinfo($file, PATHINFO_EXTENSION);

      switch ($file_ext) {
        case 'jpg':
        case 'gif':
        case 'JPEG':
        case 'jpeg':
        case 'png':
          $name_explode = explode("_", $file);
          $image_location =  $dir .'/'. $file;

          $file_temp = file_get_contents($image_location);
          $file_temp = file_save_data($file_temp, 'public://' . $file, FILE_EXISTS_RENAME);
          $node-&gt;field_ep_image = array(
            $node-&gt;language =&gt; array(
              0 =&gt; array(
              'fid' =&gt; $file_temp-&gt;fid,
              'filename' =&gt; $file_temp-&gt;filename,
              'filemime' =&gt; $file_temp-&gt;filemime,
              'uid' =&gt; 1,
              'uri' =&gt; $file_temp-&gt;uri,
              'status' =&gt; 1
              )
            )
          );
        break;
      }

    }

    closedir($handle);
  }


What is the correct way to populate an imagefield programmatically in D7?
I don't have the exact answer to your question, but you could check how other modules do it. Devel Generate for instance (part of Devel) can populate image fields. Check out devel_generate_fields() in devel_generate.fields.inc and image_devel_generate() in image.devel_generate.inc.

Hope that helps.