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