How to Copy Files in Drupal Using a Hook_update

Copy files easily on any environment without having to do it manually

Sergio Guardiola Herrador
2 min read2 days ago
Photo by Maksym Kaharlytskyi on Unsplash

There are many ways of copying files from one folder to another. The most common is to do it directly on the server.

In other cases, you might need to do it in several environments, which can be time-consuming as it’s not just copying and will probably involve downloading from other servers using scp for example.

Having a way to automate the process can save you time and avoid missing copying some of the files.

In this example, I’m copying images from the folder images of a custom module to the files public folder, in this case, sites/default/files/logos:

/**
* Implements hook_update_N().
*/
function my_custom_module_update_9001() {
// Define the source directory within the module.
$source_directory = DRUPAL_ROOT . '/modules/custom/my_custom_module/images/december2023';

// The directory within 'sites/default/files'.
$destination_directory = 'logos';

// Construct the destination path.
$destination = "public://$destination_directory/";

// Ensure the destination directory exists, create it if not.
$file_system = \Drupal::service('file_system');
$file_system->prepareDirectory($destination…

--

--

Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net