Skip to content

Instantly share code, notes, and snippets.

@davereid
Created November 14, 2011 22:43
Show Gist options
  • Save davereid/1365457 to your computer and use it in GitHub Desktop.
Save davereid/1365457 to your computer and use it in GitHub Desktop.
file_get_uri_from_url()
<?php
function file_get_uri_from_url($url, $load_file = TRUE) {
$base_paths = &drupal_static(__FUNCTION__);
if (!isset($base_paths)) {
$base_paths = array();
foreach (file_get_stream_wrappers() as $scheme => $stream_wrapper) {
$class = file_stream_wrapper_get_class($scheme);
if (class_exists($class) && method_exists($class, 'getExternalUrl')) {
$wrapper = new $class();
$wrapper->setUri($scheme . '://');
$base_paths[$scheme] = $wrapper->getExternalUrl();
}
}
$base_paths = array_filter($base_paths);
}
foreach ($base_paths as $scheme => $base_path) {
if (preg_match('/^' . preg_quote($base_path, '/') . '(.+)$/', $url, $matches)) {
$uri = $scheme . '://' . $matches[1];
if ($load_file) {
if ($fid = db_query("SELECT fid FROM {file_managed} WHERE uri = :uri", array(':uri' => $uri))->fetchField()) {
return file_load($fid);
}
}
else {
return $uri;
}
}
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment