I have a drupal module that requires other files from the web. Is it possible for the module to download these files as its being activated?
Assuming PHP is configured to allow remote file access (see allow_url_fopen
) and the module directory have write permissions, you can download any needed files in hook_enable
or, probably even better, hook_install
.
The Drupal Way is to the use the File Interface and the install hooks:
hook_enable()
: fires when a module is enabled.hook_install()
: fires when a module is installed.hook_requirements()
: informs the user whether the requirements for the module have been met.
If the file only needs to be downloaded once, it's probably better to use hook_install()
and use hook_requirements()
to provide feedback on whether it worked. If you need fresh data every time the module's enabled, opt for hook_enable()
.
In terms of downloading files, use whatever PHP method you want. If you need to use an external library, either put it within your module's directory and use include
and/or require
, or consider using the Libraries API, which aims to provide a central repository for third-party scripts and libraries.
Once you have the file data, you'd use the File Interface. Modules have access to the files directory of a site (defined in Site configuration -> File system). You'd first create your own directory under it using file_create_path()
, then save data to it using file_save_data()
. Check out the rest of the File Interface API documentation for other things you can do.
Then, once it's saved, just check to see if the data's available with file system using file_check_location()
and access it with file_get_contents()
or include/require
.