27 April 2023

Load a file entity in Drupal 10 by using its Uniform Resource Identifier (URI). This snippet provides a simple code example that demonstrates how to load a file entity by URI and check if it was loaded successfully.

Source code viewer
  1. use Drupal\file\Entity\File;
  2.  
  3. // Replace "public://example.txt" with the URI of your file.
  4. $file_uri = 'public://example.txt';
  5.  
  6. // Load the file entity by URI.
  7. $file = File::loadByUri($file_uri);
  8.  
  9. // Check if the file entity was loaded successfully.
  10. if ($file) {
  11. // Do something with the file entity.
  12. }
Programming Language: PHP