Using the Drupal 6 files table for uploads

Drupal 6 provides a files table for managing files in your custom modules, but the correct usage isn't well/obviously documented. The following code works best in my experience:

 $file = new stdClass();
 $file->filename = file_munge_filename(trim(basename($_FILES['files']['name'][$source]), '.'), $extensions);
 $file->filepath = $_FILES['files']['tmp_name'][$source];
 $file->filemime = file_get_mimetype($file->filename);
 $file->filesize = $_FILES['files']['size'][$source];
 $file->uid = $user->uid;
 $file->timestamp = time();
 drupal_write_record('files', $file);


  • Files with a status of FILE_STATUS_TEMPORARY will be deleted in the following cron run.
  • Files with a status of FILE_STATUS_PERMANENT are permanent.
  • file_munge_filename() requires that the $extensions variable is passed; it is purposefully created in the above function call.