function file_url_transform_relative

file_url_transform_relative($file_url)

Transforms an absolute URL of a local file to a relative URL.

May be useful to prevent problems on multisite set-ups and prevent mixed content errors when using HTTPS + HTTP.

Parameters

string $file_url: A file URL of a local file as generated by file_create_url().

Return value

string If the file URL indeed pointed to a local file and was indeed absolute, then the transformed, relative URL to the local file. Otherwise: the original value of $file_url.

See also

file_create_url()

Related topics

File interface
Common file handling functions.

File

core/includes/file.inc, line 248
API for handling file uploads and server file management.

Code

function file_url_transform_relative($file_url) {
  // Unfortunately, we pretty much have to duplicate Symfony's
  // Request::getHttpHost() method because Request::getPort() may return NULL
  // instead of a port number.
  $request = \Drupal::request();
  $host = $request->getHost();
  $scheme = $request->getScheme();
  $port = $request->getPort() ? : 80;
  if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
    $http_host = $host;
  }
  else {
    $http_host = $host . ':' . $port;
  }

  return preg_replace('|^https?://' . $http_host . '|', '', $file_url);
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!includes!file.inc/function/file_url_transform_relative/8.1.x