How to programmatically add image from external URL using media module? I want to programmatically add an image from an external URL and have the module store and display a local copy of the image. How can I do that? Normally, I would click the "select media" button while creating a new node but I want to do it through code.
Make sure your php.ini allows allow_url_fopen. Then you can use something like this in your module:

$image = file_get_contents('http://drupal.org/files/issues/druplicon_2.png'); // string
$file = file_save_data($image, 'public://druplicon.png',FILE_EXISTS_REPLACE);


Use php's file_get_contents() function 

http://www.php.net/manual/en/function.file-get-contents.php

and then use Drupal API's file_save_data()

http://api.drupal.org/api/drupal/includes--file.inc/function/file_save_data/7

Then you should be able to call it using and save it to a node etc ..

$node = new stdClass;
$node-&gt;type = 'node_type';
node_object_prepare($node);
$node-&gt;field_image[LANGUAGE_NONE]['0']['fid'] = $file-&gt;fid;
node_save($node);




Edit: 

As pointed out in the comments, you can use function system_retrieve_file
See: https://api.drupal.org/api/drupal/modules!system!system.module/function/system_retrieve_file/7