You are here

function file_url_transform_relative in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 core/includes/file.inc \file_url_transform_relative()

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

3 calls to file_url_transform_relative()
EditorImageDialog::submitForm in core/modules/editor/src/Form/EditorImageDialog.php
Form submission handler.
UrlRewritingTest::testRelativeFileURL in core/modules/system/src/Tests/File/UrlRewritingTest.php
Test file_url_transform_relative().
_filter_html_image_secure_process in core/modules/filter/filter.module
Process callback for local image filter.

File

core/includes/file.inc, line 265
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);
}