On my site, we have a form which directly adds data into one content type. When user submits the form, all the field data is inserted. It's working fine except the Image field.

What I want is that the image field is automatically uploaded and is shown as automatically uploaded in the node admin. In the code below, I am providing a static image just to make it work and it still doesn't :(.

I have been banging my head on it for hours and hours and I'll be very thankful if you can provide me with any hope or solution ....

So with the following code, I've been able to upload the Image in the public://tmpprofiles folder. The problem is that file_copy is not working and throws an exception in error log that that

File http://yoursite.com/sites/default/files/tmpprofiles/anewimage.png could not be copied because it does not exist.

But it does exist!!!!

I don't why it is saying that. I guess it means that all the code is working except the last two lines. Those are the lines which will attach the image to the node and therefore would show this image as an uploaded image in the node admin.

Please discard my meh code if you've a better way of doing this.


  $path = './sites/default/files/animage.png';
  $filetitle = 'newimage';
  $filename = 'anewimage.png';

  $file_temp = file_get_contents($path);

  $file_temp = file_save_data($file_temp, 'public://tmpprofiles/' . $filename, FILE_EXISTS_RENAME);

  $tmp_file_path = 'public://tmpprofiles/' . $filename;

  $file_path = file_create_url($tmp_file_path);

  $file = (object) array(
    'uid' => 1,
    'uri' => $file_path,
    'filemime' => file_get_mimetype($file_path),
    'status' => 1,

  //These two lines don't work.

  $file = file_copy($file, 'public://another');      
  $new_moment_node->field_profile_photo[$new_moment_node->language][0] = (array) $file;

1 Answer 1


In Drupal 7 you can use system_retrieve_file()

As system_retrieve_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file_managed table if you want it to be managed.

Can you try this Save image from URL to a field from a custom module

  • This looks really helpful. I'll try it right now. Thanks a lot.
    – user219492
    Jun 17, 2014 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.