Drupal 6: How to Change Filename on Upload

I want to rewrite the file name when a user uploads a file. How on earth do you do that?

There appears to be very little documentation on this, so I present to you my solution, and an explanation of how I figured this out. Hopefully this will help a stranded Drupaler out there.

The Code Snippet

The following code will rewrite an uploaded file's filename from to 1234567890_<timestamp>, where "1234567890" is the timestamp.

Insert this into a custom module:

 * Implementation of FileField's hook_file_update().
 * This gets called after the file has been saved, and technically right AFTER writing to the database.
 * That's why we need to call drupal_write_record() to update the file record.
 * Too bad we can't use D7's file_save() :(
function MYMODULE_file_insert($file) {
  // change filename to <timestamp>_<filename> for absolute uniqueness, and replace spaces with '_'
  $new_filename = $file->timestamp . '_' . str_replace(' ', '_', $file->filename);
  $new_filepath = dirname($file->destination) . '/' . $new_filename;
  // $file is passed by reference
  if (file_move($file, $new_filepath)) {
    // update files table with new file information
    drupal_write_record('files', $file, 'fid');
 * Implementation of FileField's hook_file_update().
function MYMODULE_file_update(&$file) {
  if (!empty($file->fid)) {
 * Implementation of FileField's hook_file_delete().
function MYMODULE_file_delete($file) {
    // add any special delete processing here

Replace "MYMODULE" with your module's name.

If you're not sure how to make a custom module, read this tutorial.

Example Usage

CCK FileField module must be installed. In my case, I'm using Video module's Uploadfield, but any Filefield (including ImageField) will do.

In this example, a user is prompted to upload a file, let's say Bear.wmv.


When they click "Upload", the file is actually saved as 1298410169_Bear.wmv, which is of the format <timestamp>_<filename>.


How It Works

Seems simple enough, right? The thing is, FileField, by default, doesn't allow us to do this. Let's dig deeper into what's going on.

FileField works like this:

A CCK field is created that uses the AHAH uploader widget.

CCK Manage fields

This creates an AHAH Uploader form that saves the file in the "files" table.

files table

What else is happening? Let's add some fact-finding code to a custom module. If Devel module is enabled, we can use the dsm() function call to learn more.

The form is rebuilt when the file upload is returned. We can check this by implementing hook_form_alter() in a custom module:

 * Implements hook_form_alter().
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'page_node_form':
      $form['#after_build'][] = '_mymodule_video_after_build';
function _mymodule_video_after_build($form, &$form_state) {
  return $form; // don't forget return value!

This bit of code is adding an #after_build function to the form, which outputs $form and $form_state in a dsm() call.

We notice that when you upload a file by clicking "Upload", the dsm() messages display right above the File field.

dsm() messages

Expand the second array, then "values", and find the "file" field type that you set up, in this case "field_example_file". We then see all the values that are associated with the file.


It looks like "filename", "filepath", and "destination" are all the fields we want to modify. But how do we intercept FileField's upload process, and insert our modifications?

Turns out, there's actually some hooks that FileField module introduces that you can override. They're not available to view in the Drupal API, but we can find them if we search implementations in a contrib API like the Lullabot API. They are:


The documentation's pretty light. So, where to start? The FileField Meta module has a great example implementation that we can copy. We can examine it by using the Lullabot API or opening the file itself. Lullabot API links:

The code itself is located within the filefield/ module folder. If you look at filefield/filefield_meta/filefield_meta.module around Line 73, you'll see this:


 * Implementation of FileField's hook_file_insert().
function filefield_meta_file_insert(&$file) {
  if (!empty($file->fid)) {
    $record = array_merge($file->data, array('fid' => $file->fid));
    drupal_write_record('filefield_meta', $record);

 * Implementation of FileField's hook_file_update().
function filefield_meta_file_update(&$file) {
  if (!empty($file->fid)) {

 * Implementation of FileField's hook_file_delete().
function filefield_meta_file_delete($file) {
  db_query('DELETE FROM {filefield_meta} WHERE fid = %d', $file->fid);

Okay, that tells us something. filefield_meta_file_insert() is taking the $file object by reference and running it's own function, filefield_meta(), on it. That's where we'll want to add our modifications. Now, a tricky part is that hook_file_insert() actually is fired just AFTER the file is inserted. This means that the files table has already been written. That's why drupal_write_record() is called by the filefield_meta implementation. We're actually going to modify the file and then update the file record. Drupal 7 has a really neat hook called file_save() which unfortunately we can't use. So, we have to use drupal_write_record().

Let's add a dsm() right in our MYMODULE_file_insert(), this will show us what fields we have available.

function MYMODULE_file_insert($file) {
  // output file object

If you add a file again, you should see a third message at the top, which says (Object) stdClass. That's our file object. Expanding that show us all the field we have available:

file object

Since the file is already saved, we're going to call file_move() here. file_move() accepts a $file object by reference, and updates it.

Breaking down our implementation in the snippet:

$new_filename = $file->timestamp . '_' . str_replace(' ', '_', $file->filename);

We're taking the file object's timestamp and appending it to the filename. I added in an extra bit that replaces any space characters with underscores. This could be useful for, say, ImageField module, because some WYSIWYG uploaders don't like space characters.

$new_filepath = dirname($file->destination) . '/' . $new_filename;

This line takes the current directory that the file is sitting in (using PHP's dirname()) and appends the new filename to it.

Next we call file_move(). It accepts the file object by reference, and updates it accordingly. It also handles renaming the file if there's a duplicate, etc.

if (file_move($file, $new_filepath)) {
  // update files table with new file information
  drupal_write_record('files', $file, 'fid');

If the move was successful, we call drupal_write_record() to update the database.

At this point the file is properly moved and the database updated. And we're done!

file renamed

How to Only Modify Some Uploaded Files

This solution modifies every file upload. What if we only wanted to modify a specific CCK field? We can use the $file object's "source" value.

If you look at the example above, the source value for my file field is "field_example_file_0". So, we can add an IF statement to our code to only target uploads to that field.

function MYMODULE_file_insert($file) {
  if ($file->source == 'field_example_file_0') {
    // change filename to <timestamp>_<filename> for absolute uniqueness, and replace spaces with '_'
    $new_filename = $file->timestamp . '_' . str_replace(' ', '_', $file->filename);
    $new_filepath = dirname($file->destination) . '/' . $new_filename;
    // $file is passed by reference
    if (file_move($file, $new_filepath)) {
      // update files table with new file information
      drupal_write_record('files', $file, 'fid');

And that's all there is to it! I hope you found this write-up helpful. If there's any questions about my implementation, I'd be happy to answer them.


Mikael Brandin's picture

Great article! Just what I was looking for.

wjones's picture

Cool! I'm still surprised no one had written a post about this before... it seems really desirable.

Ron Williams's picture

There is a very useful module called FileField Paths that allows rewriting of filenames based on tokens on a per-field basis.

Ron Williams

Alex's picture

Awesome Work!
Thank you for this tutorial. I searched the last 3 weeks for this solution.

My main task was to scale the "original"-image down to 600x600, to safe space.

function MYMODULE_file_insert($file) {
$path = dirname($file->destination) . '/'.$file->filename;
$width = 600;
$height = 600;
image_scale($path, $path, $width, $height);

//... tutorialcode ...

richard d's picture

thanks. I'm just learning drupal and this info was helpful. FAPI is a pita for a noob like me.

Brian Shensky's picture

I'm thinking you just instructed me on to write a custom module that allows me to pass a file that was uploaded to a "slave" server along to a "master" server in a multi-node server cluster that uses one-way master-to-slave local-filesystem replication. (see: lsyncd and csync2)

How: Easy - write the hook_file_insert() code that checks the current server's IP and, if not the master server's IP, scp that file to the master, so it can replicate it "back" to ALL the other slave nodes.

Yeah, it's a little hacky, but it beats having to care for and feed a GlusterFS implementation all for the sake of an occasional file upload.

wallens's picture

I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit.
hungry shark evolution hack.apk

wallens's picture

Most of the time I don’t make comments on websites, but I'd like to say that this article really forced me to do so. Really nice post!
real racing 3 hack android

Anonymous's picture

Thanks for sharing the info,but I have to say that Software Tailor is always so helpful. They give us suppot both in technology and spirit.Please find Software Outsourcing HK

Brendon George's picture

Oh thank you so much for that code. I am an armature programmer. I was searching for this all over internet. I searched a lot in Google codes. I could not find anything there. But at last, I found it here. I thank you for posting about it.
more here

ram14's picture

Apple products are revered for its quality, precision and great design. SRSG started its operations as Apple technology partners in the year 1997.
Apple service center Mumbai
Apple product dealers in Kolkata
AVID pro tools dealers

lamountgoff's picture

You've shared an essential code that could help my project to be finish soon. Thanks a lot for the share. how to get more instagram followers

Loki's picture

Paket internet bolt saat ini semakin diminati karena ada banyak sekali yang ingin merasakan internet berkecepatan tinggi dari bolt. Jika anda tertarik dengan paket internet ini anda bisa membeli paket internet ini secara online dari internet Jual Pulsa Bolt . Untuk menemukan website jual paket internet bolt silahkan buka silahkan baca selengkapnya .
Apakah anda suka melakukan taruhan bola saat menonton pertandingan bola? Untuk itulah saat ini hadir sangat banyak situs bandar bola untuk mengakomodir taruhan anda. Ini akan membuat setiap pertandingan semakin seru. Tapi jangan berlebihan ya. agen bola online terpercaya di indonesia . Info daftar situs agen judi bola lainnya silahkan baca kunjungi website kami .
Saat ini semakin banyak yang mencari kostum badut untuk memeriahkan acara mereka. Jika anda bingung; maka anda bisa memesan kostum badut ini dari jasa jual kostum badut yang saat ini sedang marak di kota bandung. Jual kostum badut . Silahkan cek koleksi kostum badut lainnya silahkan baca selengkapnya .
Bassura city adalah kawasan super blok dengan fasilitas lengkap untuk apartemen di bassura city. Kawasan ini dilengkapi dengan mall dan banyak fasilitas lainnya anda bisa mendapatkan hunian yang dekat dari pusat perbelanjaan sehingga anda tidak akan repot lagi Bassura City . Lihat aneka penawaran bassura city hanya di sini lihat penjelasan lengkapnya .
Jika anda merlukan batu bata merah untuk membuka usaha; maka anda bisa membeli mesin cetak batu bata merah dari kami. Produk mesin cetak batu bata merah ini sudah teruji dan kualitasnya terjamin. Anda bisa melihat spesiifikasinya dari web kami Jual mesin cetak batu bata merah . Untuk melihat contoh dari mesin cetak bata merah ini silahkan ke website ini baca artikel .
Apakah anda membutuhkan baju gamis? Saat ini telah hadir gamisaddawam yang bisa membantu anda mendapatkan busana muslim yang terbaik untuk anda. Ini adalah sesuatu yang bisa memudahkan anda para penggemar gamis dengan model terbaru. Jual Busana Muslim Modern . Koleksi busana muslim dan gamis terlengkap kami bisa cek di sini. lihat penjelasan lengkapnya .
Saat ini semakin banyak peminat dari motogp dan oleh karena itu kami hadir untuk memberikan info motogp terbaru untuk peminatnya. Sekarang anda bisa membaca berbagai info terbaru dari dunia motogp yang kami berikan setiap hari. Berita Terbaru MotoGP 2015 . Jika anda menyukai info moto GP terbaru silahkan kunjungi halaman ini. kunjungi blog .
Saat ini pendidikan semakin penting dan oleh karena itu anda memerlukan bantuan untuk mengarahkan anak-anak dalam belajar di rumah. Untuk ini anda bisa memanfaatkan jasa les privat sehingga anda bisa mendapatkan pemahaman yang lebih. Guru privat . Dapatkan guru les privat terpercaya di Jakarta; Bogor; Depok; Tangerang; Bekasi. read more .
Apakah anda memerlukan aneka mesin untuk membangun usaha anda. Kami menawarkan aneka mesin yang bisa anda pakai dalam menjalankan usaha. Baik itu mesin percetakan; mesin hitung, mesin pertanian dan masih banyak lagi. Semua mesin kami jual online Jual mesin . Jika anda membutuhkan mesin percetakan; mesin pemotong; mesing hitung dan lain sebagainya hubungi kami. click here .
Baju muslim adalah busana yang didesain dengan nuansa yang alami. Anda bisa melihat perkembangan trend busana muslim yang semakin merebak di mana-mana. Jadi anda juga bisa ikut serta dengan membeli gamis untuk anda gunakan. Jual gamis syar’i murah model terbaru yang berkualitas . Dapatkan model jilbab dan gamis syar'i terbaru di sini. download di sini .
Apakah anda penggemar film box office terbaru? Kami menawarkan banyak film terbaru yang bisa anda download secara gratis dari website kami. Jadi silahkan mampir dan download gratis film-film yang anda sukai dari link yang kami sediakan download film terbaru . Jika anda ingin download film sekarang silahkan kunjungi silahkan baca selengkapnya .
Jika anda adalah pengguna android. Anda pasti ingin mengetahui seluk beluk dari gadget anda tersebut. Jadi untuk itulah telah hadir blog tutorial android dan download apk untuk memaksimalkan smartphone android anda APK Terbaru . dapatkan file APK terbaru hanya di sini kunjungi website kami .
Apakah anda memerlukan busana muslim yang sesuai syar'i atau gamis? Di sini kami memberikan banyak penawaran aneka ragam model yang bisa anda pilih dan anda jadikan koleksi busana muslim anda. Semuanya kami tawarkan dengan harga murah pusat grosir baju muslim gamis murah bandung . Silahkan memilih koleksi grosir busana muslim kami silahkan baca selengkapnya .
Saat ini semakin banyak orang yang membangun usaha di rumah dan itu bisa membantu mereka mendapatkan penghasilan tambahan. Jika anda memerlukan penghasilan tambahan anda bisa ikut melakukan usaha di rumah anda dengan model kecil Sukses Usaha dirumah . Baca profil usaha rumahan ini dan kenali potensinya download di sini .
Apakah anda sedang mencari cartridge atau kosongan untuk printer anda? Kami menyediakan cartridge printer bekas; karena yang baru mungkin terlalu mahal untuk anda. Dengan penawaran harga yang sangat miring dan bisa terjangkau kantong anda. Jual Spare Part dan Tinta Printer Murah . Silahkan beli cartridge kosongan dari printer di sini silahkan baca selengkapnya .
Playstation adalah konsol permainan yang saat populer saat ini. Saat ini seri playstation sudah sampai PS 4; tapi PS 2 dan PS 3 masih laris. Jika anda membutuhkan konsol PS 2 ataupun PS 3 anda bisa mendapatkannya dari sini harga ps2  . beli playstation harga bersaing hanya di sini kunjungi website kami .
Apakah anda membutuhkan kredit mobil? Kami dari Astra Credit Company ACC siap melayani anda. Anda bisa mendapatkan pembiayaan kredit mobil toyota; daihatsu; dan honda dari kami; dengan bunga yang rendah dan layanan bersaing. kredit mobil honda . Silahkan cek penawaran kredit yang kami miliki di sini click here .
Genteng adalah bahan atap yang sudah sangat terkenal sejak dahulu kala. Ada genteng yang terbuat dengan bahan tanah liat press. Anda bisa membeli genteng ini dengan menghubungi penjual genteng baik itu secara online ataupun melalui telepon jual genteng press tanah liat harga murah . jual genteng press tanah liat yang ada di sini. download di sini .
Saat ini ada banyak sekali penginapan di kota depok yang ditawarkan dengan harga murah. Anda bisa mendapatkan penginapan-penginapan dengan harga murah ini di hotel ataupun apartemen sewa harian. Silahkan cek penginapan di kota depok. Penginapan Murah Di Depok . Jika anda butuh penginapan murah baca info berikut download di sini .
apakah anda membutuhkan busana muslim? Baik itu jilbab atau gamis murah sesuai syar'i semuanya tersedia. Anda bisa memesan baju muslim dan baju gamis murah ini dari internet. Jilbab instant juga tersedia bagi anda yang mau praktis. Jual Jilbab murah online . silahkan cek koleksi jilbab cantik kami silahkan baca selengkapnya .
Saat ini pemerintah karimun jawa sedang berbenah untuk meningkatkan pariwisata di daerah mereka; dan anda bisa mendapatkan banyak penawaran wisata karimun jawa dari berbagai travel. Dapatkan info lengkap wisata di karimun jawa hanya di sini karimun jawa . cek foto daerah di karimun jawa di sini kunjungi website kami .
Jika anda memerlukan alat yang bisa memperbesar kelamin atau alat vital atau kejantanan pria; maka saat ini ada pompa vakum yang bisa anda pakai untuk memijat dan memperbesar kelamin pria secara bertahap. Dapatkan produk ini di sini alat pembesar alat vital pria . cek manfaat dari pompa pembesar kelamin pria di sini silahkan baca selengkapnya .
crystal x asli nasa semakin banyak ditawarkan dan saat ini ada semakin banyak orang yang memesan crystal x asli nasa ini secara online. Anda bisa mendapatkan produk ini secara online dari agen resmi nasa yang membuka blog pribadi. crystal x asli nasa . dapatkan produk crystal x asli di sini lihat penjelasan lengkapnya .
Saat ini semakin banyak produk untuk membantu pasangan suami isteri dalam berhubungan intim. Biasanya untuk variasi dalam hubungan pasangan suami isteri bisa menggunakan alat bantu seksual yang saat ini banyak dijual online di website alat bantu seksual untuk pria . cek berbagai produk alat bantu seksualitas pria di sini silahkan baca selengkapnya .
Saat ini semakin banyak obyek wisata yang muncul di mana-mana, obyek wisata ini memberikan wahana baru bagi para wisatawan; salah satunya adalah obyek wisata goa pindul yang merupakan wisata alam. Ada wifi di dalam goa pindul. Goa pindul . baca info lengkap wisata di goa pindul di sini kunjungi website kami .
Jika anda tertarik untuk medapatkan banyak pakaian wanita atau tas sepatu wanita; atau sepatu dan aksesoris wanita; anda bisa memesannya dari kami di sini. Situs jual online produk fashion wanita yang sudah berpengalaman di bidang ini jual aksesoris dan tas online . Anda juga bisa belajar aneka trik dasar SEO dan cara membuat blog dengan benar agar anda bisa mendapatkan hasil yang baik. Jika anda ingin belajar cara membuat blog; maka anda bisa mempelajarinya dari blog tutorial dasar SEO dan blog yang menyediakan panduan bertahap. tutorial seo bertahap yang cukup mudah .

Ralph L Hofmeister's picture

Many essay writers are good and they always have something special for the students. So, if you are a student and looking for better contents for your essays these writing companies reviews on topreview4you.com can help you in this regard. So always try to have the best essays and secure the best grades.

Satans Nipples's picture

Do you cock munchers really think this kind of lame SEO still works.

embossitworld's picture

I have a hard time describing my thoughts on content, but I really felt I should here. Your article is really great. I like the way you wrote this information.
Technology news

celen's picture

I simply discovered your web journal and needed to say that I have truly appreciated scanning your blog entries. much obliged for offering. Amazon.com

govindchavan's picture

Numerous article journalists are great and they generally have something uncommon for the understudies. buy facebook ratings

nimiparker's picture

Basically want to say I am ecstatic that i came upon your web site!

nimiparker's picture

Very interesting article. I would love to read the book “Start with Why”, by Simon Sinek. I think he has taken a great to

codyerin's picture

i just wanted to i would like to show some gratitude to this kind of. the item allowed me to quite a lot which has a venture i recently done. to start with i tried just using simplexml to read some sort of 400mb xml record as well as well, php had not been having your. today it could create 20k data files but it removes all of them whether it is performed in addition to anything is actually functioning fantastic. many thanks!
www.oaklandreal-estate.org |

codyerin's picture

You should comment on the competition comparison of the blog. You can highlight it's mind boggling. Your blog exploration/tour will broaden your conversions.

Loren's picture

That was a truly worthwhile read. Please keep updating your blog with more such attention grabbing posts. I liked the way you introduced pictures apt for the content to explain things better. Thanks for such a nice update.
www.htceducation.org |

philipshaun's picture

Haarscheurtjes zijn normaal als een band wat ouder wordt en vormen geen gevaar, het is geen teken dat de band direct vervangen moet worden.
meridianwomenhealth |

Anonymous's picture

I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. 
Numa Travels |

Anonymous's picture

I think this is definitely an amazing project here. So much good will be coming from this project. The ideas and the work behind this will pay off so much.
Virtual and Smalll Business |

best custom essays's picture

I just want to tell that this is an awesome blog post. Really enjoying each stuff you shared here. I have also seen that most of them here shared some best custom essays tips, tricks and some helpful resources list.

Add new comment