2
votes

I have the following code (which I found on the internet) to programmatically upload a profile picture unto an existing user account. I am however getting "duplicate entry" error.

I therefore thought I should first delete the existing photo (if any) before uploading the new photo. Or is there a better way of overwriting without getting the error below?

Error message:

DOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'http://www.example.com/sites/default/files/photo_gallery' for key 'uri': INSERT INTO {file_managed} (uid, uri, filemime, filesize, status, timestamp, type) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => 1302 [:db_insert_placeholder_1] => http://www.example.com/sites/default/files/photo_gallery/newphoto.png [:db_insert_placeholder_2] => image/png [:db_insert_placeholder_3] => 143769 [:db_insert_placeholder_4] => 1 [:db_insert_placeholder_5] => 1414500789 [:db_insert_placeholder_6] => image ) in drupal_write_record() (line 7202 of /home1/public_html/example/includes/common.inc).

Here is the code I am using:

$obj_tochange = user_load($user);
$image_path ='http://www.example.com/sites/default/files/photo_gallery/newphoto.png';     
$image_info = image_get_info($image_path);

// create file object
$file = new StdClass();
$file->uid = $obj_tochange->uid;
$file->uri = $image_path;
$file->filemime = $image_info['mime_type'];
$file->status = FILE_STATUS_PERMANENT; 
$file->filesize = $image_info['file_size'];

file_save($file);
$edit['picture'] = $file;
user_save($obj_tochange, $edit);
1

1 Answers

1
votes

You need to copy the file using file_copy before calling file_save. It should automatically change the file path if it matched any other file on server, therefore it will not throw this error.

$file = new StdClass();
// ..... your code as it is
$file = file_copy($file, 'public://', FILE_EXISTS_RENAME);
file_save($file);