How can I rename uploaded files programatically? (auto-rename image files) I am aware that the File Paths module allows administrators to use tokens to set patterns for renaming files, but as of writing (Jan 2015) there are more than 100 bugs in the queue and no updates to the dev version in almost one year.  (I also installed it and it and was unable to get it working.) So, I want to do this programmatically.

My goal is to rename all new user-uploaded image files on my Drupal 7 site to this pattern: [uid of logged in user][timestamp].extension.

Being able to rename them with the UID is very important because these files are often downloaded and exchanged (sent back and forth via email, without reference to Drupal), and we need an easy way to identify which user originally uploaded the file after it has been downloaded from the site.

I am using the Transliteration module. For inspiration, I also took a look at the File Entity Paths module, but it didn't provide me any insight.  I further consulted this article on file-naming best practices from Acquia but it provides no suggestions for doing this programmatically.
Assuming you are talking about the core file functionality, you can modify the filename in hook_file_presave() and modify the filename property.

function mymodule_file_presave($file) {
  $parts = pathinfo($file-&gt;filename);
  $file-&gt;filename = $file-&gt;uid . $file-&gt;timestamp . '.' . $parts['extension'];
}


Drupal will handle changing any other properties that need to be changed.

Some issues to be aware of:


Upload forms will expose the new name to the user after he clicks 'Upload'. It may be confusing to upload a file with a regular filename and see it changed to a string of numbers.
There is a note on the hook_file_presave documentation that the hook "doesn't distinguish between files created as a result of a copy or those created by an upload." If you do need to distinguish, check out the $file->source property or try calling menu_get_object() to figure out if the user is on a page with an upload form or not.
Consider using a dash between the uid and the timestamp for your naming convention. Your timestamps will all start with 1 (until 2033 anyway), and users with UIDs ending in 1 (e.g 11, 21, etc.) will make the filename confusing to read.