Apart from the staple file_save_data() function, we have a few other ones that can come in handy if we are dealing with managed files. Here's a few of them.
If we want to copy a file from one place to another while making sure a new database record is created, we can use file_copy(). It takes three parameters:
- The FileInterface entity that needs to be copied
- The destination URI where it should go
- The flag indicating what to do in case a file with the same name exists
The parameters are the same as for file_save_data().
Apart from the actual copying, this function also invokes hook_file_copy() which allows modules to respond to files being copied.
Very similarly to file_copy(), we also have file_move() that takes the same set of parameters but instead performs a file move. The database entry of the File entity gets updated to reflect the new file path. And hook_file_move() is invoked to allow modules to respond to this action.
Not strictly related to managed files but rather useful in all cases, we also have a file_prepare_directory() function which we can use to ensure the file destination is correct. It takes two arguments--the directory (a string representation of the path or stream URI) and a flag indicating what to do about the folder:
- FILE_CREATE_DIRECTORY : Will create the directory if it doesn't already exist
- FILE_MODIFY_PERMISSION : Will make the directory writable if it is found to be read-only
This function returns TRUE if the folder is good to go as a destination or FALSE if something went wrong or the folder doesn't exist.