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}')->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);

With cURL, it works correctly, and I can get the image. How can I save this data as a Drupal managed file?

1 Answer 1


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 & 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.
  • I did it before your asnwer with $file_name = 'public://product-img-' . time() . '.jpg'; $file_content = file_get_contents($product['img']); $file_temp = file_save_data($file_content,$file_name); ym($file_temp,'message'); if($file_temp){ // $file = file_load(db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField()); $item['field_image']['und'][0] = (array) $file_temp; }. exactly something like your answer
    – Yuseferi
    Jul 15, 2016 at 17:02

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.