hook_file_url_alter

hook_file_url_alter(&$uri)

Alter the URL to a file.

This hook is called from file_create_url(), and is called fairly frequently (10+ times per page), depending on how many files there are in a given page. If CSS and JS aggregation are disabled, this can become very frequently (50+ times per page) so performance is critical.

This function should alter the URI, if it wants to rewrite the file URL.

Parameters

$uri: The URI to a file for which we need an external URL, or the path to a shipped file.

Related topics

Hooks
Define functions that alter the behavior of Drupal core.

File

core/lib/Drupal/Core/File/file.api.php, line 57
Hooks related to the File management system.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function hook_file_url_alter(&$uri) {
  $user = \Drupal::currentUser();
 
  // User 1 will always see the local file in this example.
  if ($user->id() == 1) {
    return;
  }
 
  $cdn_extensions = array('css', 'js', 'gif', 'jpg', 'jpeg', 'png');
 
  // Most CDNs don't support private file transfers without a lot of hassle,
  // so don't support this in the common case.
  $schemes = array('public');
 
  $scheme = file_uri_scheme($uri);
 
  // Only serve shipped files and public created files from the CDN.
  if (!$scheme || in_array($scheme, $schemes)) {
    // Shipped files.
    if (!$scheme) {
      $path = $uri;
    }
    // Public created files.
    else {
      $wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
      $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
    }
 
    // Clean up Windows paths.
    $path = str_replace('\\', '/', $path);
 
    // Serve files with one of the CDN extensions from CDN 1, all others from
    // CDN 2.
    $pathinfo = pathinfo($path);
    if (isset($pathinfo['extension']) && in_array($pathinfo['extension'], $cdn_extensions)) {
      $uri = $cdn1 . '/' . $path;
    }
    else {
      $uri = $cdn2 . '/' . $path;
    }
  }
}
doc_Drupal
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.