Working with unmanaged files

Working with unmanaged files is actually pretty similar to doing so with managed files, except that they are not tracked in the database using the File entity type. There is a set of helper functions similar to what we've seen for managed files that can be accessed through the FileSystem service I mentioned earlier. Let's see some examples.

To save a new file, we do almost like we did before with managed files:

$image = file_get_contents('products://tv.jpg'); 
// Load the service statically for quick demonstration. 
$file_system = \Drupal::service('file_system'); 
$path = $file_system->saveData($image, 'public://tv.jpg', FileSystemInterface::EXISTS_REPLACE);  

We load the file data from wherever and use the saveData() method on the service the same way as we did file_save_data(). The difference is that the file is going to be saved but no database record is created. So the only way to use it is to rely on the path it is saved at and either try to access it from the browser or use it for whatever purpose we need. This method returns the URI of where the file is now saved or FALSE if there was a problem with the operation. So if all went well with the previous example, $path would now beĀ public://tv.jpg.

And just like with the managed files, we also have a few other helpful methods in that service, such as move(), copy(), and delete(). I recommend you inspect that service to get more details on how these work.