blog-banner

Drupal - Updating File name

  • Drupal 7
  • Drupal Planet
  • FILE API

If you know the file id, it is really simple,
Code:

$file = file_load($fid);
file_move($file, 'public://new_file_name);

How it works:

We need a source file object to move the file to the new location and update the file's database entry. Moving a file is performed by copying the file to the new location and then deleting the original. To get source file object, we can use file_load() function.
file_load($fid) - loads a single file object from the database
$fid - file id
return object representing the file, or FALSE if the file was not found.

After that, we can use the file_move() function to move the file new location and delete the original file.

file_move($file, 'public://new_file_name)

Parameter1 - Source File Object
Parameter2 - A string containing the destination that $source should be moved to. This must be a stream wrapper URI.
Parameter3 - Replace behavior (Default value: FILE_EXISTS_RENAME)

For more details, check here.

Get awesome tech content in your inbox