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 250
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);
}
doc_Drupal
2016-10-29 09:14:19
Comments
Leave a Comment

Please login to continue.