4

I am trying to cache in the server the profile images provided by the Facebook Graph API. So far what I did unsuccessfully was getting the path of the image then calling:

$file = file_save_upload($big_pic_url, array(), $dest, FILE_EXISTS_RENAME);

This returns NULL every time. I tried several syntax for the destination path, and also for the Pic URL path, nothing seems to work.

I am doing this the right way? Can file_save_upload() take an external link as part of its argument?

5

Here is a solution I've used recently for a Facebook module. Set the image path to $path variable (ie. http://graph.facebook.com/username/picture). Then do the following to store it via Drupal's managed file system:

$image = file_get_contents($path); // this is a PHP function to get a string representation of the image file

$destination = 'public://path/to/store/this/image/name.jpg'; // a stream wrapper path where you want this image to reside on your file system including the desired filename

$file = file_save_data($image, $destination, FILE_EXISTS_REPLACE);

if (is_object($file)) { // if you get back a Drupal $file object, everything went as expected so make the status permenant
   $file->status = 1;
   $file = file_save($file);
}
4
  • 2
    It works if file_get_contents() accept a URL; in some PHP installations, file functions are not allowed to use a URL as filename. – kiamlaluno Aug 11 '11 at 17:15
  • Yes you're exactly right about that. I have no idea how to do it otherwise... sorry! – mattacular Aug 11 '11 at 18:49
  • 1
    You can use others options like fopen() or curl Reading a Remote File Using PHP – tostinni Aug 11 '11 at 19:18
  • Ok thanks Matt, file_get_content works form the server so that will do perfectly. – silkAdmin Aug 11 '11 at 22:23
1

This is the function I am using and that works.

function get_external_image($url) { 
    $external_image = file_get_contents($url);
    $parsed_url = parse_url($url);
    $name_dest = rand(1000,9999)."_". basename($parsed_url["path"]);
    $file = file_save_data($external_image, 'public://'.$name_dest , FILE_EXISTS_REPLACE);
    if (is_object($file) && file_exists($file->uri)) {
        $file->status = 1;
        $file = file_save($file);
        drupal_write_record('file_usage', $file);
        return (array) $file;
    }
    return null;
}

This is an example on how to use it.

// Load your node.
$node = node_load("9999");
// Assign your image.
$node->field_image[$node->language]['0'] = get_external_image("http://cdn.sstatic.net/drupal/img/logo.png");
// Save your node.
node_save($node);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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