I'm trying to force replacement of existing file with same name, if a new version is uploaded by user. I've seen a lot of posts about this topic but none that I could find addresses how to force the replacement.

I'm using a custom form, and here's the code I've been trying to make work during the form validation:

  $file = file_save_upload(
        'file_validate_is_document' => array(), // Validates file is really a document.
        'file_validate_extensions' => array('pdf doc ppt pps avi mpg mov wmv'), // Validate extensions.

The revised file (let's say "file.jpg") is uploaded, but inevitably Drupal creates a new copy and renames it file_0.jpg, file_1.jpg, etc for each new version.

I even tried to programmatically delete the original file using "file_delete" prior to committing the upload but I still get the copy!

Any help would be appreciated.

3 Answers 3


This is drupal's default behaviour and a known issue. It has been addressed a couple of ways.

The Upload File Replace module addresses this issue by swapping the filenames so the new file retains the original name.

The Media Update module allows in situ replacement of media files (part of the Media project).

You could either make use of one of these modules, or use them as a model for your own function.

  • Perfect, thanks @triskelion for all the options. I ended up using the Upload File Replace. Mar 30, 2013 at 22:41

I managed to make it work using the following code.

$file = file_save_upload('file', $validators);
// If the file passed validation:
if ($file) {
    if ($file = file_move($file, 'public://', FILE_EXISTS_REPLACE)) {
        // Save the file for use in the submit handler.
        $form_state['storage']['file'] = $file;
    } else {
        form_set_error('file', t('Failed to write the uploaded file to the site\'s file folder.'));
} else {
    form_set_error('file', t('No file was uploaded.'));
$file_temp = file_save_data($attachment->data, 'public://<my_files_locatioin>/<my-filename.pdf>' , FILE_EXISTS_REPLACE);

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.