So using the 'file' module i have added a field to the user table called 'user_files'. What i want to know if how can i programmatically add a file to the user, so that it is displayed on the users profile.

So far i am storing the file information locally and then targetting the database tables directly and inserting the data into them. This has been done correctly, but the file is not dispalying.

I am using file_save_data to store the file in the database. Then manually adding it to 'field_data_field_user_files', 'field_revision_field_user_files' and 'file_usage' tables.

Is there a simpler way to get this to work?

  • Do you want to add the files for existing users or newly created user?
    – msmani
    Jul 1, 2014 at 17:13
  • I think node_save() is the drupal function you need to look at.
    – SDMulroy
    Jul 1, 2014 at 19:10
  • You wwant to create a file field in the user and then a Jul 1, 2014 at 20:32
  • I want to be able to create it for existing users when they visit a dynamically built page, so node_save() isn't what im looking for. I know the callback and the area where to put the code, just want to know the best way to insert into the database to get it to work.
    – Key
    Jul 2, 2014 at 8:15

1 Answer 1


You first need to insert the file in the database, then assign it to your entity (a user in your case)

To insert file in the database say you have your file in a temp location. You can add it to the databse at the same time the file is moved to its final location:

// uid of user that to add the file.
$uid = $UID;

// Final file name
$filename = $FILENAME;

// Fieldname where to attach the file
$fieldname = $FIELDNAME;

// File temporary path.
$file_tmp_path = $FILE_TMP_PATH;

// Let's go!

// Load user object.
$account = user_load($uid);

// Gather file info.
$filesize  = filesize($file_tmp_path);
$mime_type = mime_content_type($file_tmp_path);

// Create file object.
$file = new stdClass;
$file->uid      = $uid;
$file->filename = <desired filename>;
$file->uri      = $file_tmp_path;
$file->filemime = $mime_type;
$file->filesize = $filesize;
$file->status   = FILE_STATUS_PERMANENT;

$destination .= '/' . $filename;

// Move to its final destination and add it to the database.
// file_move moves the file and is in charge of add the needed DB records.
$file = file_move($file, $destination, FILE_EXISTS_RENAME);

// Attach file to user. 
$account->{$fieldname}[LANGUAGE_NONE][0]['fid'] = $file->fid;


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.