Save a managed file with cURL I want to save a managed file from an external site. Previously, I've used this code:

$managed = TRUE; // Whether or not to create a Drupal file record
$image_file = system_retrieve_file($product['img'], 'public://product-img-' . time() . '.jpg', $managed);
if ($image_file) {
  $file = file_load(db_query('SELECT MAX(fid) FROM {file_managed}')-&gt;fetchField());
  $item['field_image']['und'][0] = (array) $file;
}


However, it's throwing 403 errors for me so I decided to use cURL in my PHP code to get this image:

$ch = curl_init('http://g02.a.alicdn.com/kf/HTB15eliFVXXXXbKaXXXq6xXFXXXa/Original-Blackberry-Z10-Dual-Core-4-2-TouchScreen-2GB-RAM-16GB-ROM-8MP-Camera-Blackberry-os.jpg');
$fp = fopen('test.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);


With cURL, it works correctly, and I can get the image. How can I save this data as a Drupal managed file?
file_save_data() will take the contents of a file and place into a location specified by a file URI. In your example, you can take your downloaded test.jpg, retrieve its contents, and have file_save_data() do the rest.

// Assuming same cwd where curl &amp; fopen was executed.
$image_file = file_save_data(file_get_contents('test.jpg'), 'public://test.jpg', FILE_EXISTS_REPLACE);

// test.jpg will be placed/overwritten into your managed file system.
// $image_file contains the Drupal file object.